/// <summary>
    /// Saves the assignment data in a hashtable and creates a new assignment and adds it to the AssignmentObject.
    /// </summary>
	public override void FinalizeAssignment () {
		Hashtable h = new Hashtable ();
		h.Add ("photosNeeded", Int32.Parse(assignmentMaker.typeInputField.text));
		h.Add ("missionDescription", assignmentMaker.descriptionField.text + ". " + assignmentMaker.assignmentExplanation.text);
		Assignment newCameraAssignment = new Assignment (0,"Camera", h);
		assignmentMaker.assignmentObject.AddAssignment(newCameraAssignment);
	}
 public void ShouldParseSimpleAssignment()
 {
     var assignment = new Assignment(new[] {new Variable("a")},
         new[] {new ConstantExpression(Constants.One)}, false);
     var expected = new StatementBlock(assignment);
     Assert.AreEqual(expected, SyntaxParser.Parse("a = 1"));
 }
 public void ShouldParseMultipleAssignments()
 {
     var assignment = new Assignment(new[] { new Variable("a"), new Variable("b") },
         new[] { new ConstantExpression(Constants.One) }, true);
     var expected = new StatementBlock(assignment);
     Assert.AreEqual(expected, SyntaxParser.Parse("local a,b = 1"));
 }
예제 #4
0
        /// <summary>
        /// Gets the time phase data.
        /// </summary>
        /// <param name="assignment">The assignment.</param>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public static IEnumerable<TimePhasedDataType> GetTimePhaseData(Assignment.Assignment assignment, TimePhasedDataType.TimePhaseType type)
        {
            if(assignment == null)
                throw new ArgumentException("assignment");

            //определяем величину дискретизации для генератора интервалов.
            //Если ее определить слишком маленькую то будет много TimePhases елементов
            //Для плоского распределения трудозатрат использовать ДЕНЬ для нелинейных функций использовать ЧАС
            long groupIntervalValue = assignment.CurrentContour.ContourType == ContourTypes.Flat ? CalendarHelper.MilisPerDay() : CalendarHelper.MilisPerHour();

            long start = type == TimePhasedDataType.TimePhaseType.AssignmentActualWork ? assignment.Start : assignment.Stop;
            long stop = type == TimePhasedDataType.TimePhaseType.AssignmentActualWork ? assignment.Stop : assignment.End;
            Query<Interval> query = new Query<Interval>();
            AssignmentBaseFunctor<double> workFunctor = assignment.GetWorkFunctor();

            GroupingIntervalGenerator groupGen = new GroupingIntervalGenerator(start, stop, groupIntervalValue,
                                                                              workFunctor.CountourGenerator);
            TimePhaseDataGetter timePhaseGetter = new TimePhaseDataGetter(type, TimePhasedDataType.TimePhaseUnit.Day,
                                                                          TimePhasedDataType.TimePhaseUnit.Minute, workFunctor);
            WhereInRangePredicate whereInRange = new WhereInRangePredicate(start, stop);

            query.Select(timePhaseGetter).From(groupGen).Where(whereInRange.Evaluate).Execute();

            return timePhaseGetter.Value;
        }
예제 #5
0
        public void Assignment_SelectAddSelectDeleteSelect_OK()
        {
            using (System.Transactions.TransactionScope updateTransaction =
             new System.Transactions.TransactionScope())
            {
                string connectionString = GetConnectionstring();
                DataAccess d2 = new DataAccess(connectionString);

                List<Assignment> assignmentsBefore = d2.GetAssignments();

                Assignment assignment = new Assignment();
                assignment.AssignmentId = -1;
                assignment.AssignmentName = "asfdasfasdfsaf";

                Assignment assignmentAfterSave = d2.SaveAssignment(assignment);

                Assignment assignmentGetById = d2.GetAssignmentByID(assignment.AssignmentId);

                Assert.AreNotEqual(assignment.AssignmentId, -1);
                Assert.AreEqual(assignment.AssignmentName, assignmentGetById.AssignmentName);

                List<Assignment> assignmentsAfterSave = d2.GetAssignments();

                Assert.AreEqual(assignmentsAfterSave.Count, assignmentsBefore.Count + 1);

                d2.DeleteAssignment(assignment.AssignmentId);

                List<Assignment> assignmentsAfterDelete = d2.GetAssignments();

                Assert.AreEqual(assignmentsBefore.Count, assignmentsAfterDelete.Count);

            }
        }
예제 #6
0
    /// <summary>
    /// Initializes the assignment by retrieving the active Assignment from MissionControl, then configuring the scene with Assignment data if assignmentState = STATE_NEW.
    /// </summary>
    private void InitAssignment()
    {
        if (MissionControl.pObject.activeMission != null && MissionControl.pObject.activeAssignment != null)
        {
            walkAssignment = MissionControl.pObject.activeMission.activeAssignment;
        }
        else
        {
            print("Creating test assignment");
            walkAssignment = new Assignment(0, "Walk");
            Vector2 newPosition = UnityEngine.Random.insideUnitCircle * 300;
            targetLocation = new Vector3(newPosition.x, 0, newPosition.y);
        }
        if (walkAssignment.assignmentState == Assignment.STATE_NEW)
        {
            object value;
            if (walkAssignment.typeData.TryGetValue("targetLocation", out value))
            {
                targetLocation = (Vector3)value;
                Debug.Log("targetLocation: " + targetLocation);
            }
            else
            {
                Debug.Log("No target location found!");
            }

            walkAssignment.Start();
        }
        targetObject.transform.position = targetLocation;
        background.SetActive(false);
        backgroundGrid.SetActive(true);
    }
    //添加对应的作业-组信息
    protected void AddAssignmentGroup(Control topctrl, Assignment EditAssignment, int assignmentID)
    {
        foreach (Control c in topctrl.Controls)
        {
            if (c.GetType().ToString().Equals("System.Web.UI.WebControls.CheckBoxList"))
            {
                CheckBoxList cb = (CheckBoxList)c;

                //从1开始,因为第0项是班级
                for (int i = 1; i < cb.Items.Count; i++)
                {
                    if (cb.Items[i].Selected == true)
                    {
                        //new AssignmentGroupInfo对象
                        AssignmentGroupInfo newAssignmentGroupInfo = new AssignmentGroupInfo();
                        //初始化newAssignmentGroupInfo
                        newAssignmentGroupInfo.IAssignmentId = assignmentID;
                        //Items[i].Value保存的是组的ID,这是在动态生成的时候绑定的
                        newAssignmentGroupInfo.IGroupId = Convert.ToInt32(cb.Items[i].Value);
                        newAssignmentGroupInfo.INewMsgNum = 0;
                        newAssignmentGroupInfo.IState = 0;
                        //添加相应的组
                        EditAssignment.AddAssignmentGroup(newAssignmentGroupInfo);
                    }
                }
            }
            if (c.HasControls())
            {
                AddAssignmentGroup(c, EditAssignment, assignmentID);
            }
        }
    }
 /// <summary>
 /// Saves the assignment data in a hashtable and creates a new assignment and adds it to the AssignmentObject.
 /// </summary>
 public override void FinalizeAssignment()
 {
     Debug.Log("Finishing Assignment");
     Hashtable h = new Hashtable();
     h.Add("missionDescription", assignmentMaker.descriptionField.text + ". " + assignmentMaker.assignmentExplanation.text);
     Assignment newAssignment = new Assignment(0, "Scan", h);
     assignmentMaker.assignmentObject.AddAssignment(newAssignment);
 }
예제 #9
0
 public bool create(Assignment thisAssignment)
 {
     // ������ҵ
     DataClassesDataContext da = new DataClassesDataContext();
     da.Assignment.InsertOnSubmit(thisAssignment);
     da.SubmitChanges();
     return true;
 }
예제 #10
0
 public void AdjustValue()
 {
     esp = Tmp32("esp");
     CreateSymbolicEvaluator(frame);
     var ass = new Assignment(esp, new BinaryExpression(BinaryOperator.IAdd, esp.DataType, esp, Constant.Word32(4)));
     se.Evaluate(ass);
     Assert.AreEqual("fp + 0x00000004", ctx.TemporaryState[esp.Storage].ToString());
 }
 internal void AddAssignment(Guid id, Assignment a, string action)
 {
     // Make sure there isn't one already here
     _object.Remove(id);
     _action.Remove(id);
     _object.Add(id, a);
     _action.Add(id, action);
 }
예제 #12
0
 protected override void OnSynchronize(Assignment delta)
 {
   sum_ = 0;
   for (int index = 0; index < Size(); ++index)
   {
     sum_ += Value(index);
   }
 }
 public void ShouldParseLocalAssignment()
 {
     var assignment = new Assignment(new[] {new Variable("a")},
         new[] {new ConstantExpression(Constants.One)}, true);
     var expected = new StatementBlock(assignment);
     var actual = SyntaxParser.Parse("local a = 1");
     Assert.AreEqual(expected, actual);
 }
 public void ShouldParseSequentialAssignments()
 {
     var assignment1 = new Assignment(new[] { new Variable("a") },
         new[] { new ConstantExpression(Constants.One) }, true);
     var assignment2 = new Assignment(new[] { new Variable("b") },
         new[] { new ConstantExpression(Constants.Two) }, true);
     var expected = new StatementBlock(assignment1, assignment2);
     Assert.AreEqual(expected, SyntaxParser.Parse("local a = 1\nlocal b = 2"));
 }
예제 #15
0
 public void Test2()
 {
     BinaryExpression b = m.IAdd(id, m.UMul(id, 5));
     Assignment ass = new Assignment(x, b);
     var rule = new Add_mul_id_c_id_Rule(new SsaEvaluationContext(null, ssaIds));
     Assert.IsTrue(rule.Match(b));
     ass.Src = rule.Transform();
     Assert.AreEqual("x = id *u 0x00000006", ass.ToString());
 }
예제 #16
0
 /// <summary>
 /// Saves the assignment data in a hashtable and creates a new assignment and adds it to the AssignmentObject.
 /// </summary>
 public override void FinalizeAssignment()
 {
     Hashtable h = new Hashtable();
     Vector2 newPosition = UnityEngine.Random.insideUnitCircle * Int32.Parse(assignmentMaker.typeInputField.text);
     Vector3 target = new Vector3(newPosition.x, 0, newPosition.y);
     h.Add("targetLocation", target);
     h.Add("missionDescription", assignmentMaker.descriptionField.text + ". " + assignmentMaker.assignmentExplanation.text);
     Assignment newWalkAssignment = new Assignment(0, "Walk", h);
     assignmentMaker.assignmentObject.AddAssignment(newWalkAssignment);
 }
        public void BoolEquals()
        {
            var boolean = new LogicalOp("=", new IntegerLiteral("4", 0), new IntegerLiteral("5", 0), 0);
            var equals = new LogicalOp("=", boolean, boolean, 0);
            var assignment = new Assignment(result, equals, 0);
            program.Add(assignment);

            interpreter.Run(new Program(program));
            Assert.That(interpreter.Valuetable[symboltable.resolve("result")], Is.EqualTo(true));
        }
예제 #18
0
 public void configureGame(Assignment assignToUse)
 {
     useImages = assignToUse.hasImages;
     if(useImages){
       directoryForAssignment = assignToUse.imgDir;
     }
     contentForAssign = assignToUse.content;
     currMastery = AppManager.s_instance.pullAssignMastery(assignToUse);
     readyToConfigure = true;
 }
예제 #19
0
        public static void FormatAssignList(Assignment[] assignArray, SqlFragment parent, ScriptBuilder scriptBuilder, TSqlVisitor visitor)
        {
            int i = 0;
            foreach (Assignment assign in assignArray) {
                if (assign == null) {
                    continue;
                }

                AppendDelimiter(scriptBuilder, ref i);
                scriptBuilder.AppendFragment(assign, parent, visitor);
            }
        }
예제 #20
0
 public static AssigmentVm Create(Assignment model)
 {
     return new AssigmentVm
     {
         ReportId =       model.ReportId,
         AdminId =        model.AdminId,
         AdminUserName =  model.Admin.UserName,
         TargetId =       model.TargetId,
         TargetUserName = model.Target.UserName,
         Timestamp =      model.Timestamp
     };
 }
예제 #21
0
		public void Test1()
		{
			BinaryExpression b = m.Shl(m.SMul(id, 3), 2);
			Assignment ass = new Assignment(x, b);
			Statement stm = new Statement(0, ass, null);
			ssaIds[id].Uses.Add(stm);
			ssaIds[id].Uses.Add(stm);

			var rule = new Shl_mul_e_Rule(null);
			Assert.IsTrue(rule.Match(b));
			ass.Src = rule.Transform();
			Assert.AreEqual("x = id *s 0x0000000C", ass.ToString());
		}
예제 #22
0
        public ActionResult Create(Assignment assignment)
        {
            if (ModelState.IsValid)
            {
                db.Assignments.Add(assignment);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.AssetId = new SelectList(db.Assets, "ID", "AssetTag", assignment.AssetId);
            ViewBag.PersonId = new SelectList(db.Persons, "ID", "Shortname", assignment.PersonId);
            ViewBag.RoomId = new SelectList(db.Rooms, "ID", "RoomNumber", assignment.RoomId);
            return View(assignment);
        }
        protected override void Execute(CodeActivityContext context)
        {
            // Create an Assignment class and populate its properties
            Assignment a = new Assignment();

            a.WorkflowID = context.WorkflowInstanceId;
            a.LeadID = LeadID.Get(context);
            a.DateAssigned = DateTime.Now;
            a.AssignedTo = AssignedTo.Get(context);
            a.Status = "Assigned";
            a.DateDue = DateTime.Now + TimeSpan.FromDays(5);

            PersistAssignment persist = context.GetExtension<PersistAssignment>();
            persist.AddAssignment(context.WorkflowInstanceId, a, "Insert");
        }
예제 #24
0
    private void InitAssignment()
    {
        if (MissionControl.pObject.activeMission != null && MissionControl.pObject.activeAssignment != null)
        {
            assignment = MissionControl.pObject.activeMission.activeAssignment;
        }
        else
        {
            assignment = new Assignment(0, "None");
        }
        if (assignment.assignmentState == Assignment.STATE_NEW)
        {

            assignment.Start();
        }
    }
예제 #25
0
        public void Test1()
        {
            BinaryExpression b = m.IAdd(m.SMul(id, 4), id);
            Assignment ass = new Assignment(x, b);
            Statement stm = new Statement(0, ass, null);
            ssaIds[id].Uses.Add(stm);
            ssaIds[id].Uses.Add(stm);

            ctx.Statement = stm;
            Add_mul_id_c_id_Rule rule = new Add_mul_id_c_id_Rule(ctx);
            Assert.IsTrue(rule.Match(b));
            Assert.AreEqual(2, ssaIds[id].Uses.Count);
            ass.Src = rule.Transform();
            Assert.AreEqual("x = id *s 0x00000005", ass.ToString());
            Assert.AreEqual(1, ssaIds[id].Uses.Count);
        }
예제 #26
0
		public void EqbSimpleEquivalence()
		{
			TypeFactory factory = new TypeFactory();
			TypeStore store = new TypeStore();
			EquivalenceClassBuilder eqb = new EquivalenceClassBuilder(factory, store);
			Identifier id1 = new Identifier("id2", PrimitiveType.Word32, null);
			Identifier id2 = new Identifier("id2", PrimitiveType.Word32, null);
			Assignment ass = new Assignment(id1, id2);
			ass.Accept(eqb);

			Assert.IsNotNull(id1);
			Assert.IsNotNull(id2);
			Assert.AreEqual(2, id1.TypeVariable.Number, "id1 type number");
			Assert.AreEqual(2, id1.TypeVariable.Number, "id2 type number");
			Assert.AreEqual(id1.TypeVariable.Class, id2.TypeVariable.Class);
		}
        public void FalseAnd()
        {
            var falseboolean = new LogicalOp("=", new IntegerLiteral("4", 0), new IntegerLiteral("5", 0), 0);
            var trueboolean = new LogicalOp("=", new IntegerLiteral("4", 0), new IntegerLiteral("5", 0), 0);
            var and1 = new LogicalOp("&", falseboolean, trueboolean, 0);
            var and2 = new LogicalOp("&", falseboolean, falseboolean, 0);
            var assignment1 = new Assignment(result, and1, 0);
            program.Add(assignment1);
            var result2 = new VariableDeclaration("result2", "bool", 0);
            symboltable.define(new Symbol("result2", "bool"));
            var assignment2 = new Assignment(result2, and2, 0);
            program.Add(assignment2);

            interpreter.Run(new Program(program));
            Assert.That(interpreter.Valuetable[symboltable.resolve("result")], Is.EqualTo(false));
            Assert.That(interpreter.Valuetable[symboltable.resolve("result2")], Is.EqualTo(false));
        }
예제 #28
0
        public void AddProperty(PropertyDeclaration propertyExpression)
        {
            string name = propertyExpression.Name;
            var mode = propertyExpression.Mode;

            if (name == null)
            {
                name = mode.ToString().ToLower();
                mode = PropertyExpressionType.Data;
            }

            Assignment declaration;
            if (_assignments.TryGetValue(name, out declaration))
            {
                if (
                    (declaration.Mode == PropertyExpressionType.Data) !=
                    (mode == PropertyExpressionType.Data)
                )
                    throw new JintException("A property cannot be both an accessor and data");
            }
            else
            {
                declaration = new Assignment
                {
                    Mode = mode,
                    Expression = propertyExpression.Expression
                };

                _assignments.Add(name, declaration);
            }

            switch (mode)
            {
                case PropertyExpressionType.Get:
                    declaration.GetExpression = propertyExpression.Expression;
                    declaration.Expression = null;
                    break;

                case PropertyExpressionType.Set:
                    declaration.SetExpression = propertyExpression.Expression;
                    declaration.Expression = null;
                    break;
            }
        }
 /// <summary>
 /// 提交按钮的响应
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void btSubmit_Click(object sender, EventArgs e)
 {
     //用户类型
     Session["Type"] = "Teacher";
     //写代码不注意真是的
     //Session["UserName"] = "******";
     //new Model.CommentInfo,Search,Teacher,Assignment对象
     Model.CommentInfo comm=new CommentInfo ();
     Search s = new Search();
     Teacher t = new Teacher();
     Assignment ass = new Assignment();
     //初始化
     comm.DtReleaseTime = System.DateTime.Now;
     int assID = Convert.ToInt32(assmtID);
     comm.IAssignmentId = assID;
     int grpID = Convert.ToInt32(groupID);
     comm.IGroupId = grpID;
     comm.StrContents = tbNewMsg.Text;
     //判断用户名是否为空
     if (null == strUserName)
     {
         Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert",
            "<script>alert('对不起,你还未登录!')</script>");
         return;
     }
     else
     {
         //判断是否是教师用户
         if (Convert.ToString(type) == "Teacher")
         {
             comm.StrReleasePsnName = t.GetTeacherByUserName(Convert.ToString(strUserName)).StrTeacherName;
         }
     }
     //添加评论
     if (ass.AddComment(comm))
     {
         Response.Redirect("TCommunication.aspx?aid= "+comm.IAssignmentId+"&gid="+comm.IGroupId);
     }
 }
예제 #30
0
        public void TvrReplaceInMem()
        {
            var id1 = new Identifier("pptr", PrimitiveType.Word32, null);
            var id2 = new Identifier("ptr", PrimitiveType.Word32, null);
            var id3 = new Identifier("v", PrimitiveType.Word32, null);
            var ass1 = new Assignment(id2, MemLoad(id1, 0, PrimitiveType.Word32));
            var ass2 = new Assignment(id3, MemLoad(id2, 0, PrimitiveType.Word32));
            eqb.VisitAssignment(ass1);
            eqb.VisitAssignment(ass2);

            var prog = new Program();
            prog.Architecture = new FakeArchitecture();
            prog.Platform = new DefaultPlatform(null, prog.Architecture);
            trco = new TraitCollector(factory, store, dtb, prog);
            trco.VisitAssignment(ass1);
            trco.VisitAssignment(ass2);
            dtb.BuildEquivalenceClassDataTypes();

            var tvr = new TypeVariableReplacer(store);
            tvr.ReplaceTypeVariables();
            Verify("Typing/TvrReplaceInMem.txt");
        }
        /// <summary>
        /// Creates or updates a Blueprint assignment in a management group.
        /// </summary>
        /// <param name='operations'>
        /// The operations group for this extension method.
        /// </param>
        /// <param name='managementGroupName'>
        /// The name of the management group where the assignment will be saved.
        /// </param>
        /// <param name='assignmentName'>
        /// The name of the assignment.
        /// </param>
        /// <param name='assignment'>
        /// The assignment object to save.
        /// </param>

        public static Assignment CreateOrUpdateInManagementGroup(this IAssignmentsOperations operations, string managementGroupName, string assignmentName, Assignment assignment)
        {
            var resourceScope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);

            return(operations.CreateOrUpdateAsync(resourceScope, assignmentName, assignment).GetAwaiter().GetResult());
        }
예제 #32
0
 protected override bool Visit(Assignment ass)
 {
     return(_check.Visit(ass.Right));
 }
예제 #33
0
        protected override BaseStatement Visit(Assignment ass)
        {
            Add(ass.Left, ass.Right);

            return(base.Visit(ass));
        }
예제 #34
0
        public ActionResult <Assignment> Details(string id)
        {
            Assignment assignment = new Assignment();

            using (connection)
            {
                string       sqlQuery = string.Format(@"SELECT a.Id, cat.Name AS CategoryName, a.Title, a.Description, a.TimePosted, a.Deadline, a.Status, c.Id AS CreatorId, c.Email AS CreatorEmail, c.FirstName AS CreatorFirstName, c.LastName AS CreatorLastName, c.ImagePath AS CreatorImagePath, company.Name AS CompanyName, company.Id AS CompanyId
          FROM assignment AS a
          LEFT JOIN company AS company
          ON a.CompanyId = company.Id
          LEFT JOIN appuser AS c
          ON c.Id = company.UserId
          LEFT JOIN category AS cat
          ON cat.Id = a.CategoryId
          WHERE a.Id = ""{0}"" ", id);
                MySqlCommand command  = new MySqlCommand(sqlQuery, connection);

                try
                {
                    connection.Open();
                    command.Prepare();
                    MySqlDataReader reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        User creator = new User()
                        {
                            Id        = reader["CreatorId"].ToString(),
                            Email     = reader["CreatorEmail"].ToString(),
                            FirstName = reader["CreatorFirstName"].ToString(),
                            LastName  = reader["CreatorLastName"].ToString(),
                            Image     = reader["CreatorImagePath"].ToString(),
                        };
                        assignment.Creator = creator;

                        assignment.Id           = reader["Id"].ToString();
                        assignment.CompanyId    = reader["CompanyId"].ToString();
                        assignment.CompanyName  = reader["CompanyName"].ToString();
                        assignment.CategoryName = reader["CategoryName"].ToString();
                        assignment.Title        = reader["Title"].ToString();
                        assignment.Description  = reader["Description"].ToString();
                        assignment.TimePosted   = reader.GetDateTime(reader.GetOrdinal("TimePosted"));
                        assignment.Deadline     = reader.GetDateTime(reader.GetOrdinal("Deadline"));
                        assignment.Status       = Convert.ToInt32(reader["Status"]);
                    }
                    ;
                    reader.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    connection.Close();
                }
                connection.Close();
            }

            if (assignment.Title != null)
            {
                return(assignment);
            }

            throw new RestException(HttpStatusCode.NotFound);
        }
예제 #35
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public ResourceLink(Idea OwnerContainer, Assignment <DetailDesignator> /*L*/ Designator)
     : base(OwnerContainer)
 {
     this.AssignedDesignator = Designator;
 }
예제 #36
0
        internal static CodeNode Parse(ParseInfo state, ref int index)
        {
            int i = index;

            Tools.SkipSpaces(state.Code, ref i);

            if (!Parser.Validate(state.Code, "for(", ref i) &&
                (!Parser.Validate(state.Code, "for (", ref i)))
            {
                return(null);
            }

            Tools.SkipSpaces(state.Code, ref i);

            var result = new ForOf()
            {
                _labels = state.Labels.GetRange(state.Labels.Count - state.LabelsCount, state.LabelsCount).ToArray()
            };

            VariableDescriptor[] vars = null;
            var oldVariablesCount     = state.Variables.Count;

            state.lexicalScopeLevel++;
            try
            {
                var vStart = i;
                result._variable = VariableDefinition.Parse(state, ref i, true);
                if (result._variable == null)
                {
                    if (state.Code[i] == ';')
                    {
                        return(null);
                    }

                    Tools.SkipSpaces(state.Code, ref i);

                    int start = i;
                    if (!Parser.ValidateName(state.Code, ref i, state.strict))
                    {
                        return(null);
                    }

                    var varName = Tools.Unescape(state.Code.Substring(start, i - start), state.strict);
                    if (state.strict)
                    {
                        if (varName == "arguments" || varName == "eval")
                        {
                            ExceptionHelper.ThrowSyntaxError("Parameters name may not be \"arguments\" or \"eval\" in strict mode at ", state.Code, start, i - start);
                        }
                    }

                    result._variable = new Variable(varName, state.lexicalScopeLevel)
                    {
                        Position = start, Length = i - start, ScopeLevel = state.lexicalScopeLevel
                    };

                    Tools.SkipSpaces(state.Code, ref i);

                    if (state.Code[i] == '=')
                    {
                        Tools.SkipSpaces(state.Code, ref i);

                        var defVal = ExpressionTree.Parse(state, ref i, false, false, false, true, true);
                        if (defVal == null)
                        {
                            return(defVal);
                        }

                        Expression exp = new AssignmentOperatorCache(result._variable as Variable ?? (result._variable as VariableDefinition)._initializers[0] as Variable);
                        exp = new Assignment(exp, defVal)
                        {
                            Position = exp.Position,
                            Length   = defVal.EndPosition - exp.Position
                        };

                        if (result._variable == exp._left._left)
                        {
                            result._variable = exp;
                        }
                        else
                        {
                            (result._variable as VariableDefinition)._initializers[0] = exp;
                        }

                        Tools.SkipSpaces(state.Code, ref i);
                    }
                }

                if (!Parser.Validate(state.Code, "of", ref i))
                {
                    if (oldVariablesCount < state.Variables.Count)
                    {
                        state.Variables.RemoveRange(oldVariablesCount, state.Variables.Count - oldVariablesCount);
                    }

                    return(null);
                }

                state.LabelsCount = 0;
                Tools.SkipSpaces(state.Code, ref i);

                if (result._variable is VariableDefinition)
                {
                    if ((result._variable as VariableDefinition)._variables.Length > 1)
                    {
                        ExceptionHelper.ThrowSyntaxError("Too many variables in for-of loop", state.Code, i);
                    }
                }

                result._source = Parser.Parse(state, ref i, CodeFragmentType.Expression);
                Tools.SkipSpaces(state.Code, ref i);

                if (state.Code[i] != ')')
                {
                    ExceptionHelper.Throw((new SyntaxError("Expected \")\" at + " + CodeCoordinates.FromTextPosition(state.Code, i, 0))));
                }

                i++;
                state.AllowBreak.Push(true);
                state.AllowContinue.Push(true);
                result._body = Parser.Parse(state, ref i, 0);
                state.AllowBreak.Pop();
                state.AllowContinue.Pop();
                result.Position = index;
                result.Length   = i - index;
                index           = i;
                vars            = CodeBlock.extractVariables(state, oldVariablesCount);
            }
            finally
            {
                state.lexicalScopeLevel--;
            }

            return(new CodeBlock(new[] { result })
            {
                _variables = vars,
                Position = result.Position,
                Length = result.Length
            });
        }
예제 #37
0
        public void InsertAssignmentPerCoursePerStudent(Assignment assignment) // λυπαμαι για οτι ακολουθει.
        {
            List <Grade> grades = new List <Grade>();

            grades = GetAll <Grade>(query);
            List <Student> students = new StudentService().GetList();

            students = new StudentService().GetListAnalytic(students);
            List <Course_Assignment> courses_Assignments = new Course_Assignment().GetList();
            List <Course>            courses             = new CourseService().GetList();

            courses = new CourseService().GetListAnalytic(courses);
            do
            {
                Console.Write($"Assignment: {assignment.AssignmentId} {assignment.Title} {assignment.Description}\n\n------\n>");
                int   tempst;
                Grade grade = new Grade();
                new StudentView().Display(students);
                Console.Write("Select Student to Assign:\nPress 0 to go back\n\n------\n>");
                tempst = IntegerId <Student>(students);
                if (tempst == 0)
                {
                    Console.WriteLine("Process Terminated"); return;
                }
                Student student = students.FirstOrDefault(x => x.StudentId == tempst);


                if (student.Courses.Count() == 0)
                {
                    Console.WriteLine("Student is not enrolled to any course!Process terminated!");
                }
                else if (student.Courses.Count() == 1)
                {
                    int tempcourid0;
                    tempcourid0 = student.Courses[0].CourseId;
                    Course_Assignment course_Assignment1 = courses_Assignments.FirstOrDefault(x => x.CourseId == tempcourid0 && x.AssignmentId == assignment.AssignmentId);
                    if (course_Assignment1 is Course_Assignment)
                    {
                        grade.CourseId = tempcourid0;
                    }
                    else
                    {
                        Console.WriteLine("Assignment is not assigned to this course.Process terminated");
                        return;
                    }
                }
                else
                {
                    int   listsize = student.Courses.Count();
                    int   temp;
                    int[] tempcourid = new int[listsize];
                    for (int i = 0; i < listsize; i++)
                    {
                        Console.WriteLine("Student is enrolled to course(s):");
                        CourseView courseView = new CourseView();
                        courseView.Display(student.Courses);
                        while (true)
                        {
                            Console.Write("Please choose in which one the assignment will be assigned!\nPress 0 to go back\n\n------\n>");
                            temp = IntegerId <Course>(student.Courses);
                            if (temp == 0)
                            {
                                Console.WriteLine("Process Terminated"); return;
                            }
                            if (!tempcourid.Contains(temp))
                            {
                                tempcourid[i] = temp;
                                break;
                            }
                            else
                            {
                                Console.WriteLine("Already tried this course with no success!");
                            }
                        }
                        Course_Assignment course_Assignment = courses_Assignments.FirstOrDefault(x => x.CourseId == tempcourid[i] && x.AssignmentId == assignment.AssignmentId);
                        Grade             grade1            = grades.FirstOrDefault(x => x.CourseId == tempcourid[i] && x.AssignmentId == assignment.AssignmentId && x.StudentId == tempst);
                        if (grade1 is Grade)
                        {
                            Console.WriteLine($"Already assigned to {student.FirstName} {student.LastName} for this course!");
                        }
                        else if (course_Assignment is Course_Assignment)
                        {
                            grade.CourseId = tempcourid[i];
                            break;
                        }
                        else
                        {
                            Console.WriteLine("Assignment is NOT assigned to this course.Try again!");
                        }
                    }
                }
                if (grade.CourseId != 0)
                {
                    grade.AssignmentId = assignment.AssignmentId;
                    grade.StudentId    = tempst;


                    CreateData <Grade>(grade, "Grades");
                }
                else
                {
                    Console.WriteLine("Process Failed");
                }
                Console.Write("Do you want to add more students to this assignment?:<Y> or <N>?:\n>");
            } while (YesOrNo());
        }
예제 #38
0
 /// <summary>
 /// Visit operation called for assignments.
 ///
 /// <param name="a">an assignment</param>
 /// </summary>
 public virtual void visit_assignment(Assignment a)
 {
 }
예제 #39
0
 public void Visit(Assignment ass)
 {
     Console.WriteLine($" {ass.ident.token.lexeme} <- ");
     ass.expression.Accept(this);
     Console.WriteLine();
 }
예제 #40
0
 public AbsynStatement VisitAssignment(Assignment ass)
 {
     return(new AbsynAssignment(ass.Dst, ass.Src));
 }
        private void CreateAssignmentObject(Scope scope, string text)
        {
            Assignment assignment = new Assignment
            {
                AssignmentString = text.Replace(";", ""),
                Instruction      = new SingleInstruction(),
                Variable         = "",
                LocalVariables   = new List <Variable>(),
                VType            = Enums.VType.Assignment,
            };

            scope.Items.Enqueue(assignment);

            /*Match m = _regex.InstructionRegex.Match(text);
             * Match ma = _regex.Array.Match(text);
             * Match op = _regex.OperatorRegex.Match(text);
             * if(ma.Groups.Count > 1)
             * {
             *  assignment.Variable = ma.Groups[0].ToString();
             *  text = text.Replace(ma.Groups[0].ToString(),"");
             *  m = _regex.InstructionRegex.Match(text);
             * }
             * else
             * {
             *  assignment.Variable = m.Groups[0].ToString();
             *  m = m.NextMatch();
             * }
             *
             *
             * if (_regex.ThreeAddressInstructionRegex.IsMatch(text))
             * {
             *  ThreeAddressInstruction threeAddress = new ThreeAddressInstruction
             *  {
             *      InstructionType = Enums.InstructionType.ThreeAddress
             *  };
             *  assignment.Instruction = threeAddress;
             *
             *
             *  byte count = 0;
             *  while (m.Success)
             *  {
             *      TypedvCodes ins = new TypedvCodes();
             *      if (_regex.ConstantRegex.IsMatch(m.Groups[0].ToString()))
             *      {
             *          ins = CreateConstantObject(ins, m.Groups[0].ToString());
             *      }
             *      else if (_regex.Variable.IsMatch(m.Groups[0].ToString()))
             *      {
             *          ins.Name = m.Groups[0].ToString();
             *          ins.VType = Enums.VType.Variable;
             *      }
             *      else if (_regex.FunctionCall.IsMatch(m.Groups[0].ToString()))
             *      {
             *          ins.Name = m.Groups[0].ToString();
             *          ins.VType = Enums.VType.Function;
             *      }
             *      if (count == 0)
             *      {
             *          threeAddress.LeftInstruction = ins;
             *          count++;
             *      }
             *      else
             *      {
             *          threeAddress.RightInstruction = ins;
             *      }
             *      m = m.NextMatch();
             *  }
             *  threeAddress.Operator = op.Groups[0].ToString();
             * }
             * else
             * {
             *  SingleInstruction single = new SingleInstruction {InstructionType = Enums.InstructionType.SingleAddress};
             *
             *
             *  TypedvCodes ins = new TypedvCodes();
             *
             *  if (_regex.ConstantRegex.IsMatch(m.Groups[0].ToString()))
             *  {
             *      ins = CreateConstantObject(ins, m.Groups[0].ToString());
             *  }
             *  else if (_regex.Variable.IsMatch(m.Groups[0].ToString()))
             *  {
             *      ins.Name = m.Groups[0].ToString();
             *      ins.VType = Enums.VType.Variable;
             *  }
             *  else if (_regex.FunctionCall.IsMatch(m.Groups[0].ToString()))
             *  {
             *      ins.Name = m.Groups[0].ToString();
             *      ins.VType = Enums.VType.Function;
             *  }
             *  single.Instruction = ins;
             *  assignment.Instruction = single;
             *  MessageBox.Show(assignment.Instruction.InstructionType.ToString());
             * }
             */
        }
예제 #42
0
 public void Delete(Assignment entity)
 {
     repository.Delete(entity);
 }
예제 #43
0
        public IInterpreter ExplicitDereferencing()
        {
            var interpreter = new Interpreter.Interpreter();

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Language.Environment.Create(new Options()
                {
                    AllowInvalidMainResult = true,
                    DebugThrowOnError      = true,
                    AllowDereference       = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                VariableDeclaration decl = VariableDeclaration.CreateStatement("x",
                                                                               NameFactory.PointerNameReference(NameFactory.Int64NameReference(env.Options.ReassignableTypeMutability())),
                                                                               ExpressionFactory.HeapConstructor(NameFactory.Int64NameReference(env.Options.ReassignableTypeMutability()),
                                                                                                                 FunctionArgument.Create(Int64Literal.Create("4"))),
                                                                               env.Options.ReassignableModifier());
                var main_func = root_ns.AddBuilder(FunctionBuilder.Create(
                                                       "main",
                                                       ExpressionReadMode.OptionalUse,
                                                       NameFactory.Int64NameReference(),
                                                       Block.CreateStatement(new IExpression[] {
                    // x *Int = new Int(4)
                    decl,
                    // y *Int = x
                    VariableDeclaration.CreateStatement("y",
                                                        NameFactory.PointerNameReference(NameFactory.Int64NameReference(env.Options.ReassignableTypeMutability())),
                                                        NameReference.Create("x")),
                    // *x = 7 // y <- 7
                    Assignment.CreateStatement(Dereference.Create(NameReference.Create("x")), Int64Literal.Create("7")),
                    // z *Int
                    VariableDeclaration.CreateStatement("z",
                                                        NameFactory.PointerNameReference(NameFactory.Int64NameReference(env.Options.ReassignableTypeMutability())),
                                                        null, env.Options.ReassignableModifier()),
                    // z = x
                    Assignment.CreateStatement(NameReference.Create("z"), NameReference.Create("x")),
                    // v = y + z  // 14
                    VariableDeclaration.CreateStatement("v", null, ExpressionFactory.Add("y", "z"), env.Options.ReassignableModifier()),
                    // x = -12
                    Assignment.CreateStatement(NameReference.Create("x"),
                                               ExpressionFactory.HeapConstructor(NameFactory.Int64NameReference(env.Options.ReassignableTypeMutability()),
                                                                                 FunctionArgument.Create(Int64Literal.Create("-12")))),
                    // *z = *x   // z <- -12
                    Assignment.CreateStatement(Dereference.Create(NameReference.Create("z")), Dereference.Create(NameReference.Create("x"))),
                    // x = -1000
                    Assignment.CreateStatement(NameReference.Create("x"),
                                               ExpressionFactory.HeapConstructor(NameFactory.Int64NameReference(env.Options.ReassignableTypeMutability()),
                                                                                 FunctionArgument.Create(Int64Literal.Create("-1000")))),
                    // v = v+z  // v = 14 + (-12)
                    Assignment.CreateStatement(NameReference.Create("v"), ExpressionFactory.Add("v", "z")),
                    Return.Create(NameReference.Create("v"))
                })));


                ExecValue result = interpreter.TestRun(env);

                Assert.AreEqual(2L, result.RetValue.PlainValue);
            }

            return(interpreter);
        }
예제 #44
0
 public void Update(Assignment entity)
 {
     entity.UpdatedAt = DateTime.Now;
     repository.Update(entity);
 }
예제 #45
0
        public static IList <string> GetAllAccessRoles(User user, object entity)
        {
            IList <string> accessRoles = new List <string>();

            if (entity == null)
            {
                foreach (Role role in user.Roles)
                {
                    accessRoles.Add(role.Name);
                }
                return(accessRoles);
            }
            switch (entity.GetType().BaseType.Name)
            {
            case "Course":
                Course course = (Course)entity;
                if (user.Equals(course.Teacher.User))
                {
                    accessRoles.Add("Teacher");
                }
                if (user.GetTutor() != null)
                {
                    Tutor authorizedTutor = user.GetTutor();
                    foreach (Lesson otherLesson in authorizedTutor.Lessons)
                    {
                        if (course.Equals(otherLesson.Assignment.Course))
                        {
                            accessRoles.Add("Tutor");
                            break;
                        }
                    }
                }
                if (user.GetStudent() != null)
                {
                    accessRoles.Add("Student");
                }
                return(accessRoles);

            case "Assignment":
                Assignment assignment = (Assignment)entity;
                if (user.Equals(assignment.Course.Teacher.User))
                {
                    accessRoles.Add("Teacher");
                }
                if (user.GetTutor() != null)
                {
                    Tutor authorizedTutor = user.GetTutor();
                    foreach (Lesson otherLesson in authorizedTutor.Lessons)
                    {
                        if (assignment.Equals(otherLesson.Assignment))
                        {
                            accessRoles.Add("Tutor");
                            break;
                        }
                    }
                }
                if (user.GetStudent() != null)
                {
                    Student authorizedStudent = user.GetStudent();
                    foreach (GroupMembership membership in authorizedStudent.GroupMemberships)
                    {
                        if (membership.Group.Lesson.Assignment.Equals(assignment))
                        {
                            accessRoles.Add("Student");
                            break;
                        }
                    }
                }
                return(accessRoles);

            case "Lesson":
                Lesson lesson = (Lesson)entity;
                if (user.Equals(lesson.Assignment.Course.Teacher.User))
                {
                    accessRoles.Add("Teacher");
                }
                if (user.GetTutor() != null)
                {
                    Tutor authorizedTutor = user.GetTutor();
                    if (authorizedTutor.Equals(lesson.Tutor))
                    {
                        accessRoles.Add("Tutor");
                    }
                }
                if (user.GetStudent() != null)
                {
                    Student authorizedStudent = user.GetStudent();
                    foreach (GroupMembership membership in authorizedStudent.GroupMemberships)
                    {
                        if (lesson.Equals(membership.Group.Lesson))
                        {
                            accessRoles.Add("Student");
                            break;
                        }
                    }
                }
                return(accessRoles);

            case "Group":
                Models.Group group = (Models.Group)entity;
                if (user.Equals(group.Lesson.Assignment.Course.Teacher.User))
                {
                    accessRoles.Add("Teacher");
                }
                if (user.GetTutor() != null)
                {
                    Tutor authorizedTutor = user.GetTutor();
                    if (authorizedTutor.Equals(group.Lesson.Tutor))
                    {
                        accessRoles.Add("Tutor");
                    }
                }
                if (user.GetStudent() != null)
                {
                    Student authorizedStudent = user.GetStudent();
                    foreach (GroupMembership membership in authorizedStudent.GroupMemberships)
                    {
                        if (group.Equals(membership.Group))
                        {
                            accessRoles.Add("Student");
                            break;
                        }
                    }
                }
                return(accessRoles);

            default:
                return(accessRoles);
            }
        }
예제 #46
0
 void InstructionVisitor.VisitAssignment(Assignment a)
 {
     stms.Add(new AbsynAssignment(a.Dst, a.Src));
 }
예제 #47
0
        // NOT ALLOWED CreateBugSimpleHistories //
        // NOT ALLOWED CreateBugSimpleHistories //
        // NOT ALLOWED CreateEpicSimpleHistories //
        // NOT ALLOWED CreateFeatureSimpleHistories //
        // NOT ALLOWED CreateImpedimentSimpleHistories //
        // NOT ALLOWED CreateRequestSimpleHistories //
        // NOT ALLOWED CreateTaskSimpleHistories //
        // NOT ALLOWED CreateUserStorySimpleHistories //

        #endregion

        #region CreateAsync

        // NOT ALLOWED CreateAssignableAsync //
        // NOT ALLOWED CreateAssignedEffortAsync //
        public Task <IApiResponse <Assignment> > CreateAssignmentAsync(Assignment assignment) => CreateDataAsync <Assignment>(assignment);
예제 #48
0
 public virtual bool Visit(Assignment node)
 {
     return(CommonVisit(node));
 }
예제 #49
0
        // NOT ALLOWED GetBugSimpleHistoriesAsync //
        // NOT ALLOWED GetEpicSimpleHistoriesAsync //
        // NOT ALLOWED GetFeatureSimpleHistoriesAsync //
        // NOT ALLOWED GetImpedimentSimpleHistoriesAsync //
        // NOT ALLOWED GetRequestSimpleHistoriesAsync //
        // NOT ALLOWED GetTaskSimpleHistoriesAsync //
        // NOT ALLOWED GetUserStorySimpleHistoriesAsync //

        #endregion

        #region Create

        // NOT ALLOWED CreateAssignable //
        // NOT ALLOWED CreateAssignedEffort //
        public IApiResponse <Assignment> CreateAssignment(Assignment assignment) => CreateData <Assignment>(assignment);
예제 #50
0
        protected override void GenerateMethod(Node node, StreamWriter stream, string indent)
        {
            base.GenerateMethod(node, stream, indent);

            Assignment assignment = node as Assignment;

            if (assignment == null)
            {
                return;
            }

            stream.WriteLine("{0}\t\tvirtual EBTStatus update_impl(Agent* pAgent, EBTStatus childStatus)", indent);
            stream.WriteLine("{0}\t\t{{", indent);
            stream.WriteLine("{0}\t\t\tBEHAVIAC_UNUSED_VAR(pAgent);", indent);
            stream.WriteLine("{0}\t\t\tBEHAVIAC_UNUSED_VAR(childStatus);", indent);
            stream.WriteLine("{0}\t\t\tEBTStatus result = BT_SUCCESS;", indent);

            if (assignment.Opl != null && assignment.Opr != null)
            {
                PropertyDef prop = assignment.Opl.Property;

                if (prop != null)
                {
                    RightValueCppExporter.GenerateCode(assignment.Opr, stream, indent + "\t\t\t", assignment.Opr.NativeType, "opr", "opr");

                    string property = PropertyCppExporter.GetProperty(prop, assignment.Opl.ArrayIndexElement, stream, indent + "\t\t\t", "opl", "assignment");
                    string propName = prop.BasicName.Replace("[]", "");

                    if (prop.IsArrayElement && assignment.Opl.ArrayIndexElement != null)
                    {
                        ParameterCppExporter.GenerateCode(assignment.Opl.ArrayIndexElement, stream, indent + "\t\t\t", "int", "opl_index", "assignment_opl");
                        property = string.Format("({0})[opl_index]", property);
                    }

                    string opr = "opr";
                    if (!Plugin.IsArrayType(prop.Type))
                    {
                        if (assignment.Opr.Var != null && assignment.Opr.Var.ArrayIndexElement != null)
                        {
                            ParameterCppExporter.GenerateCode(assignment.Opr.Var.ArrayIndexElement, stream, indent + "\t\t\t", "int", "opr_index", "assignment_opr");
                            opr = string.Format("({0})[opr_index]", opr);
                        }
                    }

                    if (!prop.IsArrayElement && (prop.IsPar || prop.IsCustomized))
                    {
                        string propBasicName = prop.BasicName.Replace("[]", "");
                        uint   id            = Behaviac.Design.CRC32.CalcCRC(propBasicName);

                        stream.WriteLine("{0}\t\t\tpAgent->SetVariable(\"{1}\", {2}, {3}u);", indent, propBasicName, opr, id);
                    }
                    else
                    {
                        stream.WriteLine("{0}\t\t\t{1} = {2};", indent, property, opr);
                    }
                }

                if (assignment.Opr.IsMethod)
                {
                    RightValueCsExporter.PostGenerateCode(assignment.Opr, stream, indent + "\t\t\t", assignment.Opr.NativeType, "opr", string.Empty);
                }
            }

            stream.WriteLine("{0}\t\t\treturn result;", indent);
            stream.WriteLine("{0}\t\t}}", indent);
        }
예제 #51
0
        static void Main(string[] args)
        {

            // GET ALL EXERCISES
            ExercisesController exercisesController = new ExercisesController();

            var exercises = exercisesController.GetAllExercises();

            exercises.ForEach(exercise =>
            {
                Console.WriteLine($"{exercise.Id}: {exercise.ExerciseName} -- {exercise.ExerciseLanguage}");
                Console.WriteLine(" ");
            });

            Pause();

            // Find all the exercises in the database where the language is JavaScript.
            var selectExercises = exercisesController.GetExerciseByLanguage("C#");

            selectExercises.ForEach(exercise =>
            {
                Console.WriteLine($"{exercise.Id}: {exercise.ExerciseName} -- {exercise.ExerciseLanguage}");
                Console.WriteLine(" ");
            });

            Pause();

            // Insert a new exercise into the database.
            Exercise exerciseToAdd = new Exercise
            {
                ExerciseName = "Personal Website",
                ExerciseLanguage = "ReactJS"
            };

            //exercisesController.AddExercise(exerciseToAdd);
            Pause();

            // Insert a new instructor into the database. Assign the instructor to an existing cohort.
            InstructorsController instructorsController = new InstructorsController();
            Instructor instructorToAdd = new Instructor
            {
                FirstName = "Todd",
                LastName = "Packer",
                SlackHandle = "@tpDaddy",
                CohortId = 2,
                Specialty = "Hitting on Women"
            };

            instructorsController.AddInstructor(instructorToAdd);
            Pause();

            // Assign an existing exercise to an existing student.
            AssignmentsController assignmentsController = new AssignmentsController();
            Assignment assignmentToAssign = new Assignment
            {
                StudentId = 1,
                InstructorId = 2,
                ExerciseId = 3
            };

            assignmentsController.AssignExercise(assignmentToAssign);
            Pause();

            // Find all the students in the database. Include each student's cohort AND each student's list of exercises.
            StudentsController studentsController = new StudentsController();
            var students = studentsController.GetAllStudents();

            // HOW TO ONLY SHOW STUDENTS ONCE???
            students.ForEach(student =>
            {
                
                Console.WriteLine($"{student.Id}: {student.FirstName}{student.LastName} [{student.cohort.Title}] -- ");
                Console.WriteLine("Exercises:");
                exercises.ForEach(ex =>
                {
                    Console.WriteLine($"{ex.ExerciseName} -- {ex.ExerciseLanguage}");
                });
            });

            Pause();
        }
예제 #52
0
        public static void Solve(int vehicles, int capacity, Distance distances, Demands demands)
        {
            /*
             * Generate constraint model
             */

            // Third argument defines depot, i.e. start-end node for round trip.
            var model = new RoutingModel(distances.MapSize(), vehicles, 0);

            // Node costs vs. Arc Costs
            model.SetArcCostEvaluatorOfAllVehicles(distances);

            /*
             * Capacity Constraints
             */

            if (distances.MapSize() != demands.MapSize())
            {
                throw new ArgumentException("Define demand for each city.");
            }

            model.AddDimension(demands, 0, capacity, true, "capacity");

            /*
             * Solve problem and display solution
             */

            Assignment assignment = model.Solve();

            if (assignment != null)
            {
                Console.WriteLine("Depot: " + model.GetDepot());
                Console.WriteLine("Total Distance: " + assignment.ObjectiveValue() + "\n");

                for (int i = 0; i < vehicles; i++)
                {
                    /*
                     * Display Trips:
                     */

                    Console.WriteLine("Round Trip for Vehicle " + i + ":");

                    long total  = 0;
                    var  source = model.Start(i);

                    while (!model.IsEnd(source))
                    {
                        var s = model.IndexToNode(source);
                        var t = model.IndexToNode(model.Next(assignment, source));

                        total += distances.Run(s, t);

                        Console.WriteLine(String.Format(" - From {0,-2} (demand: {1,-1}) travel to {2,-2} (demand: {3,-1}) with distance: {4,-2}",
                                                        distances.ToString(s),
                                                        demands.Demand(s),
                                                        distances.ToString(t),
                                                        demands.Demand(t),
                                                        distances.Run(s, t)));
                        source = model.Next(assignment, source);
                    }

                    Console.WriteLine("Total Distance for Vehicle " + i + ": " + total + "\n");
                }
            }

            Console.ReadKey();
        }
예제 #53
0
 public virtual void EndVisit(Assignment node)
 {
     CommonEndVisit(node);
 }
        /// <summary>
        /// Creates or updates a Blueprint assignment in a management group.
        /// </summary>
        /// <param name='operations'>
        /// The operations group for this extension method.
        /// </param>
        /// <param name='managementGroupName'>
        /// The name of the management group where the assignment will be saved.
        /// </param>
        /// <param name='assignmentName'>
        /// The name of the assignment.
        /// </param>
        /// <param name='assignment'>
        /// The assignment object to save.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public static async Task <Assignment> CreateOrUpdateInManagementGroupAsync(this IAssignmentsOperations operations, string managementGroupName, string assignmentName, Assignment assignment, CancellationToken cancellationToken = default(CancellationToken))
        {
            var resourceScope = string.Format(Constants.ResourceScopes.ManagementGroupScope, managementGroupName);

            using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceScope, assignmentName, assignment, null, cancellationToken).ConfigureAwait(false))
            {
                return(_result.Body);
            }
        }
예제 #55
0
 public override void VisitAssignment(Assignment a)
 {
     base.VisitAssignment(a);
     definitions.Add(a.Dst);
 }
예제 #56
0
    static void Solve(int size, int forbidden, int seed)
    {
        RoutingModel routing = new RoutingModel(size, 1, 0);

        // Setting the cost function.
        // Put a permanent callback to the distance accessor here. The callback
        // has the following signature: ResultCallback2<int64, int64, int64>.
        // The two arguments are the from and to node inidices.
        RandomManhattan distances = new RandomManhattan(size, seed);

        routing.SetCost(distances);

        // Forbid node connections (randomly).
        Random randomizer            = new Random();
        long   forbidden_connections = 0;

        while (forbidden_connections < forbidden)
        {
            long from = randomizer.Next(size - 1);
            long to   = randomizer.Next(size - 1) + 1;
            if (routing.NextVar(from).Contains(to))
            {
                Console.WriteLine("Forbidding connection {0} -> {1}", from, to);
                routing.NextVar(from).RemoveValue(to);
                ++forbidden_connections;
            }
        }

        // Add dummy dimension to test API.
        routing.AddDimension(new ConstantCallback(),
                             size + 1,
                             size + 1,
                             true,
                             "dummy");

        // Solve, returns a solution if any (owned by RoutingModel).
        RoutingSearchParameters search_parameters =
            RoutingModel.DefaultSearchParameters();

        // Setting first solution heuristic (cheapest addition).
        search_parameters.FirstSolutionStrategy =
            FirstSolutionStrategy.Types.Value.PathCheapestArc;

        Assignment solution = routing.SolveWithParameters(search_parameters);

        Console.WriteLine("Status = {0}", routing.Status());
        if (solution != null)
        {
            // Solution cost.
            Console.WriteLine("Cost = {0}", solution.ObjectiveValue());
            // Inspect solution.
            // Only one route here; otherwise iterate from 0 to routing.vehicles() - 1
            int route_number = 0;
            for (long node = routing.Start(route_number);
                 !routing.IsEnd(node);
                 node = solution.Value(routing.NextVar(node)))
            {
                Console.Write("{0} -> ", node);
            }
            Console.WriteLine("0");
        }
    }
예제 #57
0
 public void VisitAssignment(Assignment ass)
 {
     throw new NotImplementedException();
 }
 private Timesheet GetTimesheet(Assignment assignment)
 {
     return(timesheets.FirstOrDefault(t => assignment.Placement.Id == t.PlacementId &&
                                      assignment.Start == t.Start &&
                                      assignment.Start.AddSeconds((double)assignment.Duration) == t.End));
 }
예제 #59
0
 internal Assignment(Assignment other)
 {
     Tiles = new List <ushort>(other.Tiles);
     Rules = other.Rules.Select(rule => new Rule(rule)).ToList();
 }
예제 #60
0
        protected override bool ShouldGenerateClass(Node node)
        {
            Assignment assignment = node as Assignment;

            return(assignment != null);
        }