Наследование: DatabaseObject
Пример #1
0
 public SelectionViewModel(IList<Team> teams1, IList<Team> teams2, IList<Division> divisions, Team team1 = null, Team team2 = null, Division division1 = null, Division division2 = null)
 {
     Team1List = new SelectList(teams1, "Id", "FullName", team1 != null ? team1.Id.ToString() : string.Empty);
     Team2List = new SelectList(teams2, "Id", "FullName", team2 != null ? team2.Id.ToString() : string.Empty);
     Division1List = new SelectList(divisions, "Id", "Name", division1 != null ? division1.Id.ToString() : string.Empty);
     Division2List = new SelectList(divisions, "Id", "Name", division2 != null ? division2.Id.ToString() : string.Empty);
 }
 /// <summary>
 /// 增加客户类别
 /// </summary>
 /// <param name="pc"></param>
 /// <param name="parent"></param>
 /// <returns></returns>
 public TreeNode AddDivisionNode(Division pc, TreeNode parent)
 {
     TreeNode node = parent.Nodes.Add(string.Format("{0}", pc.Name));
     RenderDeptNode(pc, node);
     _AllDivisionNodes.Add(node);
     return node;
 }
Пример #3
0
 public static DivisionDto ConvertToDto(Division d)
 {
     return new DivisionDto
     {
         Id = d.Id,
         Name = d.Name
     };
 }
Пример #4
0
 public void GetDivisionRecordsTest()
 {
     context = new CSBCDbContext();
     var house = new Division();
     var rep = new DivisionRepository(context);
     var seasonRep = new SeasonRepository(context);
     var season = seasonRep.GetCurrentSeason(1);
     var divisions = rep.GetDivisions(season.SeasonID);
     Assert.IsTrue(divisions.Any<Division>());
 }
 protected override Object GetItemFromInput()
 {
     Division ct = UpdatingItem as Division;
     if (IsAdding)
     {
         ct = new Division();
     }
     ct.Name = txtName.Text;
     ct.Parent = ParentDivision != null ? ParentDivision.ID : null;
     ct.Memo = txtMemo.Text;
     return ct;
 }
Пример #6
0
        protected Division CreateDivision()
        {
            Division division = new Division();
            division.ID = Guid.NewGuid();
            division.AllocateByAxe = TestHelper.GetRandomBool();
            division.AllocateByBrand = TestHelper.GetRandomBool();
            division.Code = ticks.Substring(ticks.Length-10, 10);
            division.Deleted = TestHelper.GetRandomBool();
            division.Name = "DivisionName" + ticks;

            return division;
        }
Пример #7
0
 private Team MakeTeam(string teamName, string shortTeamName, Conference conference, Division division,
     int teamRating, int homeBonus)
 {
     return new Team
     {
         Name = teamName,
         ShortName = shortTeamName,
         Conference = conference,
         Division = division,
         Rating = teamRating,
         HomeBonus = homeBonus,
         Record = new Record()
     };
 }
Пример #8
0
 public void InitDivisionTest()
 {
     context = new CSBCDbContext();
     var repDivision = new DivisionRepository(context);
     var division = new Division
     {
         Div_Desc = "Unit Test",
         CompanyID = 1,
         Gender = "M",
         MinDate = DateTime.Now,
         MaxDate = DateTime.Now.AddDays(60)
     };
     var divisionret = repDivision.Insert(division);
     Assert.IsTrue(divisionret != null);
 }
 private List<Division> GetDesendents(Division division)
 {
     if (division != null)
     {
         var _Divisions = new DivisionBLL(AppSettings.Current.ConnStr).GetItems(null).QueryObjects;
         List<Division> chs = new List<Division>();
         if (_Divisions != null && _Divisions.Count > 0)
         {
             foreach (Division d in _Divisions)
             {
                 if (IsDescendantOf(d, division, _Divisions)) chs.Add(d);
             }
         }
         return chs;
     }
     return null;
 }
Пример #10
0
        public ActionResult Divisions_Create([DataSourceRequest]DataSourceRequest request, Division division)
        {
            if (this.ModelState.IsValid)
            {
                var entity = new Division
                {
                    Name = division.Name,
                    CreatedOn = division.CreatedOn,
                    ModifiedOn = division.ModifiedOn,
                    IsDeleted = division.IsDeleted,
                    DeletedOn = division.DeletedOn
                };

                this.db.Divisions.Add(entity);
                this.db.SaveChanges();
                division.Id = entity.Id;
            }

            return this.Json(new[] { division }.ToDataSourceResult(request, this.ModelState));
        }
Пример #11
0
    public static void Main()
    {
        var marcin = new Employe("Marcin");
        var krzysiek = new Employe("Krzysiek");
        var marta = new Employe("Marta");

        marcin.Pay(100);
        krzysiek.Pay(120);
        marta.Pay(130);

        var dcgEmployes = new Division("DCG", new List<IEmploye>{marcin, krzysiek});
        var sgxEmployes = new Division("SGX", new List<IEmploye>{marta});

        var polandEmployes = new Division("Poland", new List<IEmploye>{dcgEmployes, sgxEmployes});
        var allEmployes = new Division("All", new List<IEmploye>{polandEmployes});

        allEmployes.Pay(10);
        Console.WriteLine("We have spend:");
        allEmployes.DisplayPayment();
    }
Пример #12
0
    public LeagueList()
    {
        Leagues = new ObservableCollection<League>();

        var leagueA = new League("League A");
        Leagues.Add(leagueA);

        var leagueB = new League("League B");
        Leagues.Add(leagueB);

            var divisionA = new Division("Division A");
            leagueB.Divisions.Add(divisionA);

            var divisionB = new Division("Division B");
            leagueB.Divisions.Add(divisionB);

            var divisionC = new Division("Division C");
            leagueB.Divisions.Add(divisionC);

                var east = new Team("Team East");
                divisionC.Teams.Add(east);

                var west = new Team("Team West");
                divisionC.Teams.Add(west);

                var north = new Team("Team North");
                divisionC.Teams.Add(north);

                var south = new Team("Team South");
                divisionC.Teams.Add(south);

            var divisionD = new Division("Division D");
            leagueB.Divisions.Add(divisionD);

        var leagueC = new League("League C");
        Leagues.Add(leagueC);
    }
Пример #13
0
        protected UserRole CreateUserRole(Division division, Role role, User user)
        {
            UserRole userRole = new UserRole();
            userRole.Division = division;
            userRole.Role = role;
            userRole.User = user;

            return userRole;
        }
Пример #14
0
 public void QuotientTest()
 {
     Assert.AreEqual(2, Division.Quotient(a, b));
 }
Пример #15
0
        protected AnimationProduct CreateAnimationProduct(Division division, Animation animation, int normalMultiple, int warehouseMultiple, Signature signature)
        {
            AnimationProduct animationProduct = new AnimationProduct();
            animationProduct.ID = Guid.NewGuid();
            animationProduct.Animation = animation;
            animationProduct.ItemType = CreateItemType(division);
            animationProduct.ItemGroup = CreateItemGroup(division);
            animationProduct.Product = CreateProduct(division);
            animationProduct.Signature = signature;
            if (normalMultiple == warehouseMultiple)
            {
                Multiple multiple = CreateMultiple(animationProduct.Product, normalMultiple);
                animationProduct.Multiple = multiple;
                animationProduct.Multiple1 = multiple;
            }
            else
            {
                animationProduct.Multiple = CreateMultiple(animationProduct.Product, normalMultiple);
                animationProduct.Multiple1 = CreateMultiple(animationProduct.Product, warehouseMultiple);
            }          
            animationProduct.OnCAS = true;
            animationProduct.ConfirmedMADMonth = DateTime.Now;
            animationProduct.StockRisk = true;
            animationProduct.DeliveryRisk = true;
            animationProduct.SortOrder = 1;

            return animationProduct;
        }
Пример #16
0
 public void Visit(Division div)
 {
     div.Left.Accept(this);
     _sb.Append("/");
     div.Right.Accept(this);
 }
Пример #17
0
        public override void Given()
        {
            viewModel = new CreateDivisionViewModel();
              viewModel.Name = "MyDivision";
              viewModel.StartingDate = DateTime.Parse("11/30/2010").ToShortDateString();
              viewModel.SeasonId = 1;

              var season = new Season("temp", GameType.EightBall);
              var division = new Division(viewModel.Name, DateTime.Now, season);
              season.SetIdTo(viewModel.SeasonId);
              season.AddDivision(division);
              repository.Setup(r => r.Get<Season>(season.Id)).Returns(season);

              var divisions = new List<Division> { division };
              repository.Setup(r => r.All<Division>()).Returns(divisions.AsQueryable());
        }
Пример #18
0
 partial void UpdateDivision(Division instance);
Пример #19
0
        private void PopulateCache()
        {
            momentCusps = new double[opts.Divisions.Length][];
            zhCusps     = new ZodiacHouse.Name[opts.Divisions.Length][];
            for (int i = 0; i < opts.Divisions.Length; i++)
            {
                Division  dtype = opts.Divisions[i];
                ArrayList al    = new ArrayList();
                ArrayList zal   = new ArrayList();
                //Console.WriteLine ("Calculating cusps for {0} between {1} and {2}",
                //	dtype, this.utToMoment(ut_lower), this.utToMoment(ut_higher));
                double ut_curr = ut_lower - (1.0 / (24.0 * 60.0));

                sweph.obtainLock(h);
                BodyPosition bp = Basics.CalculateSingleBodyPosition(ut_curr, sweph.BodyNameToSweph(mBody), mBody,
                                                                     BodyType.Name.Graha, h);
                sweph.releaseLock(h);
                //BodyPosition bp = (BodyPosition)h.getPosition(mBody).Clone();
                //DivisionPosition dp = bp.toDivisionPosition(this.dtypeRasi);

                DivisionPosition dp = bp.toDivisionPosition(dtype);

                //Console.WriteLine ("Longitude at {0} is {1} as is in varga rasi {2}",
                //	this.utToMoment(ut_curr), bp.longitude, dp.zodiac_house.value);

                //bp.longitude = new Longitude(dp.cusp_lower - 0.2);
                //dp = bp.toDivisionPosition(dtype);

                while (true)
                {
                    Moment    m        = this.utToMoment(ut_curr);
                    Longitude foundLon = new Longitude(0);
                    bool      bForward = true;

                    //Console.WriteLine ("    Starting search at {0}", this.utToMoment(ut_curr));

                    ut_curr = cs.TransitSearch(mBody, this.utToMoment(ut_curr), true,
                                               new Longitude(dp.cusp_higher), foundLon, ref bForward);

                    bp.longitude = new Longitude(dp.cusp_higher + 0.1);
                    dp           = bp.toDivisionPosition(dtype);

                    if (ut_curr >= ut_lower && ut_curr <= ut_higher + (1.0 / (24.0 * 60.0 * 60.0)) * 5.0)
                    {
                        //	Console.WriteLine ("{0}: {1} at {2}",
                        //		dtype, foundLon, this.utToMoment(ut_curr));
                        al.Add(ut_curr);
                        zal.Add(dp.zodiac_house.value);
                    }
                    else if (ut_curr > ut_higher)
                    {
                        //	Console.WriteLine ("- {0}: {1} at {2}",
                        //		dtype, foundLon, this.utToMoment(ut_curr));
                        break;
                    }
                    ut_curr += ((1.0 / (24.0 * 60.0 * 60.0)) * 5.0);
                }
                momentCusps[i] = (double[])al.ToArray(typeof(double));
                zhCusps[i]     = (ZodiacHouse.Name[])zal.ToArray(typeof(ZodiacHouse.Name));
            }


            //for (int i=0; i<opts.Divisions.Length; i++)
            //{
            //	for (int j=0; j<momentCusps[i].Length; j++)
            //	{
            //		Console.WriteLine ("Cusp for {0} at {1}", opts.Divisions[i], momentCusps[i][j]);
            //	}
            //}
        }
Пример #20
0
        public static double ZScore(dynamic score, dynamic mean, dynamic stdDev)
        {
            var zScore = Division.Divide(Subtraction.Minus(score, mean), stdDev);

            return(zScore);
        }
Пример #21
0
        public double Execute(Operation operation, Dictionary <string, double> variables)
        {
            if (operation == null)
            {
                throw new ArgumentNullException("operation");
            }

            if (operation.GetType() == typeof(IntegerConstant))
            {
                IntegerConstant constant = (IntegerConstant)operation;
                return(constant.Value);
            }
            else if (operation.GetType() == typeof(FloatingPointConstant))
            {
                FloatingPointConstant constant = (FloatingPointConstant)operation;
                return(constant.Value);
            }
            else if (operation.GetType() == typeof(Variable))
            {
                Variable variable = (Variable)operation;
                if (variables.ContainsKey(variable.Name))
                {
                    return(variables[variable.Name]);
                }
                else
                {
                    throw new VariableNotDefinedException(string.Format("The variable \"{0}\" used is not defined.", variable.Name));
                }
            }
            else if (operation.GetType() == typeof(Multiplication))
            {
                Multiplication multiplication = (Multiplication)operation;
                return(Execute(multiplication.Argument1, variables) * Execute(multiplication.Argument2, variables));
            }
            else if (operation.GetType() == typeof(Addition))
            {
                Addition addition = (Addition)operation;
                return(Execute(addition.Argument1, variables) + Execute(addition.Argument2, variables));
            }
            else if (operation.GetType() == typeof(Substraction))
            {
                Substraction addition = (Substraction)operation;
                return(Execute(addition.Argument1, variables) - Execute(addition.Argument2, variables));
            }
            else if (operation.GetType() == typeof(Division))
            {
                Division division = (Division)operation;
                return(Execute(division.Dividend, variables) / Execute(division.Divisor, variables));
            }
            else if (operation.GetType() == typeof(Exponentiation))
            {
                Exponentiation exponentiation = (Exponentiation)operation;
                return(Math.Pow(Execute(exponentiation.Base, variables), Execute(exponentiation.Exponent, variables)));
            }
            else if (operation.GetType() == typeof(Function))
            {
                Function function = (Function)operation;

                switch (function.FunctionType)
                {
                case FunctionType.Sine:
                    return(Math.Sin(Execute(function.Arguments[0], variables)));

                case FunctionType.Cosine:
                    return(Math.Cos(Execute(function.Arguments[0], variables)));

                case FunctionType.Loge:
                    return(Math.Log(Execute(function.Arguments[0], variables)));

                case FunctionType.Log10:
                    return(Math.Log10(Execute(function.Arguments[0], variables)));

                case FunctionType.Logn:
                    return(Math.Log(Execute(function.Arguments[0], variables), Execute(function.Arguments[1], variables)));

                default:
                    throw new ArgumentException(string.Format("Unsupported function \"{0}\".", function.FunctionType), "operation");
                }
            }
            else
            {
                throw new ArgumentException(string.Format("Unsupported operation \"{0}\".", operation.GetType().FullName), "operation");
            }
        }
Пример #22
0
        private void GenerateMethodBody(ILGenerator generator, Operation operation)
        {
            if (operation == null)
            {
                throw new ArgumentNullException("operation");
            }

            if (operation.GetType() == typeof(IntegerConstant))
            {
                IntegerConstant constant = (IntegerConstant)operation;

                generator.Emit(OpCodes.Ldc_I4, constant.Value);
                generator.Emit(OpCodes.Conv_R8);
            }
            else if (operation.GetType() == typeof(FloatingPointConstant))
            {
                FloatingPointConstant constant = (FloatingPointConstant)operation;

                generator.Emit(OpCodes.Ldc_R8, constant.Value);
            }
            else if (operation.GetType() == typeof(Variable))
            {
                Type dictionaryType = typeof(Dictionary <string, double>);

                Variable variable = (Variable)operation;

                Label throwExceptionLabel = generator.DefineLabel();
                Label returnLabel         = generator.DefineLabel();

                generator.Emit(OpCodes.Ldarg_0);
                generator.Emit(OpCodes.Ldstr, variable.Name);
                generator.Emit(OpCodes.Callvirt, dictionaryType.GetMethod("ContainsKey", new Type[] { typeof(string) }));
                generator.Emit(OpCodes.Ldc_I4_0);
                generator.Emit(OpCodes.Ceq);
                generator.Emit(OpCodes.Brtrue_S, throwExceptionLabel);

                generator.Emit(OpCodes.Ldarg_0);
                generator.Emit(OpCodes.Ldstr, variable.Name);
                generator.Emit(OpCodes.Callvirt, dictionaryType.GetMethod("get_Item", new Type[] { typeof(string) }));
                generator.Emit(OpCodes.Br_S, returnLabel);

                generator.MarkLabel(throwExceptionLabel);
                generator.Emit(OpCodes.Ldstr, string.Format("The variable \"{0}\" used is not defined.", variable.Name));
                generator.Emit(OpCodes.Newobj, typeof(VariableNotDefinedException).GetConstructor(new Type[] { typeof(string) }));
                generator.Emit(OpCodes.Throw);

                generator.MarkLabel(returnLabel);
            }
            else if (operation.GetType() == typeof(Multiplication))
            {
                Multiplication multiplication = (Multiplication)operation;
                GenerateMethodBody(generator, multiplication.Argument1);
                GenerateMethodBody(generator, multiplication.Argument2);

                generator.Emit(OpCodes.Mul);
            }
            else if (operation.GetType() == typeof(Addition))
            {
                Addition addition = (Addition)operation;
                GenerateMethodBody(generator, addition.Argument1);
                GenerateMethodBody(generator, addition.Argument2);

                generator.Emit(OpCodes.Add);
            }
            else if (operation.GetType() == typeof(Substraction))
            {
                Substraction addition = (Substraction)operation;
                GenerateMethodBody(generator, addition.Argument1);
                GenerateMethodBody(generator, addition.Argument2);

                generator.Emit(OpCodes.Sub);
            }
            else if (operation.GetType() == typeof(Division))
            {
                Division division = (Division)operation;
                GenerateMethodBody(generator, division.Dividend);
                GenerateMethodBody(generator, division.Divisor);

                generator.Emit(OpCodes.Div);
            }
            else if (operation.GetType() == typeof(Exponentiation))
            {
                Exponentiation exponentation = (Exponentiation)operation;
                GenerateMethodBody(generator, exponentation.Base);
                GenerateMethodBody(generator, exponentation.Exponent);

                generator.Emit(OpCodes.Call, typeof(Math).GetMethod("Pow"));
            }
            else if (operation.GetType() == typeof(Function))
            {
                Function function = (Function)operation;

                switch (function.FunctionType)
                {
                case FunctionType.Sine:
                    GenerateMethodBody(generator, function.Arguments[0]);

                    generator.Emit(OpCodes.Call, typeof(Math).GetMethod("Sin"));
                    break;

                case FunctionType.Cosine:
                    GenerateMethodBody(generator, function.Arguments[0]);

                    generator.Emit(OpCodes.Call, typeof(Math).GetMethod("Cos"));
                    break;

                case FunctionType.Loge:
                    GenerateMethodBody(generator, function.Arguments[0]);

                    generator.Emit(OpCodes.Call, typeof(Math).GetMethod("Log", new Type[] { typeof(double) }));
                    break;

                case FunctionType.Log10:
                    GenerateMethodBody(generator, function.Arguments[0]);

                    generator.Emit(OpCodes.Call, typeof(Math).GetMethod("Log10"));
                    break;

                case FunctionType.Logn:
                    GenerateMethodBody(generator, function.Arguments[0]);
                    GenerateMethodBody(generator, function.Arguments[1]);

                    generator.Emit(OpCodes.Call, typeof(Math).GetMethod("Log", new Type[] { typeof(double), typeof(double) }));
                    break;

                default:
                    throw new ArgumentException(string.Format("Unsupported function \"{0}\".", function.FunctionType), "operation");
                }
            }
            else
            {
                throw new ArgumentException(string.Format("Unsupported operation \"{0}\".", operation.GetType().FullName), "operation");
            }
        }
Пример #23
0
 public void DeleteDivision(Division division)
 {
     _repository.DeleteDivision(division);
 }
Пример #24
0
        private void button2_Click(object sender, EventArgs e)
        {
            //load File
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                using (var reader = new StreamReader(openFileDialog1.FileName))
                {
                    String raw = reader.ReadLine();
                    raw = reader.ReadLine();

                    while (raw != null)
                    {
                        string[] report = raw.Split(',');

                        manager.addDivision(report[0]);
                        bool vending = false;
                        if (report[4].Equals("YES"))
                        {
                            vending = true;
                        }

                        bool staffing = false;
                        if (report[5].Equals("FULL"))
                        {
                            staffing = true;
                        }

                        manager.addEntrance(report[0], report[1], report[2], Convert.ToDouble(report[6], CultureInfo.InvariantCulture),
                                            Convert.ToDouble(report[7], CultureInfo.InvariantCulture), report[3], vending, staffing);
                        raw = reader.ReadLine();
                    }
                }
            }

            // Carga la tabla
            Hashtable temp = manager.getDivisions();

            foreach (DictionaryEntry element in temp)
            {
                Division div = (Division)element.Value;

                List <Entrance> ent = div.GetEntrances();

                foreach (Entrance entry in ent)
                {
                    int n = table.Rows.Add();

                    table.Rows[n].Cells[0].Value = div.getName();
                    table.Rows[n].Cells[1].Value = entry.getLine();
                    table.Rows[n].Cells[2].Value = entry.getStationName();
                    table.Rows[n].Cells[3].Value = entry.getLatitude();
                    table.Rows[n].Cells[4].Value = entry.getLongitude();
                    table.Rows[n].Cells[5].Value = entry.getType();
                    table.Rows[n].Cells[6].Value = entry.getVendingText();
                    table.Rows[n].Cells[7].Value = entry.getStaffingText();
                }
            }
            searchLineButton.Enabled      = true;
            searchNameButton.Enabled      = true;
            searchLatitudeButton.Enabled  = true;
            searchLongitudeButton.Enabled = true;
            loadMapButton.Enabled         = true;
            resetTableButton.Enabled      = true;
            graphButton.Enabled           = true;
            comboBox1.Enabled             = true;
            typeComboBox.Enabled          = true;
            vendingComboBox.Enabled       = true;
            staffingComboBox.Enabled      = true;
        }
Пример #25
0
        private static List <Entry> SearchDataModel()
        {
            var entries = new List <Entry>();

            var uk        = new RegionInfo("en-UK");
            var derby     = new Municipality("Derby");
            var catterick = new Municipality("Catterick");
            var london    = new Municipality("London");
            var audit     = new SimpleAudit("*****@*****.**");

            var scrapBook = new SimplePublication("1st Derbyshire Yeomanry Scrapbook 1939 - 1947",
                                                  new VariousAuthors(),
                                                  new UnknownEditors(),
                                                  new UnknownPublicationDateTime(),
                                                  new SimplePublisher("Bemrose & Sons Ltd",
                                                                      new List <IPostalAddress>()
            {
                new SimplePostalAddress(derby, uk),
                new SimplePostalAddress(london, uk)
            }
                                                                      )
                                                  );

            var mobilisationDate = new FuzzyDateTime(new DateTime(1939, 7, 29), "yyyy/MM/dd");
            var veDay            = new FuzzyDateTime(new DateTime(1945, 5, 8), "yyyy/MM/dd");

            var armouredCar = new TemporalRole(
                new Reconnaissance(),
                new FuzzyDateRange(
                    mobilisationDate),
                GetCitationPage(1, scrapBook),
                audit);



            var firstDerbyshireYeomanry = new Regiment("1st Derbyshire Yeomanry", armouredCar, uk, GetCitationPage(1, scrapBook),
                                                       audit);

            var siddalsRoad        = new SimplePostalAddress(null, new SimpleStreetAddress(91, "Siddals Road"), derby, null, null, uk, null, null);
            var siddalsRoadPosting = new TemporalLocation(siddalsRoad, new FuzzyDateRange(mobilisationDate),
                                                          GetCitationPage(1, scrapBook),
                                                          audit);

            firstDerbyshireYeomanry.AddLocation(siddalsRoadPosting);

            var mccHarrison = new Person("M.C.C", "Harrision", null, uk, GetCitationPage(2, scrapBook),
                                         audit);

            var commandFirstDerbyshireYeomanryPosting = new TemporalRole(new LieutenantColonel(firstDerbyshireYeomanry, mccHarrison),
                                                                         new FuzzyDateRange(
                                                                             new FuzzyDateTime(new DateTime(1939, 11, 7), "yyy/MM"),
                                                                             new FuzzyDateTime(new DateTime(1941, 4, 1), "yyy/MM")
                                                                             ),
                                                                         GetCitationPage(1, scrapBook),
                                                                         audit);

            firstDerbyshireYeomanry.AddPersonel(commandFirstDerbyshireYeomanryPosting);
            mccHarrison.AddAppointment(commandFirstDerbyshireYeomanryPosting);



            var ashbourneRoad        = new SimplePostalAddress(null, new SimpleStreetAddress("Ashbourne Road"), derby, null, null, uk, null, null);
            var ashbourneRoadPosting = new TemporalLocation(ashbourneRoad, new FuzzyDateRange(new FuzzyDateTime(new DateTime(1939, 11, 1), "yyyy/MM"), new FuzzyDateTime(new DateTime(1940, 05, 1), "yyyy/MM")),
                                                            GetCitationPage(2, scrapBook),
                                                            audit);

            firstDerbyshireYeomanry.AddLocation(ashbourneRoadPosting);
            mccHarrison.AddLocation(ashbourneRoadPosting);



            var cavalryDivison = new TemporalRole(
                new Cavalry(),
                new FuzzyDateRange(
                    mobilisationDate),
                GetCitationPage(4, scrapBook),
                audit);
            var catterickGarrision        = new SimplePostalAddress(null, null, catterick, null, null, uk, null, null);
            var catterickGarrisionPosting = new TemporalLocation(catterickGarrision, new FuzzyDateRange(mobilisationDate, new FuzzyDateTime(new DateTime(1940, 05, 1), "yyyy/MM")),
                                                                 GetCitationPage(4, scrapBook),
                                                                 audit);

            var firstCavalryDivision = new Division("1st Cavalry", armouredCar, uk,
                                                    GetCitationPage(4, scrapBook),
                                                    audit);

            firstCavalryDivision.AddLocation(catterickGarrisionPosting);

            var cocFirstDerbyshireYeomanry = new TemporalChainOfCommand(firstCavalryDivision, firstDerbyshireYeomanry, new FuzzyDateRange(mobilisationDate, new FuzzyDateTime(new DateTime(1940, 05, 1), "yyyy/MM")),
                                                                        GetCitationPage(4, scrapBook),
                                                                        audit);

            firstCavalryDivision.AddHierarchy(cocFirstDerbyshireYeomanry);
            firstDerbyshireYeomanry.AddHierarchy(cocFirstDerbyshireYeomanry);

            var search = new FuzzyDateRange(new FuzzyDateTime(new DateTime(1939, 1, 1), "yyyy/MM/dd"), new FuzzyDateTime(new DateTime(1940, 12, 31), "yyyy/MM/dd"));


            var aSquadron = new Squadron("A", armouredCar, uk, GetCitationPage(7, scrapBook), audit);
            var bSquadron = new Squadron("B", armouredCar, uk, GetCitationPage(7, scrapBook), audit);
            var cSquadron = new Squadron("C", armouredCar, uk, GetCitationPage(7, scrapBook), audit);
            var dSquadron = new Squadron("D", armouredCar, uk, GetCitationPage(7, scrapBook), audit);


            EstablishChainOfCommand(firstDerbyshireYeomanry, aSquadron, mobilisationDate, veDay, GetCitationPage(4, scrapBook), audit);
            EstablishChainOfCommand(firstDerbyshireYeomanry, bSquadron, mobilisationDate, veDay, GetCitationPage(4, scrapBook), audit);
            EstablishChainOfCommand(firstDerbyshireYeomanry, cSquadron, mobilisationDate, veDay, GetCitationPage(4, scrapBook), audit);
            EstablishChainOfCommand(firstDerbyshireYeomanry, dSquadron, mobilisationDate, veDay, GetCitationPage(4, scrapBook), audit);

            var caistor       = new Municipality("Caistor");
            var talbotArms    = new SimplePostalAddress(null, new SimpleStreetAddress("16 High Street"), caistor, null, new SimplePostalCode("LN7 6QF"), uk, null, null);
            var rotationStart = new DateTime(1939, 11, 27);
            var rotationEnd   = new DateTime(1940, 5, 24);
            int rotation      = 0;

            while (rotationStart < rotationEnd)
            {
                var talbotArmsPostingRotation = new TemporalLocation(talbotArms, new FuzzyDateRange(new FuzzyDateTime(rotationStart, "yyyy/MM/dd"), 14),
                                                                     GetCitationPage(2, scrapBook),
                                                                     audit);
                rotationStart = rotationStart.AddDays(14);
                int i = rotation % 4;
                switch (i)
                {
                case 0:
                    aSquadron.AddLocation(talbotArmsPostingRotation);
                    entries.Add(GetEntry(aSquadron, talbotArmsPostingRotation));
                    break;

                case 1:
                    bSquadron.AddLocation(talbotArmsPostingRotation);
                    entries.Add(GetEntry(bSquadron, talbotArmsPostingRotation));
                    break;

                case 2:
                    cSquadron.AddLocation(talbotArmsPostingRotation);
                    entries.Add(GetEntry(cSquadron, talbotArmsPostingRotation));
                    break;

                case 3:
                    dSquadron.AddLocation(talbotArmsPostingRotation);
                    entries.Add(GetEntry(dSquadron, talbotArmsPostingRotation));
                    break;
                }

                rotation++;
            }


            entries.Add(GetEntry(firstDerbyshireYeomanry, firstDerbyshireYeomanry.Locations[0]));
            entries.Add(GetEntry(firstDerbyshireYeomanry, firstDerbyshireYeomanry.Locations[1]));
            entries.Add(GetEntry(mccHarrison, mccHarrison.Locations[0]));
            entries.Add(GetEntry(firstCavalryDivision, firstCavalryDivision.Locations[0]));


            return(entries);
        }
Пример #26
0
 public void Visit(Division div)
 {
     ResultIsIntAndBothOperandsMustBeInt(div);
 }
Пример #27
0
 public override DivisionModifier ModifyDivision(Division divisionToModify)
 {
     //kill a random unit
     return(base.ModifyDivision(divisionToModify));
 }
Пример #28
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["login_data"] == null)
        {
            Response.Redirect("../index.aspx");
        }
        else
        {
            //ตรวจสอบสิทธิ์
            login_data = (UserLoginData)Session["login_data"];
            if (autro_obj.CheckGroupUser(login_data, group_var.admin_university) || autro_obj.CheckGroupUser(login_data, group_var.admin_faculty))
            {
                /*=============================*/
                FacultyId        = Request.QueryString["FacId"];
                Session["FacId"] = FacultyId;

                if (!Page.IsPostBack)
                {
                    String sqlCommand = "Select * From MEMBER Where DIVISION_ID = '" + FacultyId + "'";
                    memberData = memberObj.getMemberFromCommand(sqlCommand);


                    lblFaculty.Text = facultyLabel.getFaculty(FacultyId).Faculty_Thai;

                    // Head Table
                    string[] ar = { "ชื่อผู้ใช้", "ชื่อ-นามสกุล", "สังกัดภาควิชา/กอง", "สังกัดคณะ/สำนัก", "ลบ" };
                    //Table tb1 = new Table();
                    tblUsers.Attributes.Add("class", "table table-bordered table-striped table-hover");
                    tblUsers.Attributes.Add("id", "dt_basic");
                    TableHeaderRow tRowHead = new TableHeaderRow();
                    tRowHead.TableSection = TableRowSection.TableHeader;
                    for (int cellCtr = 1; cellCtr <= ar.Length; cellCtr++)
                    {
                        // Create a new cell and add it to the row.
                        TableHeaderCell cellHead = new TableHeaderCell();
                        cellHead.Text = ar[cellCtr - 1];
                        tRowHead.Cells.Add(cellHead);
                    }

                    tblUsers.Rows.Add(tRowHead);

                    foreach (Member data in memberData)
                    {
                        TableRow tRowBody = new TableRow();
                        tRowBody.TableSection = TableRowSection.TableBody;

                        TableCell cellUserId = new TableCell();
                        cellUserId.Text = data.MEMBER_USER_ID;
                        tRowBody.Cells.Add(cellUserId);

                        TableCell cellUserNameThai = new TableCell();
                        Prefix    prefixObj        = new Prefix();
                        cellUserNameThai.Text = prefixObj.getPrefix(userObj.getUsers(data.MEMBER_USER_ID).USERS_INFO_TITLE_THAINAME).Prefix_Thai + userObj.getUsers(data.MEMBER_USER_ID).USERS_INFO_FIRST_THAINAME + " " + userObj.getUsers(data.MEMBER_USER_ID).USERS_INFO_FAMILY_THAINAME;
                        tRowBody.Cells.Add(cellUserNameThai);

                        TableCell  cellDepartment = new TableCell();
                        Department departmentObj  = new Department();
                        cellDepartment.Text = departmentObj.getDepartment(data.MEMBER_DEPARTMENT_ID).Department_Thai;

                        if (cellDepartment.Text == "")
                        {
                            Division divisionObj = new Division();
                            cellDepartment.Text = divisionObj.getDivision(data.MEMBER_DEPARTMENT_ID).Division_Thai;
                        }

                        tRowBody.Cells.Add(cellDepartment);

                        TableCell cellFaculty = new TableCell();
                        Faculty   facultyObj  = new Faculty();
                        cellFaculty.Text = facultyObj.getFaculty(data.MEMBER_DIVISION_ID).Faculty_Thai;
                        tRowBody.Cells.Add(cellFaculty);

                        TableCell cellDel = new TableCell();
                        //string urlDel = "#";
                        string    urlDel = "delete_Member_Faculty.aspx?Uid=" + data.MEMBER_USER_ID + "&FacId=" + data.MEMBER_DIVISION_ID + "&DeptId=" + data.MEMBER_DEPARTMENT_ID;
                        HyperLink hypDel = new HyperLink();
                        hypDel.Attributes.Add("data-target", "#deleteMember");
                        hypDel.Attributes.Add("data-toggle", "modal");
                        hypDel.Text        = "<h4><i class='fa fa-trash-o'></i></h4>";
                        hypDel.NavigateUrl = urlDel;
                        hypDel.ToolTip     = "Delete";
                        cellDel.Controls.Add(hypDel);
                        cellDel.CssClass = "text-center";
                        tRowBody.Cells.Add(cellDel);

                        tblUsers.Rows.Add(tRowBody);
                    }
                }    //end !Page.IsPostBack
                /*=============================*/
            }
            else
            {
                HttpContext.Current.Session["response"] = "ตรวจสอบไม่พบสิทธิ์การเข้าใช้งาน";
                HttpContext.Current.Response.Redirect("err_response.aspx");
            }
        }
    }
Пример #29
0
 public void Visit(Division div)
 {
     // Nothing to do here...
 }
Пример #30
0
        static void Main(string[] args)
        {
            float num1 = 0;
            float num2 = 0;
            int   option;

            Console.WriteLine();
            Console.WriteLine("         WELCOME TO MYCALCULATOR SYSTEM");
            Console.WriteLine("__________________________________________________");
            Console.WriteLine();
            Console.WriteLine("Follow the instructions bellow to do your calcs.");
            Console.WriteLine();

            do
            {
                Console.WriteLine("Select an operation:");
                Console.WriteLine();
                Console.WriteLine("     1 - Addition");
                Console.WriteLine("     2 - Subtraction");
                Console.WriteLine("     3 - Multiplication");
                Console.WriteLine("     4 - Division");
                Console.WriteLine("     0 - Exit");
                option = int.Parse(Console.ReadLine());

                if (option == 0)
                {
                    Console.WriteLine("Closing the system.");
                    break;
                }

                Console.WriteLine();
                Console.WriteLine("Now insert the numbers:");

                do
                {
                    Console.WriteLine();
                    Console.WriteLine("Insert the first number:");
                    num1 = float.Parse(Console.ReadLine());
                    Console.WriteLine();
                    Console.WriteLine("Insert the second number:");
                    num2 = float.Parse(Console.ReadLine());
                    Console.WriteLine();

                    if (option == 4 && num2 == 0)
                    {
                        Console.WriteLine("A number cannot be divided by zero, please start over.");
                    }
                } while (option == 4 && num2 == 0);

                if (option == 1)
                {
                    Addition operation = new Addition();
                    float    result    = operation.doAddition(num1, num2);
                    Console.WriteLine("The result of the operation (" + num1 + " + " + num2 + ") is " + result + ".");
                }
                else if (option == 2)
                {
                    Subtraction operation = new Subtraction();
                    float       result    = operation.doSubtraction(num1, num2);
                    Console.WriteLine("The result of the operation (" + num1 + " - " + num2 + ") is " + result + ".");
                }
                else if (option == 3)
                {
                    Multiplication operation = new Multiplication();
                    float          result    = operation.doMultiplication(num1, num2);
                    Console.WriteLine("The result of the operation (" + num1 + " * " + num2 + ") is " + result + ".");
                }
                else if (option == 4)
                {
                    Division operation = new Division();
                    float    result    = operation.doDivision(num1, num2);
                    Console.WriteLine("The result of the operation (" + num1 + " / " + num2 + ") is " + result + ".");
                }
                else
                {
                    Console.WriteLine("Closing the system.");
                    break;
                }

                Console.WriteLine();
                Console.WriteLine("Do you want to execute another operation?");
                Console.WriteLine("Type 'yes' to continue.");
                string answer = Console.ReadLine();

                if (answer == "yes")
                {
                    option = 11;
                }
                else
                {
                    option = 0;
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine("Thank you for using MyCalculator.");
                    Console.WriteLine("Closing the system.");
                }
            } while (option > 10);
        }
Пример #31
0
 public virtual void Visit(Division node)
 {
 }
Пример #32
0
        public static Organization GetOrganization(this Position position, ApplicationDbContext context)
        {
            Division positionDiv = context.Divisions.FirstOrDefault(i => i.Id == position.DivisionId);

            return(GetOrganization(positionDiv.OrganizationId, context));
        }
Пример #33
0
 //protected void btnSave_Click(object sender, System.EventArgs e)
 //{
 //    lblError.Text = "";
 //    Session["ErrorMSG"] = "";
 //    if (DivisionId > 0)
 //    {
 //        UpdDivision();
 //    }
 //    else
 //    {
 //        AddDivision();
 //    }
 //}
 //private void AddDivision()
 //{
 //    if (errorRTN() == true)
 //    {
 //        MsgBox("ERROR: " + lblError.Text);
 //        return;
 //    }
 //    if (string.IsNullOrEmpty(Session["ErrorMsg"].ToString()))
 //        ADDRow();
 //    if (string.IsNullOrEmpty(Session["ErrorMsg"].ToString()))
 //        //Interaction.MsgBox("New Record Added Successfully");
 //        if (string.IsNullOrEmpty(Session["ErrorMsg"].ToString()))
 //            LoadTeams(DivisionId);
 //    if (string.IsNullOrEmpty(Session["ErrorMsg"].ToString()))
 //        LoadRow(DivisionId);
 //    if (String.IsNullOrEmpty(Session["ErrorMsg"].ToString()))
 //        ReassignDivision(DivisionId);
 //    if (string.IsNullOrEmpty(Session["ErrorMsg"].ToString()))
 //        LoadDivisions();
 //    lblError.Text = Session["ErrorMsg"].ToString();
 //}
 //private void UpdDivision()
 //{
 //    if (errorRTN() == true)
 //    {
 //        //Interaction.MsgBox("ERROR: " + lblError.Text);
 //        return;
 //    }
 //    if (String.IsNullOrEmpty(Session["ErrorMsg"].ToString()))
 //    {
 //        UpdRow(DivisionId);
 //        //Interaction.MsgBox("Changes successfully completed");
 //        LoadTeams(DivisionId);
 //        LoadRow(DivisionId);
 //        ReassignDivision(DivisionId);
 //        LoadDivisions();
 //    }
 //    else
 //    {
 //        lblError.Text = Session["ErrorMsg"].ToString();
 //    }
 //}
 protected void btnSave_Command(object sender, CommandEventArgs e)
 {
     var division = new Division();
     DateTime date;
     if (lblDivisionID.Value == "")
         division.DivisionID = 0;
     else
         division.DivisionID = Convert.ToInt32(lblDivisionID.Value);
     division.CompanyID = Master.CompanyId;
     division.SeasonID = Master.SeasonId;
     division.Div_Desc = txtName.Text;
     division.MinDate = DateTime.Parse(txtMinDate.Text);
     division.MaxDate = DateTime.Parse(txtMaxDate.Text);
     if (radGender.SelectedIndex == 0)
         division.Gender = "M";
     if (radGender.SelectedIndex == 1)
         division.Gender = "F";
     if (DateTime.TryParse(txtMinDate2.Text, out date))
         division.MinDate2 = date;
     DateTime goodDate;
     if (DateTime.TryParse(txtMaxDate2.Text, out goodDate))
         division.MaxDate2 = DateTime.Parse(txtMaxDate2.Text);
     if (radGender2.SelectedIndex == 0)
         division.Gender2 = "M";
     if (radGender2.SelectedIndex == 1)
         division.Gender2 = "F";
     division.DraftVenue = txtVenue.Text;
     if (DateTime.TryParse(txtDate.Text, out date))
         division.DraftDate = date;
     division.DraftTime = txtTime.Text;
     division.DirectorID = Int32.Parse(cboAD.SelectedValue);
     division.CoDirectorID = 0;
     //cboAD.SelectedValue
     division.CreatedUser = Session["UserName"].ToString();
     using (var db = new CSBCDbContext())
     {
         try
         {
             var rep = new DivisionRepository(db);
             if (division.DivisionID == 0)
             {
                 var newDivision = rep.Insert(division);
                 lblDivisionID.Value = newDivision.DivisionID.ToString();
             }
             else
                 rep.Update(division);
         }
         catch (Exception ex)
         {
             Console.WriteLine("Unable to save" + ex.InnerException);
         }
     }
     ReassignDivision(DivisionId);
     LoadDivisions();
 }
Пример #34
0
 public static Position GetParentPosition(this PositionViewModel positionViewModel, Division division)
 => division.Positions.FirstOrDefault(n => n.Name == positionViewModel.ParentPositionName);
Пример #35
0
        public void CalculationTest(double divisor, double dividend, double expectedResult)
        {
            double actualResult = Division.Calculation(divisor, dividend);

            Assert.AreEqual(expectedResult, actualResult);
        }
Пример #36
0
 /// <summary>
 /// Метод возвращает все должности подразделения
 /// </summary>
 /// <param name="division"></param>
 /// <param name="context"></param>
 /// <returns></returns>
 public static List <Position> GetPositions(this Division division, ApplicationDbContext context)
 => context.Positions.Where(divId => divId.DivisionId == division.Id).ToList();
Пример #37
0
        protected SalesArea CreateSalesArea(DistributionChannel channel, Division division, string SalesOrgCode)
        {
            SalesArea salesArea = new SalesArea();
            salesArea.ID = Guid.NewGuid();
            salesArea.DistributionChannel = channel;
            salesArea.SalesOrganization = CreateSalesOrganization(SalesOrgCode);
            salesArea.Division = division;
            salesArea.Name = "SalesArea1";
            salesArea.Code = "454";
            salesArea.Deleted = false;

            return salesArea;
        }
Пример #38
0
 /// <summary>
 /// Метод возвращает всех сотрудников подразделения
 /// </summary>
 /// <param name="division"></param>
 /// <param name="context"></param>
 /// <returns></returns>
 public static List <Employee> GetEmployees(this Division division, ApplicationDbContext context)
 => context.Employees.Where(divId => divId.DivisionId == division.Id).ToList();
Пример #39
0
        protected Customer CreateCustomer(CustomerGroup customerGroup, string name, string code, SalesEmployee employee, Division division)
        {
            Customer customer = new Customer();
            customer.ID = Guid.NewGuid();
            customer.SalesEmployee = employee;
            customer.CustomerGroup = customerGroup;
            customer.AccountNumber = code;
            customer.Name = name;
            customer.IncludeInSystem = true;
            customer.Manual = false;

            return customer;
        }
Пример #40
0
            /// <summary>
            /// Validates a person object.
            /// </summary>
            public PersonValidator()
            {
                RuleFor(x => x.Id).NotEmpty();
                RuleFor(x => x.LastName).NotEmpty().Length(1, 40)
                .WithMessage("The last name must not be left blank and must not exceed 40 characters.");
                RuleFor(x => x.FirstName).Length(0, 40)
                .WithMessage("The first name must not exceed 40 characters.");
                RuleFor(x => x.MiddleName).Length(0, 40)
                .WithMessage("The middle name must not exceed 40 characters.");
                RuleFor(x => x.Suffix).Length(0, 40)
                .WithMessage("The suffix must not exceed 40 characters.");
                RuleFor(x => x.SSN).NotEmpty().Must(x => System.Text.RegularExpressions.Regex.IsMatch(x, @"^(?!\b(\d)\1+-(\d)\1+-(\d)\1+\b)(?!123-45-6789|219-09-9999|078-05-1120)(?!666|000|9\d{2})\d{3}(?!00)\d{2}(?!0{4})\d{4}$"))
                .WithMessage("The SSN must be valid and contain only numbers.");
                RuleFor(x => x.DateOfBirth).NotEmpty()
                .WithMessage("The DOB must not be left blank.");
                RuleFor(x => x.PRD).NotEmpty()
                .WithMessage("The DOB must not be left blank.");
                RuleFor(x => x.Sex).NotNull()
                .WithMessage("The sex must not be left blank.");
                RuleFor(x => x.Remarks).Length(0, 150)
                .WithMessage("Remarks must not exceed 150 characters.");
                RuleFor(x => x.Command).NotEmpty().WithMessage("A person must have a command.  If you are trying to indicate this person left the command, please set his or her duty status to 'LOSS'.");
                RuleFor(x => x.Department).NotEmpty().WithMessage("A person must have a department.  If you are trying to indicate this person left the command, please set his or her duty status to 'LOSS'.");
                RuleFor(x => x.Division).NotEmpty().WithMessage("A person must have a division.  If you are trying to indicate this person left the command, please set his or her duty status to 'LOSS'.");
                RuleFor(x => x.Ethnicity).Must(x =>
                {
                    if (x == null)
                    {
                        return(true);
                    }

                    Ethnicity ethnicity = DataProvider.CurrentSession.Get <Ethnicity>(x.Id);

                    if (ethnicity == null)
                    {
                        return(false);
                    }

                    return(ethnicity.Equals(x));
                })
                .WithMessage("The ethnicity wasn't valid.  It must match exactly a list item in the database.");
                RuleFor(x => x.ReligiousPreference).Must(x =>
                {
                    if (x == null)
                    {
                        return(true);
                    }

                    ReligiousPreference pref = DataProvider.CurrentSession.Get <ReligiousPreference>(x.Id);

                    if (pref == null)
                    {
                        return(false);
                    }

                    return(pref.Equals(x));
                })
                .WithMessage("The religious preference wasn't valid.  It must match exactly a list item in the database.");
                RuleFor(x => x.Designation).Must(x =>
                {
                    if (x == null)
                    {
                        return(true);
                    }

                    Designation designation = DataProvider.CurrentSession.Get <Designation>(x.Id);

                    if (designation == null)
                    {
                        return(false);
                    }

                    return(designation.Equals(x));
                })
                .WithMessage("The designation wasn't valid.  It must match exactly a list item in the database.");
                RuleFor(x => x.Division).Must((person, x) =>
                {
                    if (x == null)
                    {
                        return(true);
                    }

                    Division division = DataProvider.CurrentSession.Get <Division>(x.Id);

                    if (division == null)
                    {
                        return(false);
                    }

                    return(division.Equals(x));
                })
                .WithMessage("The division wasn't a valid division.  It must match exactly.");
                RuleFor(x => x.Department).Must(x =>
                {
                    if (x == null)
                    {
                        return(true);
                    }

                    Department department = DataProvider.CurrentSession.Get <Department>(x.Id);

                    if (department == null)
                    {
                        return(false);
                    }

                    return(department.Equals(x));
                })
                .WithMessage("The department was invalid.");
                RuleFor(x => x.Command).Must(x =>
                {
                    if (x == null)
                    {
                        return(true);
                    }

                    Command command = DataProvider.CurrentSession.Get <Command>(x.Id);

                    if (command == null)
                    {
                        return(false);
                    }

                    return(command.Equals(x));
                })
                .WithMessage("The command was invalid.");
                RuleFor(x => x.PrimaryNEC).Must((person, x) =>
                {
                    if (x == null)
                    {
                        return(true);
                    }

                    NEC nec = DataProvider.CurrentSession.Get <NEC>(x.Id);

                    if (nec == null)
                    {
                        return(false);
                    }

                    if (!nec.Equals(x))
                    {
                        return(false);
                    }

                    //Now let's also make sure this isn't in the secondary NECs.
                    if (person.SecondaryNECs.Any(y => y.Id == x.Id))
                    {
                        return(false);
                    }

                    return(true);
                })
                .WithMessage("The primary NEC must not exist in the secondary NECs list.");
                RuleFor(x => x.Supervisor).Length(0, 40)
                .WithMessage("The supervisor field may not be longer than 40 characters.");
                RuleFor(x => x.WorkCenter).Length(0, 40)
                .WithMessage("The work center field may not be longer than 40 characters.");
                RuleFor(x => x.WorkRoom).Length(0, 40)
                .WithMessage("The work room field may not be longer than 40 characters.");
                RuleFor(x => x.Shift).Length(0, 40)
                .WithMessage("The shift field may not be longer than 40 characters.");
                RuleFor(x => x.WorkRemarks).Length(0, 150)
                .WithMessage("The work remarks field may not be longer than 150 characters.");
                RuleFor(x => x.UIC).Must(x =>
                {
                    if (x == null)
                    {
                        return(true);
                    }

                    UIC uic = DataProvider.CurrentSession.Get <UIC>(x.Id);

                    if (uic == null)
                    {
                        return(false);
                    }

                    return(uic.Equals(x));
                })
                .WithMessage("The UIC was invalid.");
                RuleFor(x => x.JobTitle).Length(0, 40)
                .WithMessage("The job title may not be longer than 40 characters.");
                RuleFor(x => x.UserPreferences).Must((person, x) =>
                {
                    return(x.Keys.Count <= 20);
                })
                .WithMessage("You may not submit more than 20 preference keys.");
                RuleForEach(x => x.UserPreferences).Must((person, x) =>
                {
                    return(x.Value.Length <= 1000);
                })
                .WithMessage("No preference value may be more than 1000 characters.");

                When(x => x.IsClaimed, () =>
                {
                    RuleFor(x => x.EmailAddresses).Must((person, x) =>
                    {
                        return(x.Any(y => y.IsDodEmailAddress));
                    }).WithMessage("You must have at least one mail.mil address.");
                });

                RuleForEach(x => x.SubscribedEvents).Must((person, subEvent) =>
                {
                    if (person.SubscribedEvents.Count(x => x.Key == subEvent.Key) != 1)
                    {
                        return(false);
                    }

                    var changeEvent = ChangeEvents.ChangeEventHelper.AllChangeEvents.FirstOrDefault(x => x.Id == subEvent.Key);

                    if (changeEvent == null)
                    {
                        return(false);
                    }

                    if (!changeEvent.ValidLevels.Contains(subEvent.Value))
                    {
                        return(false);
                    }

                    return(true);
                })
                .WithMessage("One or more of your subscription events were not valid.");

                //Set validations
                RuleFor(x => x.EmailAddresses)
                .SetCollectionValidator(new EmailAddress.EmailAddressValidator());
                RuleFor(x => x.PhoneNumbers)
                .SetCollectionValidator(new PhoneNumber.PhoneNumberValidator());
                RuleFor(x => x.PhysicalAddresses)
                .SetCollectionValidator(new PhysicalAddress.PhysicalAddressValidator());
            }
Пример #41
0
        protected SalesEmployee CreateSalesEmployee(Division division)
        {
            SalesEmployee salesEmployee = new SalesEmployee();
            salesEmployee.ID = Guid.NewGuid();
            salesEmployee.Name = "Sales Employee";
            salesEmployee.EmployeeNumber = "65454";
            salesEmployee.Division = division;
 
            return salesEmployee;
        }
Пример #42
0
        public static string Process(string input1, string input2, string input3)
        {
            string output = string.Empty;

            switch (input3)
            {
            case "add":
                output = Addition.Add(input1, input2).ToString();
                break;

            case "subtraction":
                output = Subtraction.Sub(input1, input2).ToString();
                break;

            case "multiplication":
                output = Multiplication.Mul(input1, input2).ToString();
                break;

            case "division":
                output = Division.Div(input1, input2).ToString();
                break;

            case "divby3notby6":
                output = Divisionbythreenotbysix.Run(input1).ToString();
                break;

            case "armstrongornot":
                output = Armstrongnumber.Check(input1).ToString();
                break;

            case "factorial":
                output = Factorial.Calculate(input1).ToString();
                break;

            case "palindrome":
                output = PalindromeNumber.Find(input1).ToString();
                break;

            case "reverse":
                output = ReverseNumber.Reverse(input1).ToString();
                break;

            case "sumofdigits":
                output = Sumofdigits.Find(input1).ToString();
                break;

            case "decimaltobinary":
                output = DecimaltoBinary.Converts(input1).ToString();
                break;

            case "numberincharacter":
                output = NumbersInCharacters.Print(input1).ToString();
                break;

            case "strreverse":
                output = StringReverse.Reverse(input1).ToString();
                break;

            case "duplicate":
                output = DuplicateElement.Find(input1).ToString();
                break;

            case "unique":
                output = UniqueElement.Return(input1).ToString();
                break;

            case "strpalindrome":
                output = StringPalindrome.Find(input1).ToString();
                break;

            case "length":
                output = StringLength.Calculate(input1).ToString();
                break;

            case "vowels":
                output = NumofVowels.Print(input1).ToString();
                break;

            case "search":
                output = CharacterSearching.Search(input1, input2).ToString();
                break;

            case "count":
                output = WordCount.Count(input1).ToString();
                break;

            case "date":
                output = DateandTime.Calculate(input1).ToString();
                break;
            }
            return(output);
        }
Пример #43
0
 public override DivisionModifier ModifyDivision(Division divisionToModify)
 {
     return(base.ModifyDivision(divisionToModify));
 }
Пример #44
0
        private Expression GenerateMethodBody(Operation operation, ParameterExpression contextParameter,
                                              IFunctionRegistry functionRegistry)
        {
            if (operation == null)
            {
                throw new ArgumentNullException("operation");
            }

            if (operation.GetType() == typeof(IntegerConstant))
            {
                IntegerConstant constant = (IntegerConstant)operation;

                return(Expression.Convert(Expression.Constant(constant.Value, typeof(int)), typeof(double)));
            }
            else if (operation.GetType() == typeof(FloatingPointConstant))
            {
                FloatingPointConstant constant = (FloatingPointConstant)operation;

                return(Expression.Constant(constant.Value, typeof(double)));
            }
            else if (operation.GetType() == typeof(Variable))
            {
                Type contextType    = typeof(FormulaContext);
                Type dictionaryType = typeof(IDictionary <string, double>);

                Variable variable = (Variable)operation;

                Expression          getVariables = Expression.Property(contextParameter, "Variables");
                ParameterExpression value        = Expression.Variable(typeof(double), "value");

                Expression variableFound = Expression.Call(getVariables,
                                                           dictionaryType.GetRuntimeMethod("TryGetValue", new Type[] { typeof(string), typeof(double).MakeByRefType() }),
                                                           Expression.Constant(variable.Name),
                                                           value);

                Expression throwException = Expression.Throw(
                    Expression.New(typeof(VariableNotDefinedException).GetConstructor(new Type[] { typeof(string) }),
                                   Expression.Constant(string.Format("The variable \"{0}\" used is not defined.", variable.Name))));

                LabelTarget returnLabel = Expression.Label(typeof(double));

                return(Expression.Block(
                           new[] { value },
                           Expression.IfThenElse(
                               variableFound,
                               Expression.Return(returnLabel, value),
                               throwException
                               ),
                           Expression.Label(returnLabel, Expression.Constant(0.0))
                           ));
            }
            else if (operation.GetType() == typeof(Multiplication))
            {
                Multiplication multiplication = (Multiplication)operation;
                Expression     argument1      = GenerateMethodBody(multiplication.Argument1, contextParameter, functionRegistry);
                Expression     argument2      = GenerateMethodBody(multiplication.Argument2, contextParameter, functionRegistry);

                return(Expression.Multiply(argument1, argument2));
            }
            else if (operation.GetType() == typeof(Addition))
            {
                Addition   addition  = (Addition)operation;
                Expression argument1 = GenerateMethodBody(addition.Argument1, contextParameter, functionRegistry);
                Expression argument2 = GenerateMethodBody(addition.Argument2, contextParameter, functionRegistry);

                return(Expression.Add(argument1, argument2));
            }
            else if (operation.GetType() == typeof(Subtraction))
            {
                Subtraction addition  = (Subtraction)operation;
                Expression  argument1 = GenerateMethodBody(addition.Argument1, contextParameter, functionRegistry);
                Expression  argument2 = GenerateMethodBody(addition.Argument2, contextParameter, functionRegistry);

                return(Expression.Subtract(argument1, argument2));
            }
            else if (operation.GetType() == typeof(Division))
            {
                Division   division = (Division)operation;
                Expression dividend = GenerateMethodBody(division.Dividend, contextParameter, functionRegistry);
                Expression divisor  = GenerateMethodBody(division.Divisor, contextParameter, functionRegistry);

                return(Expression.Divide(dividend, divisor));
            }
            else if (operation.GetType() == typeof(Modulo))
            {
                Modulo     modulo   = (Modulo)operation;
                Expression dividend = GenerateMethodBody(modulo.Dividend, contextParameter, functionRegistry);
                Expression divisor  = GenerateMethodBody(modulo.Divisor, contextParameter, functionRegistry);

                return(Expression.Modulo(dividend, divisor));
            }
            else if (operation.GetType() == typeof(Exponentiation))
            {
                Exponentiation exponentation = (Exponentiation)operation;
                Expression     @base         = GenerateMethodBody(exponentation.Base, contextParameter, functionRegistry);
                Expression     exponent      = GenerateMethodBody(exponentation.Exponent, contextParameter, functionRegistry);

                return(Expression.Call(null, typeof(Math).GetRuntimeMethod("Pow", new Type[] { typeof(double), typeof(double) }), @base, exponent));
            }
            else if (operation.GetType() == typeof(UnaryMinus))
            {
                UnaryMinus unaryMinus = (UnaryMinus)operation;
                Expression argument   = GenerateMethodBody(unaryMinus.Argument, contextParameter, functionRegistry);
                return(Expression.Negate(argument));
            }
            else if (operation.GetType() == typeof(LessThan))
            {
                LessThan   lessThan  = (LessThan)operation;
                Expression argument1 = GenerateMethodBody(lessThan.Argument1, contextParameter, functionRegistry);
                Expression argument2 = GenerateMethodBody(lessThan.Argument2, contextParameter, functionRegistry);

                return(Expression.Condition(Expression.LessThan(argument1, argument2),
                                            Expression.Constant(1.0),
                                            Expression.Constant(0.0)));
            }
            else if (operation.GetType() == typeof(LessOrEqualThan))
            {
                LessOrEqualThan lessOrEqualThan = (LessOrEqualThan)operation;
                Expression      argument1       = GenerateMethodBody(lessOrEqualThan.Argument1, contextParameter, functionRegistry);
                Expression      argument2       = GenerateMethodBody(lessOrEqualThan.Argument2, contextParameter, functionRegistry);

                return(Expression.Condition(Expression.LessThanOrEqual(argument1, argument2),
                                            Expression.Constant(1.0),
                                            Expression.Constant(0.0)));
            }
            else if (operation.GetType() == typeof(GreaterThan))
            {
                GreaterThan greaterThan = (GreaterThan)operation;
                Expression  argument1   = GenerateMethodBody(greaterThan.Argument1, contextParameter, functionRegistry);
                Expression  argument2   = GenerateMethodBody(greaterThan.Argument2, contextParameter, functionRegistry);

                return(Expression.Condition(Expression.GreaterThan(argument1, argument2),
                                            Expression.Constant(1.0),
                                            Expression.Constant(0.0)));
            }
            else if (operation.GetType() == typeof(GreaterOrEqualThan))
            {
                GreaterOrEqualThan greaterOrEqualThan = (GreaterOrEqualThan)operation;
                Expression         argument1          = GenerateMethodBody(greaterOrEqualThan.Argument1, contextParameter, functionRegistry);
                Expression         argument2          = GenerateMethodBody(greaterOrEqualThan.Argument2, contextParameter, functionRegistry);

                return(Expression.Condition(Expression.GreaterThanOrEqual(argument1, argument2),
                                            Expression.Constant(1.0),
                                            Expression.Constant(0.0)));
            }
            else if (operation.GetType() == typeof(Equal))
            {
                Equal      equal     = (Equal)operation;
                Expression argument1 = GenerateMethodBody(equal.Argument1, contextParameter, functionRegistry);
                Expression argument2 = GenerateMethodBody(equal.Argument2, contextParameter, functionRegistry);

                return(Expression.Condition(Expression.Equal(argument1, argument2),
                                            Expression.Constant(1.0),
                                            Expression.Constant(0.0)));
            }
            else if (operation.GetType() == typeof(NotEqual))
            {
                NotEqual   notEqual  = (NotEqual)operation;
                Expression argument1 = GenerateMethodBody(notEqual.Argument1, contextParameter, functionRegistry);
                Expression argument2 = GenerateMethodBody(notEqual.Argument2, contextParameter, functionRegistry);

                return(Expression.Condition(Expression.NotEqual(argument1, argument2),
                                            Expression.Constant(1.0),
                                            Expression.Constant(0.0)));
            }
            else if (operation.GetType() == typeof(Function))
            {
                Function function = (Function)operation;

                FunctionInfo functionInfo = functionRegistry.GetFunctionInfo(function.FunctionName);
                Type         funcType;
                Type[]       parameterTypes;
                Expression[] arguments;

                if (functionInfo.IsDynamicFunc)
                {
                    funcType       = typeof(DynamicFunc <double, double>);
                    parameterTypes = new Type[] { typeof(double[]) };


                    Expression[] arrayArguments = new Expression[function.Arguments.Count];
                    for (int i = 0; i < function.Arguments.Count; i++)
                    {
                        arrayArguments[i] = GenerateMethodBody(function.Arguments[i], contextParameter, functionRegistry);
                    }

                    arguments    = new Expression[1];
                    arguments[0] = NewArrayExpression.NewArrayInit(typeof(double), arrayArguments);
                }
                else
                {
                    funcType       = GetFuncType(functionInfo.NumberOfParameters);
                    parameterTypes = (from i in Enumerable.Range(0, functionInfo.NumberOfParameters)
                                      select typeof(double)).ToArray();

                    arguments = new Expression[functionInfo.NumberOfParameters];
                    for (int i = 0; i < functionInfo.NumberOfParameters; i++)
                    {
                        arguments[i] = GenerateMethodBody(function.Arguments[i], contextParameter, functionRegistry);
                    }
                }

                Expression getFunctionRegistry = Expression.Property(contextParameter, "FunctionRegistry");

                ParameterExpression functionInfoVariable = Expression.Variable(typeof(FunctionInfo));

                return(Expression.Block(
                           new[] { functionInfoVariable },
                           Expression.Assign(
                               functionInfoVariable,
                               Expression.Call(getFunctionRegistry, typeof(IFunctionRegistry).GetRuntimeMethod("GetFunctionInfo", new Type[] { typeof(string) }), Expression.Constant(function.FunctionName))
                               ),
                           Expression.Call(
                               Expression.Convert(Expression.Property(functionInfoVariable, "Function"), funcType),
                               funcType.GetRuntimeMethod("Invoke", parameterTypes),
                               arguments)));
            }
            else
            {
                throw new ArgumentException(string.Format("Unsupported operation \"{0}\".", operation.GetType().FullName), "operation");
            }
        }
Пример #45
0
 partial void InsertDivision(Division instance);
        private void Initialize(IEnumerable <string> variableNames, int nConstants)
        {
            #region symbol declaration
            var add    = new Addition();
            var sub    = new Subtraction();
            var mul    = new Multiplication();
            var div    = new Division();
            var mean   = new Average();
            var log    = new Logarithm();
            var pow    = new Power();
            var square = new Square();
            var root   = new Root();
            var sqrt   = new SquareRoot();
            var exp    = new Exponential();

            // we use our own random number generator here because we assume
            // that grammars are only initialized once when setting the grammar in the problem.
            // This means everytime the grammar parameter in the problem is changed
            // we initialize the constants to new values
            var rand = new MersenneTwister();
            // warm up
            for (int i = 0; i < 1000; i++)
            {
                rand.NextDouble();
            }

            var constants = new List <Constant>(nConstants);
            for (int i = 0; i < nConstants; i++)
            {
                var constant = new Constant();
                do
                {
                    var constVal = rand.NextDouble() * 20.0 - 10.0;
                    constant.Name             = string.Format("{0:0.000}", constVal);
                    constant.MinValue         = constVal;
                    constant.MaxValue         = constVal;
                    constant.ManipulatorSigma = 0.0;
                    constant.ManipulatorMu    = 0.0;
                    constant.MultiplicativeManipulatorSigma = 0.0;
                } while (constants.Any(c => c.Name == constant.Name)); // unlikely, but it could happen that the same constant value is sampled twice. so we resample if necessary.
                constants.Add(constant);
            }

            var variables = new List <HeuristicLab.Problems.DataAnalysis.Symbolic.Variable>();
            foreach (var variableName in variableNames)
            {
                var variableSymbol = new HeuristicLab.Problems.DataAnalysis.Symbolic.Variable();
                variableSymbol.Name = variableName;
                variableSymbol.WeightManipulatorMu    = 0.0;
                variableSymbol.WeightManipulatorSigma = 0.0;
                variableSymbol.WeightMu    = 1.0;
                variableSymbol.WeightSigma = 0.0;
                variableSymbol.MultiplicativeWeightManipulatorSigma = 0.0;
                variableSymbol.AllVariableNames = new[] { variableName };
                variableSymbol.VariableNames    = new[] { variableName };
                variables.Add(variableSymbol);
            }

            #endregion

            AddSymbol(add);
            AddSymbol(sub);
            AddSymbol(mul);
            AddSymbol(div);
            AddSymbol(mean);
            AddSymbol(log);
            AddSymbol(pow);
            AddSymbol(square);
            AddSymbol(root);
            AddSymbol(sqrt);
            AddSymbol(exp);
            constants.ForEach(AddSymbol);
            variables.ForEach(AddSymbol);

            #region subtree count configuration
            SetSubtreeCount(add, 2, 2);
            SetSubtreeCount(sub, 2, 2);
            SetSubtreeCount(mul, 2, 2);
            SetSubtreeCount(div, 2, 2);
            SetSubtreeCount(mean, 2, 2);
            SetSubtreeCount(log, 1, 1);
            SetSubtreeCount(pow, 2, 2);
            SetSubtreeCount(square, 1, 1);
            SetSubtreeCount(root, 2, 2);
            SetSubtreeCount(sqrt, 1, 1);
            SetSubtreeCount(exp, 1, 1);
            constants.ForEach((c) => SetSubtreeCount(c, 0, 0));
            variables.ForEach((v) => SetSubtreeCount(v, 0, 0));
            #endregion

            var functions       = new ISymbol[] { add, sub, mul, div, mean, log, pow, root, square, sqrt };
            var terminalSymbols = variables.Concat <ISymbol>(constants);
            var allSymbols      = functions.Concat(terminalSymbols);

            #region allowed child symbols configuration
            foreach (var s in allSymbols)
            {
                AddAllowedChildSymbol(StartSymbol, s);
            }
            foreach (var parentSymb in functions)
            {
                foreach (var childSymb in allSymbols)
                {
                    AddAllowedChildSymbol(parentSymb, childSymb);
                }
            }

            #endregion
        }
Пример #47
0
 partial void DeleteDivision(Division instance);
 public void SetDivision(int i, Division division)
 {
     Divisions[i] = division;
 }
Пример #49
0
        // POST: Tournament/Create
        // Create tournament, either with or without excel upload.
        //
        public ActionResult Create(string name, string password, string startTimes, string endTimes)
        {
            try
            {
                if (!db.TournamentSet.Any(x => x.Password == password))
                {
                    Tournament t = new Tournament();
                    List<TimeInterval> tis = new List<TimeInterval>();

                    HttpPostedFileBase file = null;
                    int poolStart = 1;

                    List<DateTime> startTimesList = startTimes.Split(',').Select(DateTime.Parse).ToList();
                    List<DateTime> endTimesList = endTimes.Split(',').Select(DateTime.Parse).ToList();
                    for (int i = 0; i < startTimesList.Count; i++)
                    {
                        tis.Add(new TimeInterval() { StartTime = startTimesList[i], EndTime = endTimesList[i] });
                        db.TimeIntervalSet.Add(new TimeInterval() { StartTime = startTimesList[i], EndTime = endTimesList[i] });
                    }

                    // Check for attatched file
                    if (Request != null && Request.Files.Count > 0 && Request.Files[0] != null && Request.Files[0].ContentLength > 0)
                    {
                        file = Request.Files[0];
                        IExcelDataReader excelReader;
                        switch (Path.GetExtension(file.FileName))
                        {
                            case ".xlsx":
                                excelReader = ExcelReaderFactory.CreateOpenXmlReader(file.InputStream);
                                break;
                            case ".xls":
                                excelReader = ExcelReaderFactory.CreateBinaryReader(file.InputStream);
                                break;
                            default:
                                excelReader = ExcelReaderFactory.CreateBinaryReader(file.InputStream);
                                break;
                        }

                        DataSet result = excelReader.AsDataSet();

                        List<string> divisions = new List<string>();
                        List<string> pools = new List<string>();
                        List<string> teams = new List<string>();

                        Division d = new Division();
                        Pool p = new Pool();

                        int missingFLs = 0;
                        int flIndex = 0;

                        t.Name = result.Tables[0].Rows[0][0].ToString();
                        object[] stopRow = new object[1];
                        stopRow[0] = "Stop";
                        result.Tables[0].Rows.Add(stopRow);
                        // Loop over number rows in the table
                        for (int i = 1; i < result.Tables[0].Rows.Count; i++)
                        {
                            if (!string.IsNullOrEmpty(result.Tables[0].Rows[i][0].ToString()) || string.IsNullOrEmpty(result.Tables[0].Rows[i][1].ToString()))
                            {
                                if (t.Divisions.Count > 0)
                                {
                                    // A loop running from where one pool starts till another ends
                                    for (int j = poolStart; j < i; j++)
                                    {

                                        p = new Pool() { Division = d, Name = result.Tables[0].Rows[j][1].ToString(), IsAuto = false };

                                        // Create new teams and link them to the pool
                                        for (int teamIndex = 2; teamIndex < 25; teamIndex++)
                                        {
                                            try
                                            {
                                                string teamName = result.Tables[0].Rows[j][teamIndex].ToString();
                                                if (!string.IsNullOrEmpty(result.Tables[0].Rows[j][teamIndex].ToString()))
                                                {

                                                    Team newTeam = new Team() { Name = teamName, Pool = p, IsAuto = false, };
                                                    // Make sure teams gets standard time intervals
                                                    foreach (TimeInterval ti in tis)
                                                    {
                                                        newTeam.TimeIntervals.Add(db.TimeIntervalSet.Add(new TimeInterval { StartTime = ti.StartTime, EndTime = ti.EndTime }));
                                                    }
                                                    p.Teams.Add(newTeam);
                                                    newTeam = db.TeamSet.Add(newTeam);
                                                }
                                                else
                                                    break;
                                            } catch(Exception e)
                                            {
                                                break;
                                            }

                                        }
                                        p = db.PoolSet.Add(p);
                                        if (p.Teams.Count > missingFLs)
                                            missingFLs = p.Teams.Count;
                                    }
                                    // Create finalslinks for division. MissingFls is the max number of teams in a pool in a division
                                    for (flIndex = 0; flIndex < missingFLs; flIndex++)
                                    {
                                        d.FinalsLinks.Add(new FinalsLink() { Division = d, PoolPlacement = flIndex + 1, Finalstage = flIndex + 1 });
                                    }
                                }

                                if (string.IsNullOrEmpty(result.Tables[0].Rows[i][1].ToString()))
                                    break;

                                // Create the division and assign data
                                d = new Division() { Tournament = t, Name = result.Tables[0].Rows[i][0].ToString(), FieldSize = FieldSize.ElevenMan, MatchDuration = 60 };
                                d = db.DivisionSet.Add(d);
                                missingFLs = 0;
                                poolStart = i;
                            }

                        }
                        excelReader.Close();
                    }

                    // Standard code for creating the tournament. Creates the tournament even when there are no excel data
                    t.Name = name;
                    t.Password = password;
                    t.TimeIntervals = tis;
                    t = db.TournamentSet.Add(t);
                    db.SaveChanges();

                    return Json(new { status = "success", message = "New tournament added", id = t.Id }, JsonRequestBehavior.AllowGet);

                }
                return Json(new { status = "error", message = "Password already exists" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { status = "error", message = "New tournament not added", details = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
Пример #50
0
 public async Task AddDivisionAsync(Division division)
 {
     await _context.Divisions.AddAsync(division);
 }
Пример #51
0
        public override void Given()
        {
            viewModel = new CreateDivisionViewModel();
              viewModel.Name = "MyDivision";
              viewModel.StartingDate = DateTime.Parse("11/30/2010").ToShortDateString();
              viewModel.SeasonId = 1;

              var season = new Season("temp", GameType.EightBall);
              season.SetIdTo(viewModel.SeasonId);

              repository.Setup(r => r.Get<Season>(season.Id)).Returns(season);
              repository.Setup(r => r.All<Division>()).Returns(new List<Division>().AsQueryable());
              repository.Setup(r => r.SaveOrUpdate<Division>(It.IsAny<Division>())).Callback<Division>(d => savedDivision = d).Returns(savedDivision);
        }
Пример #52
0
 public IActionResult Edit(Division division)
 {
     db.Entry(division).State = EntityState.Modified;
     db.SaveChanges();
     return(RedirectToAction("Index"));
 }
Пример #53
0
 public override bool Visit(Division node)
 {
     Visit((ArithmeticBinaryExpression)node);
     return(true);
 }
Пример #54
0
 public IActionResult Create(Division division)
 {
     db.Divisions.Add(division);
     db.SaveChanges();
     return(RedirectToAction("Index"));
 }
Пример #55
0
 public Employee( string name, Division division )
 {
     Name = name;
     Division = division;
 }
Пример #56
0
 public void QuotientintQuotientZeroTest()
 {
     Assert.ThrowsException <DivideByZeroException>(() => Division.Quotient(a, e));
 }
Пример #57
0
        private void LoadRow(Division division)
        {
            try
            {
                lblDivisionID.Value = division.DivisionID.ToString();
                txtName.Text = division.Div_Desc.ToString();
                if (division.MinDate.Value != null)
                {
                    txtMinDate.Text = division.MinDate.Value.ToString("yyyy-MM-dd");
                    hdnMinDateOld.Value = division.MinDate.Value.ToString("yyyy-MM-dd");
                }
                else
                {
                    txtMinDate.Text = String.Empty;
                    hdnMinDateOld.Value = String.Empty;
                }
                if (division.MaxDate.Value != null)
                {
                    txtMaxDate.Text = division.MaxDate.Value.ToString("yyyy-MM-dd");
                    hdnMaxDateOld.Value = division.MaxDate.Value.ToString("yyyy-MM-dd");
                }
                else
                {
                    txtMaxDate.Text = String.Empty;
                    hdnMaxDateOld.Value = String.Empty;

                }
                if (division.MinDate2 != null)
                {
                    txtMinDate2.Text = division.MinDate2.Value.ToString("yyyy-MM-dd");
                    hdnMinDate2Old.Value = division.MinDate2.Value.ToString("yyyy-MM-dd");
                }
                else {
                    txtMinDate2.Text = String.Empty;
                    hdnMinDate2Old.Value = String.Empty;
                }
                if (division.MaxDate2 != null)
                {
                    txtMaxDate2.Text = division.MaxDate2.Value.ToString("yyyy-MM-dd");
                    hdnMaxDate2Old.Value = division.MaxDate2.Value.ToString("yyyy-MM-dd");
                }
                else
                {
                    txtMaxDate2.Text = String.Empty;
                    hdnMaxDate2Old.Value = String.Empty;

                }
                lblHPhon.Text = "";
                lblCPhon.Text = "";
                if (division.Director != null)
                {
                    if (division.Director.Cellphone != null)
                    {
                        lblCPhon.Text += "  C-" + division.Director.Cellphone.ToString();
                    }
                    if (division.Director.Household != null)
                    {
                        if (division.Director.Household.Phone != null)
                        {
                            lblHPhon.Text = "H-" + division.Director.Household.Phone.ToString();
                        }
                    }
                }

                cboAD.SelectedValue = "0";
                if (division.DirectorID != 0)
                {
                    //if (Information.IsNumeric(row["DirectorID"]) & rsData.Rows(0).Item("AD"] == true) {
                    cboAD.SelectedValue = division.DirectorID.ToString();
                    //}
                }
                hdnGenderOld.Value = division.Gender.ToString().Trim();
                if (division.Gender.ToString().Trim() == "M")
                {

                    radGender.SelectedIndex = 0;
                }
                else
                {
                    radGender.SelectedIndex = 1;
                    //radGender.Items(1).Selected() = true;
                    //radGender.Items(0).Selected() = false;
                }
                if (!String.IsNullOrEmpty(division.Gender2))
                {
                    hdnGender2Old.Value = division.Gender2.ToString().Trim();
                    if (division.Gender2.ToString().Trim() == "M")
                    {
                        radGender2.SelectedIndex = 0;

                    }
                    else
                    {
                        radGender2.SelectedIndex = 1;
                    }
                }
                if (!String.IsNullOrEmpty(division.DraftVenue))
                    txtVenue.Text = division.DraftVenue.ToString();
                else
                    txtVenue.Text = String.Empty;
                if (division.DraftDate.HasValue)
                    txtDate.Text = division.DraftDate.Value.ToShortDateString();
                else txtDate.Text = String.Empty;
                if (!String.IsNullOrEmpty(division.DraftTime))
                    txtTime.Text = division.DraftTime.ToString();
                else txtTime.Text = String.Empty;
            }
            catch (Exception ex)
            {
                lblError.Text = "LoadRow::" + ex.Message;
            }

            //LoadTeams(division.DivisionID);
        }
Пример #58
0
 public void QuotientDoulbleTest()
 {
     Assert.AreEqual(1.9901960784313728, Division.Quotient(c, d));
 }
Пример #59
0
 internal void Edit(Division division)
 {
     DivisionSQL.Update(division.Id, division.Name);
     Divisions.First(d => d.Id == division.Id).Name = division.Name;
 }
Пример #60
0
        static void Main(string[] args)
        {
            //PhasorMeasurement busAVoltage = new PhasorMeasurement()
            //    {
            //        Type = PhasorType.VoltagePhasor,
            //        BaseKV = new VoltageLevel(1, 230),
            //        Magnitude = 133518.0156,
            //        AngleInDegrees = -2.4644
            //    };
            //PhasorMeasurement busBVoltage = new PhasorMeasurement()
            //{
            //    Type = PhasorType.VoltagePhasor,
            //    BaseKV = new VoltageLevel(1, 230),
            //    Magnitude = 133758.7656,
            //    AngleInDegrees = 2.4317
            //};
            //PhasorMeasurement busCVoltage = new PhasorMeasurement()
            //{
            //    Type = PhasorType.VoltagePhasor,
            //    BaseKV = new VoltageLevel(1, 230),
            //    Magnitude = 133666.7188,
            //    AngleInDegrees = -2.1697
            //};
            //PhasorMeasurement busDVoltage = new PhasorMeasurement()
            //{
            //    Type = PhasorType.VoltagePhasor,
            //    BaseKV = new VoltageLevel(1, 230),
            //    Magnitude = 134102.8125,
            //    AngleInDegrees = 0.0096257
            //};
            //PhasorMeasurement busEVoltage = new PhasorMeasurement()
            //{
            //    Type = PhasorType.VoltagePhasor,
            //    BaseKV = new VoltageLevel(1, 230),
            //    Magnitude = 133088.9688,
            //    AngleInDegrees = -7.2477
            //};
            //PhasorMeasurement busFVoltage = new PhasorMeasurement()
            //{
            //    Type = PhasorType.VoltagePhasor,
            //    BaseKV = new VoltageLevel(1, 230),
            //    Magnitude = 133141.7344,
            //    AngleInDegrees = -6.3372
            //};
            //PhasorMeasurement busGVoltage = new PhasorMeasurement()
            //{
            //    Type = PhasorType.VoltagePhasor,
            //    BaseKV = new VoltageLevel(1, 230),
            //    Magnitude = 133346.1094,
            //    AngleInDegrees = -5.8259
            //};
            //PhasorMeasurement busHVoltage = new PhasorMeasurement()
            //{
            //    Type = PhasorType.VoltagePhasor,
            //    BaseKV = new VoltageLevel(1, 230),
            //    Magnitude = 133492.2969,
            //    AngleInDegrees = -4.6002
            //};
            /////
            /////
            ///// Current
            //PhasorMeasurement busBtoBusAFlow = new PhasorMeasurement()
            //    {
            //        Type = PhasorType.CurrentPhasor,
            //        BaseKV = new VoltageLevel(1, 230)
            //    };
            //PhasorMeasurement busBtoBusCFlow = new PhasorMeasurement()
            //{
            //    Type = PhasorType.CurrentPhasor,
            //    BaseKV = new VoltageLevel(1, 230)
            //};
            //PhasorMeasurement busDtoBusCFlow = new PhasorMeasurement()
            //{
            //    Type = PhasorType.CurrentPhasor,
            //    BaseKV = new VoltageLevel(1, 230)
            //};
            //PhasorMeasurement busDtoBusFFlow = new PhasorMeasurement()
            //{
            //    Type = PhasorType.CurrentPhasor,
            //    BaseKV = new VoltageLevel(1, 230)
            //};
            //PhasorMeasurement busAtoBusEFlow = new PhasorMeasurement()
            //{
            //    Type = PhasorType.CurrentPhasor,
            //    BaseKV = new VoltageLevel(1, 230)
            //};
            //PhasorMeasurement busFtoBusEFlow = new PhasorMeasurement()
            //{
            //    Type = PhasorType.CurrentPhasor,
            //    BaseKV = new VoltageLevel(1, 230)
            //};
            //PhasorMeasurement busAtoBusGFlow = new PhasorMeasurement()
            //{
            //    Type = PhasorType.CurrentPhasor,
            //    BaseKV = new VoltageLevel(1, 230)
            //};
            //PhasorMeasurement busHtoBusGFlow = new PhasorMeasurement()
            //{
            //    Type = PhasorType.CurrentPhasor,
            //    BaseKV = new VoltageLevel(1, 230)
            //};
            //PhasorMeasurement busDtoBusHFlow = new PhasorMeasurement()
            //{
            //    Type = PhasorType.CurrentPhasor,
            //    BaseKV = new VoltageLevel(1, 230)
            //};

            //busBtoBusAFlow.PerUnitComplexPhasor = (busBVoltage.PerUnitComplexPhasor - busAVoltage.PerUnitComplexPhasor) / (new Complex(0.0, 0.01));
            //busBtoBusCFlow.PerUnitComplexPhasor = (busBVoltage.PerUnitComplexPhasor - busCVoltage.PerUnitComplexPhasor) / (new Complex(0.0, 0.06));
            //busDtoBusCFlow.PerUnitComplexPhasor = (busDVoltage.PerUnitComplexPhasor - busCVoltage.PerUnitComplexPhasor) / (new Complex(0.0, 0.06));
            //busDtoBusFFlow.PerUnitComplexPhasor = (busDVoltage.PerUnitComplexPhasor - busFVoltage.PerUnitComplexPhasor) / (new Complex(0.0, 0.01));
            //busAtoBusEFlow.PerUnitComplexPhasor = (busAVoltage.PerUnitComplexPhasor - busEVoltage.PerUnitComplexPhasor) / (new Complex(0.0, 0.005));
            //busFtoBusEFlow.PerUnitComplexPhasor = (busFVoltage.PerUnitComplexPhasor - busEVoltage.PerUnitComplexPhasor) / (new Complex(0.0, 0.005));
            //busAtoBusGFlow.PerUnitComplexPhasor = (busAVoltage.PerUnitComplexPhasor - busGVoltage.PerUnitComplexPhasor) / (new Complex(0.0, 0.005));
            //busHtoBusGFlow.PerUnitComplexPhasor = (busHVoltage.PerUnitComplexPhasor - busGVoltage.PerUnitComplexPhasor) / (new Complex(0.0, 0.01));
            //busDtoBusHFlow.PerUnitComplexPhasor = (busDVoltage.PerUnitComplexPhasor - busHVoltage.PerUnitComplexPhasor) / (new Complex(0.0, 0.01));


            //Console.WriteLine("BusB.BusA: " + busBtoBusAFlow.Magnitude.ToString() + " " + (busBtoBusAFlow.AngleInDegrees).ToString());
            //Console.WriteLine("BusB.BusC: " + busBtoBusCFlow.Magnitude.ToString() + " " + (busBtoBusCFlow.AngleInDegrees).ToString());
            //Console.WriteLine("BusD.BusC: " + busDtoBusCFlow.Magnitude.ToString() + " " + (busDtoBusCFlow.AngleInDegrees).ToString());
            //Console.WriteLine("BusD.BusF: " + busDtoBusFFlow.Magnitude.ToString() + " " + (busDtoBusFFlow.AngleInDegrees).ToString());
            //Console.WriteLine("BusA.BusE: " + busAtoBusEFlow.Magnitude.ToString() + " " + (busAtoBusEFlow.AngleInDegrees).ToString());
            //Console.WriteLine("BusF.BusE: " + busFtoBusEFlow.Magnitude.ToString() + " " + (busFtoBusEFlow.AngleInDegrees).ToString());
            //Console.WriteLine("BusA.BusG: " + busAtoBusGFlow.Magnitude.ToString() + " " + (busAtoBusGFlow.AngleInDegrees).ToString());
            //Console.WriteLine("BusH.BusG: " + busHtoBusGFlow.Magnitude.ToString() + " " + (busHtoBusGFlow.AngleInDegrees).ToString());
            //Console.WriteLine("BusD.BusH: " + busDtoBusHFlow.Magnitude.ToString() + " " + (busDtoBusHFlow.AngleInDegrees).ToString());


            //Network network = Network.DeserializeFromXml(@"\\psf\Home\Documents\mc2\Linear State Estimation\EPG\LinearStateEstimator.OfflineModule\x86\TransmissionLineGraphTestFull4.xml");
            //Network network = Network.DeserializeFromXml(@"\\psf\Home\Documents\mc2\Projects\EPG - WECC SDVCA\Data\July 20, 2014 Test Cases\shunt_test_model.xml");

            //RawMeasurements rawMeasurements = RawMeasurements.DeserializeFromXml(@"\\psf\Home\Documents\mc2\Projects\EPG - WECC SDVCA\Data\July 20, 2014 Test Cases\ShuntSeriesTestCase151.xml");
            //network.Initialize();

            //network.Model.InputKeyValuePairs.Clear();

            //for (int i = 0; i < rawMeasurements.Items.Count(); i++)
            //{
            //    network.Model.InputKeyValuePairs.Add(rawMeasurements.Items[i].Key, Convert.ToDouble(rawMeasurements.Items[i].Value));
            //}

            //network.Model.OnNewMeasurements();

            //Console.WriteLine(network.Model.ComponentList());

            //Dictionary<string, double> receivedMeasurements = network.Model.GetReceivedMeasurements();

            //foreach (KeyValuePair<string, double> keyValuePair in receivedMeasurements)
            //{
            //    Console.WriteLine(keyValuePair.Key + " " + keyValuePair.Value.ToString());
            //}

            //Console.WriteLine(rawMeasurements.Items.Count().ToString());
            //Console.WriteLine(receivedMeasurements.Count.ToString());
            //Console.WriteLine();

            //network.RunNetworkReconstructionCheck();

            //network.Model.DetermineActiveCurrentFlows();
            //network.Model.DetermineActiveCurrentInjections();

            //Console.WriteLine(network.Model.MeasurementInclusionStatusList());

            //network.Model.ResolveToObservedBusses();

            //Console.WriteLine(network.Model.ObservedBusses.Count);

            //foreach (Substation substation in network.Model.Substations)
            //{
            //    Console.WriteLine(substation.Graph.AdjacencyList.ToString());
            //}

            //network.Model.ResolveToSingleFlowBranches();

            //foreach (TransmissionLine transmissionLine in network.Model.TransmissionLines)
            //{
            //    Console.WriteLine();
            //    Console.WriteLine(transmissionLine.Name);
            //    Console.WriteLine("Has at least one flow path: " + transmissionLine.Graph.HasAtLeastOneFlowPath.ToString());
            //    Console.WriteLine(transmissionLine.Graph.DirectlyConnectedAdjacencyList.ToString());
            //    Console.WriteLine(transmissionLine.Graph.SeriesImpedanceConnectedAdjacencyList.ToString());
            //    Console.WriteLine(transmissionLine.Graph.RootNode.ToSubtreeString());
            //    List<SeriesBranchBase> seriesBranches = transmissionLine.Graph.SingleFlowPathBranches;
            //    foreach (SeriesBranchBase seriesBranch in seriesBranches)
            //    {
            //        seriesBranch.ToVerboseString();
            //    }
            //}

            //network.ComputeSystemState();
            //network.Model.ComputeEstimatedCurrentFlows();
            //network.Model.ComputeEstimatedCurrentInjections();

            //TransmissionLine transmissionLine = network.Model.Companies[0].Divisions[0].TransmissionLines[0];

            //foreach (Switch bypassSwitch in transmissionLine.Switches)
            //{
            //    bypassSwitch.IsInDefaultMode = false;
            //    bypassSwitch.ActualState = SwitchingDeviceActualState.Closed;
            //    if (bypassSwitch.InternalID == 1) { bypassSwitch.ActualState = SwitchingDeviceActualState.Closed; }
            //    Console.WriteLine(String.Format("ID:{0} Normally:{1} Actually:{2}", bypassSwitch.InternalID, bypassSwitch.NormalState, bypassSwitch.ActualState));
            //}

            //TransmissionLineGraph graph = new TransmissionLineGraph(transmissionLine);
            //graph.InitializeAdjacencyLists();
            //Console.WriteLine(graph.DireclyConnectedAdjacencyList.ToString());
            //graph.ResolveConnectedAdjacencies();
            //Console.WriteLine(graph.DireclyConnectedAdjacencyList.ToString());
            //Console.WriteLine(graph.SeriesImpedanceConnectedAdjacencyList.ToString());
            //if (graph.HasAtLeastOneFlowPath)
            //{
            //    Console.WriteLine(graph.SeriesImpedanceConnectedAdjacencyList.ToString());
            //    graph.InitializeTree();
            //    Console.WriteLine(graph.RootNode.ToSubtreeString());
            //    Console.WriteLine("Number of series branches: " + graph.SingleFlowPathBranches.Count);
            //    Console.WriteLine(graph.ResolveToSingleSeriesBranch().RawImpedanceParameters.ToString());
            //}
            //else
            //{
            //    Console.WriteLine("Graph does not have at least one flow path -> tree would be invalid!");
            //}
            //SequencedMeasurementSnapshotPathSet sequencedMeasurementSnapshotPathSet = new SequencedMeasurementSnapshotPathSet();
            //sequencedMeasurementSnapshotPathSet.MeasurementSnapshotPaths.Add(new MeasurementSnapshotPath("value"));

            //sequencedMeasurementSnapshotPathSet.SerializeToXml("\\\\psf\\Home\\Documents\\mc2\\Projects\\EPG - WECC SDVCA\\Data\\TestCases.xml");
            CsvFileWithHeader coFile = new CsvFileWithHeader("U:\\Documents\\Projects\\02 Linear State Estimator\\EMS to LSE\\lse_co.out");
            CsvFileWithHeader dvFile = new CsvFileWithHeader("U:\\Documents\\Projects\\02 Linear State Estimator\\EMS to LSE\\lse_dv.out");
            CsvFileWithHeader stFile = new CsvFileWithHeader("U:\\Documents\\Projects\\02 Linear State Estimator\\EMS to LSE\\lse_st.out");
            CsvFileWithHeader ndFile = new CsvFileWithHeader("U:\\Documents\\Projects\\02 Linear State Estimator\\EMS to LSE\\lse_nd.out");

            List <double> nodeBaseKvs  = new List <double>();
            NetworkModel  networkModel = new NetworkModel();


            foreach (Dictionary <string, string> node in ndFile.StructuredData)
            {
                if (!nodeBaseKvs.Contains(Convert.ToDouble(node["id_kv"].TrimEnd('\'').TrimStart('\''))))
                {
                    nodeBaseKvs.Add(Convert.ToDouble(node["id_kv"].TrimEnd('\'').TrimStart('\'')));
                }
            }
            nodeBaseKvs.Sort();
            for (int i = 0; i < nodeBaseKvs.Count; i++)
            {
                networkModel.VoltageLevels.Add(new VoltageLevel(i + 1, nodeBaseKvs[i]));
            }

            foreach (Dictionary <string, string> row in coFile.StructuredData)
            {
                Company company = new Company()
                {
                    InternalID = Convert.ToInt32(row["%SUBSCRIPT"]),
                    Number     = Convert.ToInt32(row["%SUBSCRIPT"]),
                    Name       = row["id_area"],
                    Acronym    = row["id_area"],
                };
                networkModel.Companies.Add(company);

                foreach (Dictionary <string, string> divisionRecord in dvFile.StructuredData)
                {
                    if (company.Number == Convert.ToInt32(divisionRecord["i$area_dv"]))
                    {
                        Division division = new Division()
                        {
                            InternalID = Convert.ToInt32(divisionRecord["%SUBSCRIPT"]),
                            Number     = Convert.ToInt32(divisionRecord["%SUBSCRIPT"]),
                            Name       = divisionRecord["id_dv"],
                            Acronym    = divisionRecord["id_dv"],
                        };
                        company.Divisions.Add(division);

                        foreach (Dictionary <string, string> substationRecord in stFile.StructuredData)
                        {
                            if (division.Name == substationRecord["id_dv"])
                            {
                                Substation substation = new Substation()
                                {
                                    InternalID = Convert.ToInt32(substationRecord["%SUBSCRIPT"]),
                                    Number     = Convert.ToInt32(substationRecord["%SUBSCRIPT"]),
                                    Acronym    = substationRecord["id_st"],
                                    Name       = substationRecord["id_st"]
                                };
                                division.Substations.Add(substation);

                                foreach (Dictionary <string, string> nodeRecord in ndFile.StructuredData)
                                {
                                    if (substation.Name == nodeRecord["id_st"])
                                    {
                                        double       baseKvValue = Convert.ToDouble(nodeRecord["id_kv"].TrimEnd('\'').TrimStart('\''));
                                        VoltageLevel baseKv      = new VoltageLevel(1, 999);
                                        foreach (VoltageLevel voltageLevel in networkModel.VoltageLevels)
                                        {
                                            if (voltageLevel.Value == baseKv.Value)
                                            {
                                                baseKv = voltageLevel;
                                            }
                                        }
                                        Node node = new Node()
                                        {
                                            InternalID  = Convert.ToInt32(nodeRecord["%SUBSCRIPT"]),
                                            Number      = Convert.ToInt32(nodeRecord["%SUBSCRIPT"]),
                                            Acronym     = nodeRecord["id_nd"],
                                            Name        = nodeRecord["id_st"] + "_" + nodeRecord["id_nd"],
                                            Description = nodeRecord["id_st"] + " " + nodeRecord["id_kv"] + "kV Node " + nodeRecord["id_nd"],
                                            BaseKV      = baseKv
                                        };

                                        VoltagePhasorGroup voltage = new VoltagePhasorGroup()
                                        {
                                            InternalID  = node.InternalID,
                                            Number      = node.Number,
                                            Acronym     = "V " + node.InternalID.ToString(),
                                            Name        = "Phasor Name",
                                            Description = "Voltage Phasor Group Description",
                                            IsEnabled   = true,
                                            UseStatusFlagForRemovingMeasurements = true,
                                            MeasuredNode = node
                                        };

                                        voltage.ZeroSequence.Measurement.BaseKV     = node.BaseKV;
                                        voltage.ZeroSequence.Estimate.BaseKV        = node.BaseKV;
                                        voltage.NegativeSequence.Measurement.BaseKV = node.BaseKV;
                                        voltage.NegativeSequence.Estimate.BaseKV    = node.BaseKV;
                                        voltage.PositiveSequence.Measurement.BaseKV = node.BaseKV;
                                        voltage.PositiveSequence.Estimate.BaseKV    = node.BaseKV;
                                        voltage.PhaseA.Measurement.BaseKV           = node.BaseKV;
                                        voltage.PhaseA.Estimate.BaseKV    = node.BaseKV;
                                        voltage.PhaseB.Measurement.BaseKV = node.BaseKV;
                                        voltage.PhaseB.Estimate.BaseKV    = node.BaseKV;
                                        voltage.PhaseC.Measurement.BaseKV = node.BaseKV;
                                        voltage.PhaseC.Estimate.BaseKV    = node.BaseKV;

                                        node.Voltage = voltage;

                                        substation.Nodes.Add(node);
                                    }
                                }
                            }
                        }
                    }
                }
            }



            Network network = new Network(networkModel);

            network.SerializeToXml("U:\\ems.xml");

            Console.ReadLine();
        }