Example #1
0
        //Evolving
        /// <summary>
        /// 
        /// </summary>
        /// <param name="count"></param>
        /// <param name="fullGridIndex"></param>
        /// <returns></returns>
        /// <Rules>
        ///Any live cell with fewer than two live neighbours dies, as if caused by under-population.
        ///Any live cell with two or three live neighbours lives on to the next generation.
        ///Any live cell with more than three live neighbours dies, as if by overcrowding.
        ///Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
        /// </Rules>
        public IEnumerable<GridIndex> Evolve(int count, List<GridIndex> fullGridIndex)
        {
            IEnumerable<IGridIndex> EvolvedGrids = new List<GridIndex>();

            var neighbour = new Neighbour();
            for (int rowIndex = 0; rowIndex < Grid.NumberOfRows; rowIndex++)
            {
                for (int colIndex = 0; colIndex < Grid.NumberOfCols; colIndex++)
                {
                    EvolvedGrids = neighbour.ValidateNeighbours(rowIndex, colIndex, fullGridIndex);
                    if (EvolvedGrids.Count<IGridIndex>() == 3)
                    {
                        try
                        {
                            fullGridIndex.Single(s => s.RowIndex == rowIndex && s.ColIndex == colIndex).isAlive = true;
                        }
                        catch (Exception ex)
                        { }
                        //grid.isAlive = true;
                    }
                    else if (EvolvedGrids.Count<IGridIndex>() == 2)
                    {
                        if (fullGridIndex.Single(s => s.RowIndex == rowIndex && s.ColIndex == colIndex).isAlive==true )
                        {
                            fullGridIndex.Single(s => s.RowIndex == rowIndex && s.ColIndex == colIndex).isAlive = true;
                        }
                    }
                    else if ((EvolvedGrids.Count<IGridIndex>() < 2) || (EvolvedGrids.Count<IGridIndex>() > 3))
                    {
                        fullGridIndex.Single(s => s.RowIndex == rowIndex && s.ColIndex == colIndex).isAlive = false;
                    }
                }
            }
            return fullGridIndex;
        }
        public List<TimeTableViewModelRow> GetTimeTable(List<Port> ports)
        {
            var timetables = _timeTables.All();

            var allEntries = timetables.SelectMany(x => x.Entries).OrderBy(x => x.Time).ToList();
            var rows = new List<TimeTableViewModelRow>();

            foreach (var timetable in allEntries)
            {
                var origin = ports.Single(x => x.Id == timetable.OriginId);
                var destination = ports.Single(x => x.Id == timetable.DestinationId);
                var destinationName = destination.Name;
                var originName = origin.Name;
                var ferry = _ferryService.NextFerryAvailableFrom(origin.Id, timetable.Time);
                var arrivalTime = timetable.Time.Add(timetable.JourneyTime);
                var row = new TimeTableViewModelRow
                {
                    DestinationPort = destinationName,
                    FerryName = ferry == null ? "" : ferry.Name,
                    JourneyLength = timetable.JourneyTime.ToString("hh':'mm"),
                    OriginPort = originName,
                    StartTime = timetable.Time.ToString("hh':'mm"),
                    ArrivalTime = arrivalTime.ToString("hh':'mm"),
                };
                rows.Add(row);
            }
            return rows;
        }
Example #3
0
        private void AddOrUpdate(Lag lag, Match match, DataContext context, MatchImport.ExcelMatch excelMatch, List<Vaapen> våpen)
        {
            var existing = (from l in context.Lag
                            where l.LagId == lag.LagId
                            select l).FirstOrDefault();

            if (existing == null)
            {
                context.Lag.Add(lag);
            }
            else
            {
                existing.Navn = lag.Navn;
                existing.HemmeligKode = lag.HemmeligKode;
                existing.Farge = lag.Farge;
            }

            if (!match.DeltakendeLag.Any(x => x.Lag.LagId == lag.LagId))
            {
                var lagIMatch = match.LeggTil(existing ?? lag);

                // Legg til våpen bare på nye lag i matcher (dvs. ikke få flere våper ved flere importer)
                var felle = våpen.Single(x => x.VaapenId == Constants.Våpen.Felle);
                for (int i = 0; i < excelMatch.PrLagFelle.GetValueOrDefault(); i++)
                {
                    lagIMatch.LeggTilVåpen(felle);
                }

                var bombe = våpen.Single(x => x.VaapenId == Constants.Våpen.Bombe);
                for (int i = 0; i < excelMatch.PrLagBombe.GetValueOrDefault(); i++)
                {
                    lagIMatch.LeggTilVåpen(bombe);
                }
            }
        }
Example #4
0
        public void WebHookUri_Validates(Uri uri, ValidationOutcome expected)
        {
            // Arrange
            WebHook webHook = new WebHook { WebHookUri = uri };
            var validationResults = new List<ValidationResult>();
            var context = new ValidationContext(webHook) { MemberName = "WebHookUri" };

            // Act
            bool actual = Validator.TryValidateProperty(webHook.WebHookUri, context, validationResults);

            // Assert
            switch (expected)
            {
                case ValidationOutcome.Valid:
                    Assert.True(actual);
                    break;

                case ValidationOutcome.Required:
                    Assert.False(actual);
                    Assert.Equal("The WebHookUri field is required.", validationResults.Single().ErrorMessage);
                    Assert.Equal("WebHookUri", validationResults.Single().MemberNames.Single());
                    break;

                default:
                    Assert.True(false);
                    break;
            }
        }
        protected override void ApplyChanges(ref List<Objects.Option> initialOptions)
        {
            var tweetCountOption = initialOptions.Single(x => x.OptionId == (int)TwitterNotifier.TwitterOptionId.TweetCount);
            tweetCountOption.Active = TweetCountCheckbox.Checked;
            tweetCountOption.Numerics[0] = Convert.ToInt32(TweetCountMinutesNumericUpDown.Value);

            var directMessageOption = initialOptions.Single(x => x.OptionId == (int)TwitterNotifier.TwitterOptionId.DirectMessage);
            directMessageOption.Active = ReadDirectMessagecheckBox.Checked;
        }
 private static void ConnectDevicesToMessages(List<Device> devices, List<Message> messages)
 {
     messages.ForEach(x =>
         {
             x.SenderDevice = devices.Single(d => d.Key == x.FromId);
             if (x.ToId != null)
             {
                 x.RecieverDevice = devices.Single(d => d.Key == x.ToId);
             }
         });
 }
Example #7
0
        public Solution(string path)
        {
            SolutionPath = path;
            Name = Path.GetFileNameWithoutExtension(path);

            var projects = new List<Project>();

            IEnumerable<string> lines = File.ReadAllLines(path);
            var enumerator = lines.GetEnumerator();

            while (enumerator.MoveNext())
            {
                if (enumerator.Current.StartsWith("Project"))
                {
                    var projectFragment = new List<string> {enumerator.Current};

                    while (enumerator.MoveNext() && !enumerator.Current.StartsWith("EndProject"))
                    {
                        projectFragment.Add(enumerator.Current);
                    }

                    projectFragment.Add(enumerator.Current);

                    projects.Add(new Project(projectFragment));
                }

                if (enumerator.Current.Trim().StartsWith("GlobalSection(ProjectDependencies)"))
                {
                    while (enumerator.MoveNext() && !enumerator.Current.Trim().StartsWith("EndGlobalSection"))
                    {
                        var splitted = enumerator.Current.Trim()
                                                    .Split(new[] {' ', '.'}, StringSplitOptions.RemoveEmptyEntries);

                        var projectGuid = new Guid(splitted.First().Trim());
                        var dependencyGuid = new Guid(splitted.Last().Trim());

                        var project = projects.Single(prj => prj.Guid == projectGuid);

                        project.DependsOnGuids = new List<Guid>(project.DependsOnGuids) { dependencyGuid };
                    }
                }
            }

            foreach (var project in projects)
            {
                var dependsList = project.DependsOnGuids.ToList();

                project.DependsOnGuids = dependsList.Distinct().ToList();

                project.AllDependsOnProjects = dependsList.Select(guid => projects.Single(proj => proj.Guid == guid)).ToList();
            }

            Projects = prepareExplicitDependecies(projects.OrderBy(project => project.Name));
        }
        /// <summary>
        /// Creates a CommitInformation object from raw commit info data from git.  The string passed in should be
        /// exact output of a log or show command using --format=raw.
        /// </summary>
        /// <param name="rawData">Raw commit data from git.</param>
        /// <returns>CommitInformation object populated with parsed info from git string.</returns>
        public static CommitInformation CreateFromRawData(string rawData)
        {
            var lines = new List<string>(rawData.Split('\n'));

            var commit = lines.Single(l => l.StartsWith(COMMIT_LABEL));
            var guid = commit.Substring(COMMIT_LABEL.Length);
            lines.Remove(commit);

            // TODO: we can use this to add more relationship info like gitk does if wanted
            var tree = lines.Single(l => l.StartsWith(TREE_LABEL));
            var treeGuid = tree.Substring(TREE_LABEL.Length);
            lines.Remove(tree);

            // TODO: we can use this to add more relationship info like gitk does if wanted
            List<string> parentLines = lines.FindAll(l => l.StartsWith(PARENT_LABEL));
            var parentGuids = parentLines.Select(parent => parent.Substring(PARENT_LABEL.Length)).ToArray();
            lines.RemoveAll(parentLines.Contains);

            var authorInfo = lines.Single(l => l.StartsWith(AUTHOR_LABEL));
            var author = GetPersonFromAuthorInfoLine(authorInfo, AUTHOR_LABEL.Length);
            var authorDate = GetTimeFromAuthorInfoLine(authorInfo);
            lines.Remove(authorInfo);

            var committerInfo = lines.Single(l => l.StartsWith(COMMITTER_LABEL));
            var committer = GetPersonFromAuthorInfoLine(committerInfo, COMMITTER_LABEL.Length);
            var commitDate = GetTimeFromAuthorInfoLine(committerInfo);
            lines.Remove(committerInfo);

            var message = new StringBuilder();
            foreach (var line in lines)
                message.AppendFormat("{0}\n", line);

            var body = "\n\n" + message.ToString().TrimStart().TrimEnd() + "\n\n";

            //We need to recode the commit message because of a bug in Git.
            //We cannot let git recode the message to Settings.Encoding which is
            //needed to allow the "git log" to print the filename in Settings.Encoding
            Encoding logoutputEncoding = GitCommandHelpers.GetLogoutputEncoding();
            if (logoutputEncoding != Settings.Encoding)
                body = logoutputEncoding.GetString(Settings.Encoding.GetBytes(body));

            var header = FillToLenght(Strings.GetAuthorText() + ":", COMMITHEADER_STRING_LENGTH) + author + "\n" +
                         FillToLenght(Strings.GetAuthorDateText() + ":", COMMITHEADER_STRING_LENGTH) + GitCommandHelpers.GetRelativeDateString(DateTime.UtcNow, authorDate.UtcDateTime) + " (" + authorDate.LocalDateTime.ToString("ddd MMM dd HH':'mm':'ss yyyy") + ")\n" +
                         FillToLenght(Strings.GetCommitterText() + ":", COMMITHEADER_STRING_LENGTH) + committer + "\n" +
                         FillToLenght(Strings.GetCommitterDateText() + ":", COMMITHEADER_STRING_LENGTH) + GitCommandHelpers.GetRelativeDateString(DateTime.UtcNow, commitDate.UtcDateTime) + " (" + commitDate.LocalDateTime.ToString("ddd MMM dd HH':'mm':'ss yyyy") + ")\n" +
                         FillToLenght(Strings.GetCommitHashText() + ":", COMMITHEADER_STRING_LENGTH) + guid;

            header = RemoveRedundancies(header);

            var commitInformation = new CommitInformation(header, body);

            return commitInformation;
        }
        protected override void ApplyChanges(ref List<Objects.Option> initialOptions)
        {
            var tweetCountOption = initialOptions.Single(x => x.OptionId == (int)PrototypeNotifier.PrototypeOptionId.CountOption);
            tweetCountOption.Active = TweetCountCheckbox.Checked;
            tweetCountOption.Numerics[0] = Convert.ToInt32(TweetCountMinutesNumericUpDown.Value);

            var directMessageOption = initialOptions.Single(x => x.OptionId == (int)PrototypeNotifier.PrototypeOptionId.CheckedOnlyOption);
            directMessageOption.Active = ReadDirectMessagecheckBox.Checked;

            var newNotificationOption = initialOptions.Single(x => x.OptionId == (int)PrototypeNotifier.PrototypeOptionId.GestureOption);
            newNotificationOption.Active = ReactToNotificationsCheckBox.Checked;
        }
        public void Begin(List<Resource> resources)
        {
            _resourceCache = resources;
            _jobProcessor.SetJobTypes(resources);

            // Spawn Base/First Job
            var trooper = _resourceCache.Single(r => r.TableId.Equals("stormTrooper"));
            _jobProcessor.AddJob(trooper);

            var fighter = _resourceCache.Single(r => r.TableId.Equals("tieFighter"));
            _jobProcessor.AddJob(fighter);

            _timer.Start();
        }
        public static FerryJourney CreateFerryJourney(List<PortModel> ports, TimeTableEntry timetable)
        {
            if (ports == null)
                return null;

            if (timetable == null)
                return null;

            var fj = new FerryJourney
            {
                Origin = ports.Single(x => x.Id == timetable.OriginId),
                Destination = ports.Single(x => x.Id == timetable.DestinationId)
            };
            return fj;
        }
		private void Remove()
		{
			var serializer = new XmlSerializer(typeof(List<ModuleStateSave>));

			// Get existing saves if there are any.
			var existingSaves = new List<ModuleStateSave>();
			try
			{
				var fileReader = new StreamReader(AppDomain.CurrentDomain.BaseDirectory +
					Settings.Default.ModuleStateSaveFileName);
				existingSaves = (List<ModuleStateSave>)serializer.Deserialize(fileReader);
				fileReader.Close();
			}
			catch (Exception) { }

			// Remove existing save.
			existingSaves.Remove(existingSaves.Single(s => s.Name == selectedItem));

			// Overwrite file.
			var fileWriter = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory +
				Settings.Default.ModuleStateSaveFileName);
			serializer.Serialize(fileWriter, existingSaves);

			fileWriter.Close();

			controlCenterVM.ReloadModuleButtonContexts();
            //Write to console "'" + selectedItem + "' removed."
        }
Example #13
0
        public PokemonViewModel(Main main, List<PowerLevel> levels, List<Category> categories, List<Pokemon> pokemon, List<SpecialAttack> specialAttacks, List<StandardAttack> standardAttacks, List<UserName> users)
            : this()
        {
            this.AddDate = main.AddDate;
            this.EvolvedFrom = main.EvolvedFrom;
            this.Height = main.Height;
            this.HeightCategoryId = main.HeightCategory;
            this.Id = main.Id;
            this.PokemonId = main.PokemonId;
            this.SpecialAttack = main.SpecialAttack;
            this.StandardAttack = main.StandardAttack;
            this.TrainerLevelCaught = main.TrainerLevelCaught;
            this.Weight = main.Weight;
            this.WeightCategoryId = main.WeightCategory;
            this.XId = main.XId;
            this.PowerLevels = levels;

            this.PowerLevel = levels.Single(x => x.Id == levels.Max(y => y.Id));

            _categories = categories;
            _pokemon = pokemon;
            _specialAttacks = specialAttacks;
            _standardAttacks = standardAttacks;
            _users = users;
        }
Example #14
0
        public override IDocumentDTO CastByfToDTO(object byfRecord)
        {
            var byf = Cast(byfRecord);
            //if (byf.Id.Value == 4566788)
            //{
            //    var a = "DSAf";
            //}
            var stall  = _stalls?.Single(_ => _.Id == byf.Stall.Id.Value);
            var active = new LeaseDTO
            {
                Id                   = (int)byf.Id.Value,
                Tenant               = byf.Tenant.CastTenant(),
                Stall                = stall,
                ContractStart        = byf.ContractStart.ToLocalTime(),
                ContractEnd          = byf.ContractEnd.ToLocalTime(),
                ProductToSell        = byf.ProductToSell.Trim().NullIfBlank(),
                Rent                 = byf.CastRentParams(),
                Rights               = byf.CastRightsParams(),
                ApplicationSubmitted = byf.ApplicationSubmitted,
                Remarks              = byf.Remarks.Trim().NullIfBlank(),
            };

            //if (_terminations == null) return active;

            //if (_terminations.TryGetValue(byf.Id.Value, out DateTime termDate))
            //    return new InactiveLeaseDTO(active, "Terminated", termDate, "Migrator");
            //else
            //    return active;

            return(active.AsInactiveIfSo(_terminations, _lastClosedDate));
        }
Example #15
0
        public IEnumerable<MultipoolInformation> GetMultipoolInformation(string userAgent = "")
        {
            WebClient client = new ApiWebClient();
            if (!string.IsNullOrEmpty(userAgent))
                client.Headers.Add("user-agent", userAgent);

            string apiUrl = GetApiUrl();

            string jsonString = client.DownloadString(apiUrl);

            JObject jsonObject = JObject.Parse(jsonString);
            jsonObject = jsonObject.Value<JObject>("result");

            JArray jsonArray = jsonObject.Value<JArray>("stats");

            List<MultipoolInformation> result = new List<MultipoolInformation>();

            foreach (JToken jToken in jsonArray)
            {
                MultipoolInformation multipoolInformation = new MultipoolInformation();
                if (multipoolInformation.PopulateFromJson(jToken))
                    result.Add(multipoolInformation);
            }

            MultipoolInformation btcInformation = result.Single(mpi => mpi.Algorithm.Equals(AlgorithmNames.SHA256));

            foreach (MultipoolInformation otherInformation in result)
            {
                KnownAlgorithm knownAlgorithm = KnownAlgorithms.Algorithms.Single(ka => ka.Name.Equals(otherInformation.Algorithm));
                otherInformation.Profitability = ((otherInformation.Price * knownAlgorithm.Multiplier) / btcInformation.Price) * PoolProfitability * 100;
            }

            return result;
        }
        public void Interpret(string infix)
        {
            _stToLex = new StringToLexem(infix);

            while ((_lexems = _stToLex.ToLexems()).Count > 0 || _lexems.Any(x =>
                x.LexemType == LexemType.EndOfExpr || x.LexemType == LexemType.Brace))
            {
                if (_skipToCloseBrace)
                {
                    int opennedBraces = 0;
                    while (!_lexems.Any(x => x.LexemType == LexemType.Brace && x.Content.ToString() == "}" && opennedBraces == 0))
                    {
                        if (_lexems.Any(x => x.LexemType == LexemType.Brace))
                        {
                            var brace = _lexems.Single(x => x.LexemType == LexemType.Brace);
                            if (brace.Content.ToString() == "{") opennedBraces++; else opennedBraces--;
                        }
                        _lexems = _stToLex.ToLexems();
                    }
                }
                Output.Clear();
                ToRPN();
                Stack.Clear();
                Eval();
            }
        }
Example #17
0
        private PaymentCartViewModel PopulateViewModel(List <OrderItemSessionModel> orderItemsSessionModel, List <KeyValuePair <int, int> > quantityData = null)
        {
            decimal netTotal  = 0;
            var     viewModel = new PaymentCartViewModel();

            foreach (var orderItemSessionModel in orderItemsSessionModel)
            {
                var quantity = quantityData?.Single(x => x.Key == orderItemSessionModel.Product.Id).Value ?? orderItemSessionModel.Quantity;
                orderItemSessionModel.Quantity = quantity;

                var item = new PaymentCartItem
                {
                    ProductId   = orderItemSessionModel.Product.Id,
                    Name        = orderItemSessionModel.Product.Name,
                    Description = orderItemSessionModel.Product.Category,
                    Price       = orderItemSessionModel.Product.Price,
                    Quantity    = quantity
                };

                viewModel.Items.Add(item);
                netTotal += item.Price.Price * item.Quantity;

                foreach (var property in orderItemSessionModel.Properties)
                {
                    var subItem = new PaymentCartItem
                    {
                        ProductId   = orderItemSessionModel.Product.Id,
                        Name        = orderItemSessionModel.Product.Name,
                        Description = $"{property.Type} - {property.Name} {property.Value} {property.Unit}",
                        Price       = property.Price,
                        Quantity    = item.Quantity
                    };

                    item.SubItems.Add(subItem);

                    netTotal += subItem.Price.Price * subItem.Quantity;
                }
            }

            var vat        = netTotal * ((decimal)10.0 / 100);
            var grossTotal = netTotal + vat;

            viewModel.GrossTotal = grossTotal;
            viewModel.Vat        = vat;
            viewModel.NetTotal   = netTotal;
            viewModel.Currency   = orderItemsSessionModel[0].Product.Price.Currency;

            var paymentSessionModel = new PaymentSessionModel
            {
                OrderCode  = $"TT{DateTime.Now:yyMMdd}{Guid.NewGuid().ToString().Split('-')[1].ToUpper()}",
                GrossTotal = grossTotal,
                Vat        = vat,
                NetTotal   = netTotal,
                Currency   = viewModel.Currency
            };

            HttpContext.Session.Set(SessionConstants.PAYMENT_SESSION_MODEL_NAME, paymentSessionModel);

            return(viewModel);
        }
Example #18
0
        public void InitDataBase(string connectionString)
        {
            using (var ctx = new Context(connectionString))
            {
                if (ctx.Database.Exists())
                    ctx.Database.Delete();
                ctx.Database.Initialize(true);
                List<Province> entityProwinces = new List<Province>();
                foreach (var province in ProvinceData.GetProvinces())
                {
                    var prow = new Province { Code = province.Code, Name = province.Name };
                    ctx.Provinces.Add(prow);
                    ctx.SaveChanges();
                    entityProwinces.Add(prow);
                }

                BulkUploadToSql bulk =
                    BulkUploadToSql.Load(
                        HomeData.GetHomes()
                            .Select(
                                i =>
                                    new Bulk.Home
                                    {
                                        AddTime = DateTime.Now,
                                        BuildYear = i.BuildYear,
                                        City = i.City,
                                        Description = i.Description,
                                        Price = i.Price,
                                        Surface = i.Surface,
                                        ProvinceId = entityProwinces.Single(j => j.Code == i.HomeProvince.Code).Id
                                    }), "Home", 10000, connectionString);
                bulk.Flush();

            }
        }
Example #19
0
    static void Main(string[] args)
    {
        const int NUMBER_OF_POSITIONS = 4;
        Console.Error.WriteLine("Using {0} positions", NUMBER_OF_POSITIONS);

        var allPositions = Enumerable.Range(0, NUMBER_OF_POSITIONS).ToArray();

        var validValues = new List<int[][]> {
            Enumerable.Repeat(Enumerable.Range(0, 10).ToArray(), NUMBER_OF_POSITIONS).ToArray()
        };

        logSolutions(validValues);

        int N = int.Parse(Console.ReadLine());
        for (int i = 0; i < N; i++)
        {
            string[] inputs = Console.ReadLine().Split(' ');
            int[] guess = inputs[0].Select(x => int.Parse(x.ToString())).ToArray();
            int bulls = int.Parse(inputs[1]);
            int cows = int.Parse(inputs[2]);
            Console.Error.WriteLine("guess {0} == {1} bulls + {2} cows", inputs[0], bulls, cows);

            validValues = validValues.SelectMany(possibility =>
                solve(possibility, guess, bulls, cows, NUMBER_OF_POSITIONS - 1)
            ).ToList();

            logSolutions(validValues);
        }

        var solution = string.Join("", validValues.Single().Select(x => x.Single()).ToArray());
        Console.WriteLine(solution);
        Console.ReadLine();
    }
Example #20
0
        /// <summary>
        /// Inner calculation, don't call this directly
        /// </summary>
        private static string FindPermutationAt(List<string> alphabet, int currentIndex, int searchIndex)
        {
            // Factorial computation, does this exist in .NET framework already?
            Func<int, int> factorial = n => Enumerable.Range(1, n).Aggregate((acc, x) => acc * x);

            // Exit condition
            if (alphabet.Count == 1)
            {
                return alphabet.Single();
            }

            // Number of combinations for each sybil in the alphabet
            int combinations = factorial(alphabet.Count - 1);

            // foreach sybil in alphabet
            for (int i = 0, lowIndex = currentIndex; i < alphabet.Count; i++, lowIndex += combinations)
            {
                int highIndex = lowIndex + combinations;

                // Search index should be between lowIndex and highIndex
                if (searchIndex >= lowIndex && searchIndex <= highIndex)
                {
                    var found = alphabet[i];

                    // Remove found sybil from alphabet
                    var newAlphabet = alphabet.Except(new[] { found }).ToList();

                    // Add and recurse
                    return found + FindPermutationAt(newAlphabet, lowIndex, searchIndex);
                }
            }

            // Should only end up here if we ask for searchIndex more than max
            throw new IndexOutOfRangeException("No such index exist in permutation: " + searchIndex);
        }
 internal void InitNetBrowser ()
 {
     _serviceList = new List<NSNetService> ();
     _netBrowser = new NSNetServiceBrowser ();
     
     _source = new ServicesTableSource (this);
     servicesTable.Source = _source;
     
     _netBrowser.SearchForServices ("_bonjourdemoservice._tcp", "");
     
     _netBrowser.FoundService += delegate(object sender, NSNetServiceEventArgs e) {
         logView.AppendTextLine (String.Format ("{0} added", e.Service.Name));
         
         _serviceList.Add (e.Service);
         
         e.Service.AddressResolved += ServiceAddressResolved;
         
         // NOTE: could also insert and remove rows in a
         // more fine grained fashion here as well
         servicesTable.ReloadData ();
     };
     
     _netBrowser.ServiceRemoved += delegate(object sender, NSNetServiceEventArgs e) {
         logView.AppendTextLine (String.Format ("{0} removed", e.Service.Name));
         
         var nsService = _serviceList.Single (s => s.Name.Equals (e.Service.Name));
         _serviceList.Remove (nsService);
         servicesTable.ReloadData ();
     };
 }
Example #22
0
 private static int GetMaxHappiness(Stack<string> atTable, List<string> free, Conditions conditions)
 {
     if (free.Count == 1)
     {
         atTable.Push(free.Single());
         var table = new Table(atTable.ToList());
         var totalHappiness = table.CalcTotalHappiness(conditions);
         atTable.Pop();
         return totalHappiness;
     }
     var maxHappiness = 0;
     for (int i = 0; i < free.Count; i++)
     {
         atTable.Push(free[i]);
         free.RemoveAt(i);
         var happiness = GetMaxHappiness(atTable, free, conditions);
         if (happiness > maxHappiness)
         {
             maxHappiness = happiness;
         }
         var person = atTable.Pop();
         free.Insert(i, person);
     }
     return maxHappiness;
 }
Example #23
0
        public static Color ModifyColor(Color baseColor, List<WeightedColor> modifyingWeightedColors)
        {
            // remove any modifiers that have no effect
            modifyingWeightedColors = modifyingWeightedColors.Where(weightedColor => weightedColor.Weight > 0.0).ToList();

            // if there are no colours to apply, return the base color
            var color = baseColor;
            if (modifyingWeightedColors.Count == 0)
            {
                return color;
            }

            // if there is only one colour to apply, do so and return
            if (modifyingWeightedColors.Count == 1)
            {
                var modifier = modifyingWeightedColors.Single();
                color = InterpolateColor(color, modifier.Color, modifier.Weight);
                return color;
            }

            // if there are two or more colours to apply
            // calculate the colour of the modifiers and apply it using the max weighting of all modifiers
            var modifierOpacity = modifyingWeightedColors.Max(weightedColor => weightedColor.Weight);
            var modifierColor = InterpolateWeightedColors(modifyingWeightedColors);
            color = InterpolateColor(color, modifierColor, modifierOpacity);
            return color;
        }
Example #24
0
        private void btnLogin_Click(object sender, EventArgs e)
        {
            List<User> users = new List<User>();

            using (ClinicModel context = new ClinicModel())
            {
                users = context.Users
                    .Where(x => x.Username == txtUsername.Text)
                    .ToList();
            }

            if (users.Count == 0)
            {
                DialogResult = DialogResult.No;
                Close();
            }
            else
            {
                User user = users.Single(); 

                if (user.Password.Equals(txtPassword.Text))
                {
                    DialogResult = DialogResult.OK;
                    Close();
                }
                else
                {
                    DialogResult = DialogResult.No;
                    Close();
                }
            }
        }
Example #25
0
        public ActionResult Index()
        {
            var model = new List<SettingsViewModel>();

            foreach (object enumVal in Enum.GetValues(typeof (SettingField)))
            {
                if (((SettingField) enumVal).GetAttributeOfType<CategoryAttribute>() == null)
                    continue;

                var setting = new SettingViewModel();
                setting.Key = Enum.GetName(typeof (SettingField), enumVal);
                setting.Name = ((SettingField) enumVal).GetAttributeOfType<NameAttribute>().Name.TA();

                setting.Value = settings.Get<object>(((SettingField) enumVal)).ToString();

                setting.EditorType = ((SettingField) enumVal).GetAttributeOfType<UIHintAttribute>() != null
                    ? ((SettingField) enumVal).GetAttributeOfType<UIHintAttribute>().UIHint
                    : ((SettingField) enumVal).GetAttributeOfType<TypeAttribute>().Type.Name;

                var category = ((SettingField) enumVal).GetAttributeOfType<CategoryAttribute>().Category.TA();

                if (model.None(s => s.Category == category))
                    model.Add(new SettingsViewModel { Category = category, Settings = new List<SettingViewModel>() });
                model.Single(s => s.Category == category).Settings.Add(setting);
            }

            return View(model);
        }
        /// <summary>
        /// The main Process method converts an intermediate format content pipeline
        /// NodeContent tree to a ModelContent object with embedded animation data.
        /// </summary>
        public override ModelContent Process(NodeContent input, ContentProcessorContext context)
        {
            contentPath = Environment.CurrentDirectory;

            using (XmlReader reader = XmlReader.Create(MaterialDataFilePath))
            {
                incomingMaterials = IntermediateSerializer.Deserialize<List<MaterialData>>(reader, null);
            }
            context.AddDependency(Path.Combine(Environment.CurrentDirectory, MaterialDataFilePath));

            // Chain to the base ModelProcessor class so it can convert the model data.
            ModelContent model = base.Process(input, context);

            // Put the material's flags into the ModelMeshPartContent's Tag property.
            foreach (ModelMeshContent mmc in model.Meshes)
            {
                foreach (ModelMeshPartContent mmpc in mmc.MeshParts)
                {
                    MaterialData mat = incomingMaterials.Single(m => m.Name == mmpc.Material.Name);
                    MaterialInfo extraInfo = new MaterialInfo();
                    extraInfo.HandlingFlags = mat.HandlingFlags;
                    extraInfo.RenderState = mat.RenderState;
                    mmpc.Tag = extraInfo;
                }
            }

            return model;
        }
Example #27
0
        public ScreenRecordForm( IPluginHost pluginHost )
            : base(pluginHost)
        {
            this.StickyWindow = new DroidExplorer.UI.StickyWindow ( this );
            CommonResolutions = GetCommonResolutions ( );
            InitializeComponent ( );

            var defaultFile = "screenrecord_{0}_{1}.mp4".With ( this.PluginHost.Device, DateTime.Now.ToString ( "yyyy-MM-dd-hh" ) );
            this.location.Text = "/sdcard/{0}".With ( defaultFile );

            var resolution = new VideoSize ( PluginHost.CommandRunner.GetScreenResolution ( ) );
            var sizes = CommonResolutions.Concat ( new List<VideoSize> { resolution } ).OrderBy ( x => x.Size.Width ).Select ( x => x ).ToList ( );
            resolutionList.DataSource = sizes;
            resolutionList.DisplayMember = "Display";
            resolutionList.ValueMember = "Size";
            resolutionList.SelectedItem = resolution;

            rotateList.DataSource = GetRotateArgumentsList ( );
            rotateList.DisplayMember = "Display";
            rotateList.ValueMember = "Arguments";

            var bitrates = new List<BitRate> ( );

            for ( int i = 1; i < 25; i++ ) {
                bitrates.Add ( new BitRate ( i ) );
            }

            bitrateList.DataSource = bitrates;
            bitrateList.DisplayMember = "Display";
            bitrateList.ValueMember = "Value";
            bitrateList.SelectedItem = bitrates.Single ( x => x.Mbps == 4 );
            var ts = new TimeSpan ( 0, 0, 0, timeLimit.Value, 0 );
            displayTime.Text = ts.ToString ( );
        }
Example #28
0
 public List<humanresourcesDataSet.vw_resume_candidateRow> SearchCandidate()
 {
     List<humanresourcesDataSet.vw_resume_candidateRow> dt = new List<humanresourcesDataSet.vw_resume_candidateRow>();
     dt = this.vw_resume_candidateTableAdapter1.GetDataBySearch("%" + this.txtCandidate_name.Text + "%", "%" + this.txtOther.Text + "%", "%" + this.txtpapersN.Text + "%", "%" + this.txtEMail.Text + "%", "%" + this.txtRegister.Text + "%", "%" + this.txtMobile.Text + "%").ToList();
     dt = rbtnSexBoth.Checked ? dt : dt.Where(d => (d.Candidate_sex == 1) == this.rbtnMale.Checked).ToList();
     dt = this.cboNationality.SelectedItem == null ? dt : dt.Where(d => d.Nationality_id == (cboNationality.SelectedItem as humanresourcesDataSet.nationalityRow).Nationality_id).ToList();
     dt = this.cboMinz.SelectedItem == null ? dt : dt.Where(d => d.Mingz_id == (cboMinz.SelectedItem as humanresourcesDataSet.mingzRow).Mingz_id).ToList();
     dt = !this.checkBox1.Checked?dt: dt.Where(d => d.Candidate_birthday.Date >= this.dateTimePicker1.Value.Date && d.Candidate_birthday.Date <= this.dateTimePicker3.Value.Date).ToList();
     dt = this.cboCandidate_marriage.SelectedIndex <= 0 ? dt : dt.Where(d => d.Candidate_marriage == this.cboCandidate_marriage.SelectedItem as string).ToList();
     dt = this.cboCity1.SelectedItem == null ? dt : dt.Where(d => d.City_id == (cboCity1.SelectedItem as humanresourcesDataSet.cityRow).City_id).ToList();
     dt = this.cboCity2.SelectedItem == null ? dt : dt.Where(d => d.City_id == (cboCity2.SelectedItem as humanresourcesDataSet.cityRow).City_id).ToList();
     if (this.checkBox2.Checked)
     {
         List<int> id = new List<int>();
         foreach (humanresourcesDataSet.vw_resume_candidateRow item in dt)
         {
             humanresourcesDataSet.work_experienceRow w = this.tableAdapterManager1.work_experienceTableAdapter.GetFirstDataByResumeID(item.Resume_id).SingleOrDefault();
             if (w != null)
             {
                 if (w.WE_DateS.Date < this.dateTimePicker2.Value.Date || w.WE_DateS.Date > this.dateTimePicker4.Value.Date )
                 {
                     id.Add(item.Resume_id);
                 }
             }
             else
             {
                 id.Add(item.Resume_id);
             }
         }
         foreach (int item in id)
         {
             dt.Remove(dt.Single(d => d.Resume_id == item));
         }
     }
     if (!string.IsNullOrEmpty(this.textBox5.Text) || !string.IsNullOrEmpty(this.textBox4.Text))
     {
         List<int> id = new List<int>();
         foreach (humanresourcesDataSet.vw_resume_candidateRow item in dt)
         {
             humanresourcesDataSet.work_experienceRow w = this.tableAdapterManager1.work_experienceTableAdapter.GetLastDataByResumeID(item.Resume_id).SingleOrDefault();
             if (w != null)
             {
                 if (!w.WE_name.Contains(this.textBox5.Text.Trim()) || !w.WE_position.Contains(this.textBox4.Text.Trim()))
                 {
                     id.Add(item.Resume_id);
                 }
             }
             else
             {
                 id.Add(item.Resume_id);
             }
         }
         foreach (int item in id)
         {
             dt.Remove(dt.Single(d => d.Resume_id == item));
         }
     }
     return dt;
 }
        public void display_attribute_takes_precedence_over_displayname_attribute()
        {
            var model = new DisplayModel();
            var context = new ValidationContext(model);

            var results = new List<ValidationResult>();

            model.Value3 = null;
            Validator.TryValidateObject(model, context, results, true);
            Assert.Equal("requiredif only chosen", results.Single().ErrorMessage);

            results.Clear();

            model.Value3 = new object();
            Validator.TryValidateObject(model, context, results, true);
            Assert.Equal("assertthat only chosen", results.Single().ErrorMessage);
        }
		public override void BuildInto(List<LanguageConstruct> destination)
		{
			var prelude = new List<LanguageConstruct>();
			Prelude.BuildInto(prelude);
			var bodyConstructs = new List<LanguageConstruct>();
			_BuildBodyInto(bodyConstructs);
			destination.Add(new UnknownBlock(StartsParagraph, (UnknownPrelude) prelude.Single(), bodyConstructs, Errors));
		}
Example #31
0
 private async Task<List<Models.Usuario>> RecuperarMembros()
 {
     var httpClient = Servico.Instanciar();
     var response = await httpClient.GetAsync("api/usuario?grupo=" + grupo.Id);
     var strJson = response.Content.ReadAsStringAsync().Result;
     membros = JsonConvert.DeserializeObject<List<Models.Usuario>>(strJson);
     membros.Remove(membros.Single(m => m.Id == usuario.Id));
     return membros;
 }
Example #32
0
        public ContactDirectory()
        {
            teams = new List<Team>();

              contacts = DemoData.GetRandomContacts(5000);

              var t1 = new Team()
              {
            Name = "X Ray",
            Id = "8888",
            TeamMembers = new List<Contact>()
              };

              t1.TeamMembers.Add(contacts.Single(m => m.Id == "1111"));
              t1.TeamMembers.Add(contacts.Single(m => m.Id == "2222"));

              teams.Add(t1);
        }
Example #33
0
        private static IEnumerable <Article> CreateArticlesWithChildren()
        {
            var authors = new List <Author>
            {
                new Author {
                    Id = 1, FirstName = "Stuart", LastName = "Anderson"
                },
                new Author {
                    Id = 2, FirstName = "Elaina", LastName = "Loveland"
                },
                new Author {
                    Id = 3, FirstName = "Susan", LastName = "Ladika"
                }
            };

            var subjects = new List <Subject>
            {
                new Subject {
                    Id = 1, Name = "Ethics"
                },
                new Subject {
                    Id = 2, Name = "Global Citizenship"
                },
                new Subject {
                    Id = 3, Name = "Higher Education"
                },
                new Subject {
                    Id = 4, Name = "Public Policy"
                }
            };

            var articles = new List <Article> {
                new Article {
                    Id              = 1,
                    Title           = "All-in-One Comprehensive Immigration Reform",
                    Page            = 4,
                    Issue           = Issues.Fall,
                    PublicationYear = PublicationYears.Y2013,
                    IsSupplement    = false,
                    Hyperlink       = "http://www.nafsa.org/_/File/_/ie_julaug13_frontlines.pdf",
                    Authors         = new List <Author> {
                        authors.Single(x => x.FirstName == "Stuart" && x.LastName == "Anderson")
                    },
                    Subjects = new List <Subject>
                    {
                        subjects.Single(x => x.Name == "Higher Education"),
                        subjects.Single(x => x.Name == "Public Policy")
                    }
                },
                new Article {
                    Id              = 2,
                    Title           = "From Undocumented Immigrant to Brain Surgeon: An Interview with Alfredo Quiñones-Hinojosa",
                    Page            = 20,
                    Issue           = Issues.Summer,
                    PublicationYear = PublicationYears.Y2013,
                    IsSupplement    = false,
                    Hyperlink       = "http://www.nafsa.org/_/File/_/ie_julaug13_voices.pdf",
                    Authors         = new List <Author> {
                        authors.Single(x => x.FirstName == "Elaina" && x.LastName == "Loveland")
                    },
                    Subjects = new List <Subject>
                    {
                        subjects.Single(x => x.Name == "Higher Education"),
                        subjects.Single(x => x.Name == "Public Policy"),
                        subjects.Single(x => x.Name == "Global Citizenship")
                    }
                },
                new Article {
                    Id              = 3,
                    Title           = "A Champion for Development, Security, and Human Rights: An Interview with Kofi Annan",
                    Page            = 4,
                    Issue           = Issues.Spring,
                    PublicationYear = PublicationYears.Y2013,
                    IsSupplement    = false,
                    Hyperlink       = "http://www.nafsa.org/_/File/_/ie_mayjun13_voices.pdf",
                    Authors         = new List <Author> {
                        authors.Single(x => x.FirstName == "Elaina" && x.LastName == "Loveland")
                    },
                    Subjects = new List <Subject>
                    {
                        subjects.Single(x => x.Name == "Ethics"),
                        subjects.Single(x => x.Name == "Global Citizenship")
                    }
                },
                new Article {
                    Id              = 4,
                    Title           = "A Perspective on Communism's Collapse and European Higher Education",
                    Page            = 34,
                    Issue           = Issues.Spring,
                    PublicationYear = PublicationYears.Y2013,
                    IsSupplement    = false,
                    Authors         = new List <Author> {
                        authors.Single(x => x.FirstName == "Elaina" && x.LastName == "Loveland")
                    },
                    Subjects = new List <Subject>
                    {
                        subjects.Single(x => x.Name == "Higher Education"),
                        subjects.Single(x => x.Name == "Public Policy")
                    }
                },
                new Article {
                    Id              = 5,
                    Title           = "Building a Literate World",
                    Page            = 14,
                    Issue           = Issues.Fall,
                    PublicationYear = PublicationYears.Y2013,
                    IsSupplement    = false,
                    Authors         = new List <Author> {
                        authors.Single(x => x.FirstName == "Susan" && x.LastName == "Ladika")
                    },
                    Subjects = new List <Subject>
                    {
                        subjects.Single(x => x.Name == "Higher Education"),
                        subjects.Single(x => x.Name == "Global Citizenship")
                    }
                }
            };

            return(articles);
        }
Example #34
0
        protected override void Seed(SchoolContext context)
        {
            var students = new List <Student>
            {
                new Student {
                    FirstMidName   = "Carson", LastName = "Alexander",
                    EnrollmentDate = DateTime.Parse("2010-09-01")
                },
                new Student {
                    FirstMidName   = "Meredith", LastName = "Alonso",
                    EnrollmentDate = DateTime.Parse("2012-09-01")
                },
                new Student {
                    FirstMidName   = "Arturo", LastName = "Anand",
                    EnrollmentDate = DateTime.Parse("2013-09-01")
                },
                new Student {
                    FirstMidName   = "Gytis", LastName = "Barzdukas",
                    EnrollmentDate = DateTime.Parse("2012-09-01")
                },
                new Student {
                    FirstMidName   = "Yan", LastName = "Li",
                    EnrollmentDate = DateTime.Parse("2012-09-01")
                },
                new Student {
                    FirstMidName   = "Peggy", LastName = "Justice",
                    EnrollmentDate = DateTime.Parse("2011-09-01")
                },
                new Student {
                    FirstMidName   = "Laura", LastName = "Norman",
                    EnrollmentDate = DateTime.Parse("2013-09-01")
                },
                new Student {
                    FirstMidName   = "Nino", LastName = "Olivetto",
                    EnrollmentDate = DateTime.Parse("2005-09-01")
                }
            };

            students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, s));
            context.SaveChanges();

            var instructors = new List <Instructor>
            {
                new Instructor {
                    FirstMidName = "Kim", LastName = "Abercrombie",
                    HireDate     = DateTime.Parse("1995-03-11")
                },
                new Instructor {
                    FirstMidName = "Fadi", LastName = "Fakhouri",
                    HireDate     = DateTime.Parse("2002-07-06")
                },
                new Instructor {
                    FirstMidName = "Roger", LastName = "Harui",
                    HireDate     = DateTime.Parse("1998-07-01")
                },
                new Instructor {
                    FirstMidName = "Candace", LastName = "Kapoor",
                    HireDate     = DateTime.Parse("2001-01-15")
                },
                new Instructor {
                    FirstMidName = "Roger", LastName = "Zheng",
                    HireDate     = DateTime.Parse("2004-02-12")
                }
            };

            instructors.ForEach(s => context.Instructors.AddOrUpdate(p => p.LastName, s));
            context.SaveChanges();

            var departments = new List <Department>
            {
                new Department {
                    Name         = "English", Budget = 350000,
                    StartDate    = DateTime.Parse("2007-09-01"),
                    InstructorID = instructors.Single(i => i.LastName == "Abercrombie").ID
                },
                new Department {
                    Name         = "Mathematics", Budget = 100000,
                    StartDate    = DateTime.Parse("2007-09-01"),
                    InstructorID = instructors.Single(i => i.LastName == "Fakhouri").ID
                },
                new Department {
                    Name         = "Engineering", Budget = 350000,
                    StartDate    = DateTime.Parse("2007-09-01"),
                    InstructorID = instructors.Single(i => i.LastName == "Harui").ID
                },
                new Department {
                    Name         = "Economics", Budget = 100000,
                    StartDate    = DateTime.Parse("2007-09-01"),
                    InstructorID = instructors.Single(i => i.LastName == "Kapoor").ID
                }
            };

            departments.ForEach(s => context.Departments.AddOrUpdate(p => p.Name, s));
            context.SaveChanges();

            var courses = new List <Course>
            {
                new Course {
                    CourseID     = 1050, Title = "Chemistry", Credits = 3,
                    DepartmentID = departments.Single(s => s.Name == "Engineering").DepartmentID,
                    Instructors  = new List <Instructor>()
                },
                new Course {
                    CourseID     = 4022, Title = "Microeconomics", Credits = 3,
                    DepartmentID = departments.Single(s => s.Name == "Economics").DepartmentID,
                    Instructors  = new List <Instructor>()
                },
                new Course {
                    CourseID     = 4041, Title = "Macroeconomics", Credits = 3,
                    DepartmentID = departments.Single(s => s.Name == "Economics").DepartmentID,
                    Instructors  = new List <Instructor>()
                },
                new Course {
                    CourseID     = 1045, Title = "Calculus", Credits = 4,
                    DepartmentID = departments.Single(s => s.Name == "Mathematics").DepartmentID,
                    Instructors  = new List <Instructor>()
                },
                new Course {
                    CourseID     = 3141, Title = "Trigonometry", Credits = 4,
                    DepartmentID = departments.Single(s => s.Name == "Mathematics").DepartmentID,
                    Instructors  = new List <Instructor>()
                },
                new Course {
                    CourseID     = 2021, Title = "Composition", Credits = 3,
                    DepartmentID = departments.Single(s => s.Name == "English").DepartmentID,
                    Instructors  = new List <Instructor>()
                },
                new Course {
                    CourseID     = 2042, Title = "Literature", Credits = 4,
                    DepartmentID = departments.Single(s => s.Name == "English").DepartmentID,
                    Instructors  = new List <Instructor>()
                },
            };

            courses.ForEach(s => context.Courses.AddOrUpdate(p => p.CourseID, s));
            context.SaveChanges();

            var officeAssignments = new List <OfficeAssignment>
            {
                new OfficeAssignment {
                    InstructorID = instructors.Single(i => i.LastName == "Fakhouri").ID,
                    Location     = "Smith 17"
                },
                new OfficeAssignment {
                    InstructorID = instructors.Single(i => i.LastName == "Harui").ID,
                    Location     = "Gowan 27"
                },
                new OfficeAssignment {
                    InstructorID = instructors.Single(i => i.LastName == "Kapoor").ID,
                    Location     = "Thompson 304"
                },
            };

            officeAssignments.ForEach(s => context.OfficeAssignments.AddOrUpdate(p => p.InstructorID, s));
            context.SaveChanges();

            AddOrUpdateInstructor(context, "Chemistry", "Kapoor");
            AddOrUpdateInstructor(context, "Chemistry", "Harui");
            AddOrUpdateInstructor(context, "Microeconomics", "Zheng");
            AddOrUpdateInstructor(context, "Macroeconomics", "Zheng");

            AddOrUpdateInstructor(context, "Calculus", "Fakhouri");
            AddOrUpdateInstructor(context, "Trigonometry", "Harui");
            AddOrUpdateInstructor(context, "Composition", "Abercrombie");
            AddOrUpdateInstructor(context, "Literature", "Abercrombie");

            context.SaveChanges();

            var enrollments = new List <Enrollment>
            {
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alexander").ID,
                    CourseID  = courses.Single(c => c.Title == "Chemistry").CourseID,
                    Grade     = Grade.A
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alexander").ID,
                    CourseID  = courses.Single(c => c.Title == "Microeconomics").CourseID,
                    Grade     = Grade.C
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alexander").ID,
                    CourseID  = courses.Single(c => c.Title == "Macroeconomics").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alonso").ID,
                    CourseID  = courses.Single(c => c.Title == "Calculus").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alonso").ID,
                    CourseID  = courses.Single(c => c.Title == "Trigonometry").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alonso").ID,
                    CourseID  = courses.Single(c => c.Title == "Composition").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Anand").ID,
                    CourseID  = courses.Single(c => c.Title == "Chemistry").CourseID
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Anand").ID,
                    CourseID  = courses.Single(c => c.Title == "Microeconomics").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Barzdukas").ID,
                    CourseID  = courses.Single(c => c.Title == "Chemistry").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Li").ID,
                    CourseID  = courses.Single(c => c.Title == "Composition").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Justice").ID,
                    CourseID  = courses.Single(c => c.Title == "Literature").CourseID,
                    Grade     = Grade.B
                }
            };

            foreach (Enrollment e in enrollments)
            {
                var enrollmentInDataBase = context.Enrollments.Where(
                    s =>
                    s.Student.ID == e.StudentID &&
                    s.Course.CourseID == e.CourseID).SingleOrDefault();
                if (enrollmentInDataBase == null)
                {
                    context.Enrollments.Add(e);
                }
            }
            context.SaveChanges();
        }
Example #35
0
 public Courses GetByID(int id)
 {
     return(coursesList.Single(c => c.ID == id));
 }
Example #36
0
        static void ExportOrders()
        {
            _logger.Debug("ExportOrders ");
            DateTime dtstart = new DateTime(2019, 01, 31);
            var      existsD = AlohaFly.DBProvider.Client.GetDishList().Result.Where(a => a.IsToGo);

            var existsOrders = AlohaFly.DBProvider.Client.GetOrderToGoList(new OrderToGoFilter()
            {
                DeliveryDateStart = dtstart.AddDays(-5),
                DeliveryDateEnd   = DateTime.Now.AddDays(5)
            }, new PageInfo()
            {
                Skip = 0,
                Take = 1000
            }
                                                                           ).Result.Select(a => a.OldId).ToList();

            var custs     = AlohaFly.DBProvider.Client.GetOrderCustomerList().Result;
            var oldOrders = db.Orders.Where(a => a.DateDelivery >= dtstart && !existsOrders.Contains(a.ID));

            List <OrderCustomerAddress> addresses = new List <OrderCustomerAddress>();

            foreach (var addrList in custs.Select(a => a.Addresses))
            {
                addresses.AddRange(addrList);
            }
            foreach (var ord in oldOrders)
            {
                try
                {
                    _logger.Debug("ToGoOrder " + ord.ID);
                    OrderToGo ordNew = new OrderToGo();
                    ordNew.OldId       = ord.ID;
                    ordNew.AddressId   = addresses.Single(a => a.OldId == ord.AddressID).Id;
                    ordNew.PhoneNumber = db.Tel.Single(a => a.ID == ord.TelID).Number;
                    //  ordNew.Comment = ord.CommentCourier;
                    ordNew.CommentKitchen = ord.CommentKitchen;
                    ordNew.CreatedById    = GetOpenId(ord.Operator);
                    _logger.Debug("ordNew.CreatedById ");
                    ordNew.CreationDate       = ord.CreateDate + ord.CreateTime;
                    ordNew.DeliveryDate       = ord.DateDelivery.GetValueOrDefault();// + ord.TimeDelivery.GetValueOrDefault();
                    ordNew.DiscountPercent    = 0;
                    ordNew.IsSHSent           = false;
                    ordNew.MarketingChannelId = ord.SaleChannelID;
                    ordNew.ReadyTime          = ord.DateReady.GetValueOrDefault();//+ord.TimeReady
                    _logger.Debug("ordNew.ReadyTime");
                    ordNew.OrderCustomerId = custs.Single(a => a.OldId == ord.ClientID).Id;
                    _logger.Debug("ordNew.OrderCustomerId ");
                    ordNew.DriverId = GetDriverId(ord.Courier);
                    _logger.Debug("ordNew.DriverId ");
                    ordNew.OrderStatus = GetStatus(ord.Status.GetValueOrDefault());
                    _logger.Debug("ordNew.OrderStatus ");
                    ordNew.Summ = ord.Summ.GetValueOrDefault();
                    _logger.Debug("ordNew.Summ ");
                    ordNew.DeliveryPrice = ord.DeliveryPrice.GetValueOrDefault();
                    var packs = new List <DishPackageToGoOrder>();
                    foreach (var d in db.OrderContent.Where(a => a.OrderID == ord.ID))
                    {
                        _logger.Debug("d.Name; 0");
                        var nd = new DishPackageToGoOrder();
                        nd.DishName   = d.Name;
                        nd.Amount     = d.Amount.GetValueOrDefault();
                        nd.Comment    = d.WarmUP;
                        nd.TotalPrice = d.Price.GetValueOrDefault();
                        nd.Code       = d.Code;
                        if (existsD.Any(a => a.Barcode == d.Code))
                        {
                            nd.DishId = existsD.FirstOrDefault(a => a.Barcode == d.Code).Id;
                        }
                        else
                        {
                            nd.DishId = existsD.FirstOrDefault(a => a.Barcode == 17).Id;
                        }
                        _logger.Debug("d.Name; 1");
                        packs.Add(nd);
                    }

                    var res = AlohaFly.DBProvider.Client.CreateOrderToGo(ordNew);
                    if (!res.Success)
                    {
                        _logger.Debug($"ExportOrders error ");
                    }

                    //  var id = res.CreatedObjectId;

                    foreach (var d in packs)
                    {
                        d.OrderToGoId = res.CreatedObjectId;
                        OperationResult res2 = AlohaFly.DBProvider.Client.CreateDishPackageToGoOrder(d);
                        d.Id = res2.CreatedObjectId;
                    }

                    //ordNew.
                }
                catch (Exception e)
                {
                    _logger.Debug("Error ToGoOrder " + e.Message);
                }
            }
        }
Example #37
0
        static void Main(string[] args)
        {
            #region LoadChannel
            _channel   = ChannelD.GetChannel();
            _channelId = _channel._id;
            #endregion

            #region LoadStream
            _stream = StreamD.GetStreamByUser(_channelId);
            if (_stream.stream == null)
            {
                _streamUptime = new DateTime();
            }
            else
            {
                _streamUptime = _stream.stream.created_at.ToLocalTime();
            }

            #endregion

            _irc = new IrcClient("irc.twitch.tv", 6667, ChatBot.botName, _password, _channel.name);
            TwitchApi  api      = new TwitchApi();
            TmiApi     tmi      = new TmiApi();
            ViewerList chatters = new ViewerList();
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
            TwitchSocket twitchSocket = new TwitchSocket();
            ChatBot.init();

            #region LoadBroadCasterInfo
            _broadcaster = UserD.GetUser(_broadcasterName);
            #endregion

            _moderators.Add("gaelLevel");
            _moderators.Add("terror_seeds");
            _moderators.Add("nebulea");
            _moderators.Add("novaevermoon");

            #region LoadCommands
            List <CommandO> commands = new List <CommandO>();
            commands = CommandD.LoadCommands();
            LaunchTimer launchTimer = new LaunchTimer(_irc);
            foreach (CommandO command in commands)
            {
                if (command.type == "timed")
                {
                    launchTimer.createTimer(command);
                }
            }


            if (commands.Count != 0)
            {
                _commandsText = new StringBuilder();
                foreach (CommandO command in commands)
                {
                    if (command.userLevel == "everyone" && command.timer == 0)
                    {
                        _commandsText.Append("!" + command.keyword + ", ");
                    }
                }
                _commandsText.Length = _commandsText.Length - 2;
            }


            #endregion

            //chatters = tmi.getViewerList(_channel);

            //_viewers = tmi.getViewers(chatters);
            twitchSocket.ClientWebSocket = twitchSocket.WebSocketConnectAsync().Result;
            var testSocket = twitchSocket.WhisperSubscribeAsync(twitchSocket.ClientWebSocket, _broadcaster.users[0]._id);
            //ClientWebSocket webSocket = twitchSocket.WebSocketConnectAsync().Result;

            //var testWebSocket = twitchSocket.WhisperSubscribeAsync(twitchSocket.whisperWebSocket,_broadcaster.users[0]._id).Result;


            PingSender ping = new PingSender(_irc);
            ping.Start();

            while (true)
            {
                string   fullMessage  = _irc.ReadMessage();
                CommandO foundCommand = new CommandO();
                if (fullMessage.Contains("PRIVMSG"))
                {
                    _username = UserD.GetUsername(fullMessage);
                    string message = ChatBot.GetMessage(fullMessage);
                    _user = UserD.GetUser(_username);
                    UserD.InsertUser(_user);

                    bool isSubscriber = SubscriberD.IsSubscriber(_user.users[0]._id, _broadcaster.users[0]._id);


                    if (isSubscriber == false && _user.isPermit == false)
                    {
                        bool link = ChatBot.checkLink(message);
                        if (link == true)
                        {
                            _irc.WriteChatMessage(".timeout " + _username + " 15");
                            _irc.WriteChatMessage("Posting links is not allowed here for non-subs, if you think this link might interest me, just whisper me or one of my mods ♡");
                        }
                    }

                    char firstCharacter = message[0];

                    try
                    {
                        if (firstCharacter == '!')
                        {
                            string commandMessage = message.Substring(message.IndexOf('!') + 1);

                            bool kappamonCommand = CommandD.IsKappamonCommand(commandMessage);

                            if (!kappamonCommand)
                            {
                                if (commandMessage.Contains(" "))
                                {
                                    _command = commandMessage.Split(' ');
                                    if (_command.Length == 2)
                                    {
                                        commandMessage   = _command[0];
                                        _chatterUsername = _command[1];
                                    }
                                }
                                else
                                {
                                    _command[0] = commandMessage;
                                }

                                if (commands.Any(c => c.keyword == commandMessage))
                                {
                                    foundCommand = commands.Single(c => c.keyword == commandMessage);

                                    if (foundCommand.parameters != 0)
                                    {
                                        Type testType = typeof(Program);
                                        Dictionary <string, dynamic> newDic = new Dictionary <string, dynamic>();

                                        foreach (KeyValuePair <string, dynamic> dic in foundCommand.parameterList)
                                        {
                                            var fieldInfo = testType.GetField(dic.Key.ToString(), BindingFlags.Static | BindingFlags.Public).GetValue(testType);
                                            newDic.Add(dic.Key.ToString(), fieldInfo.ToString());
                                        }

                                        foundCommand.parameterList = newDic;
                                    }

                                    if (foundCommand.userLevel == "moderator" && !_moderators.Contains(_username))
                                    {
                                        _irc.WriteChatMessage("You are not allowed to use this command !");
                                    }
                                    else
                                    {
                                        DateTime date = DateTime.Now;

                                        if (foundCommand.startedTime.AddMilliseconds(foundCommand.cooldown) < DateTime.Now)

                                        {
                                            foundCommand.startedTime = DateTime.Now;
                                            if (foundCommand.keyword == "commands")
                                            {
                                                foundCommand.message += _commandsText;
                                            }

                                            switch (foundCommand.type)
                                            {
                                            case "request":
                                                string query = foundCommand.request;
                                                using (MySqlConnection mySqlConnection = new MySqlConnection("" /*connectionString*/))
                                                {
                                                    if (foundCommand.condition != "")
                                                    {
                                                        switch (foundCommand.condition)
                                                        {
                                                        case "userName":
                                                            foundCommand.request = string.Format(foundCommand.request, _username);
                                                            foundCommand.message = string.Format(foundCommand.message, _username);
                                                            break;
                                                        }
                                                    }

                                                    if (foundCommand.request.Contains("SELECT"))
                                                    {
                                                        Tuple <int, string> test = CommandD.ExecuteSelectCommand(foundCommand.request);
                                                        if (foundCommand.message.Contains("@"))
                                                        {
                                                            _irc.WriteChatMessage(foundCommand.message.Replace("@", test.Item1.ToString()));
                                                        }
                                                        else
                                                        {
                                                            _irc.WriteChatMessage(test.Item2);
                                                        }
                                                    }
                                                    else if (foundCommand.request.Contains("UPDATE"))
                                                    {
                                                        Tuple <int, string> result = CommandD.ExecuteUpdateCommand(foundCommand.request, foundCommand.message);
                                                        mySqlConnection.Close();
                                                        if (result.Item1 < 0)
                                                        {
                                                        }
                                                        else
                                                        {
                                                            _irc.WriteChatMessage(result.Item2);
                                                        }
                                                    }
                                                }
                                                break;

                                            case "regular":
                                                if (foundCommand.message.Contains("{"))
                                                {
                                                    _irc.WriteChatMessage(string.Format(foundCommand.message, _username));
                                                }
                                                else
                                                {
                                                    _irc.WriteChatMessage(foundCommand.message);
                                                }
                                                break;

                                            case "api":
                                                MethodInfo mInfo;
                                                Type       type = Assembly.Load("MoonBot_Data").GetType(foundCommand.assembly, false, true);
                                                mInfo = type.GetMethod(foundCommand.message);
                                                object[] parameters;

                                                if (foundCommand.parameters == 0)
                                                {
                                                    parameters = new object[] {};
                                                }
                                                else
                                                {
                                                    //Type testType = typeof(Program);
                                                    parameters = new object[] { foundCommand.parameterList };
                                                }

                                                object apiAnswer = mInfo.Invoke(null, parameters);
                                                _irc.WriteChatMessage(apiAnswer.ToString());
                                                break;

                                            case "moonlights":
                                                _irc.WriteChatMessage("Switching color to : " + foundCommand.keyword);
                                                _port.Open();
                                                _port.Write(foundCommand.message);
                                                _port.Close();
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            TimeSpan span = date - foundCommand.startedTime;
                                            int      ms   = (int)span.TotalMilliseconds;
                                            if (ms <= foundCommand.cooldown)
                                            {
                                                _irc.WriteChatMessage("This command is in cooldown right now, be patient !");
                                            }
                                            else
                                            {
                                                _irc.WriteChatMessage(foundCommand.message);
                                                foundCommand.startedTime = DateTime.Now;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    _irc.WriteChatMessage("This command does not exist, type !commands to know what commands are available");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        StringBuilder sb = new StringBuilder(DateTime.Now.ToString("dd-MM-yyyy") + " : " + ex.Message);
                        Console.WriteLine(sb);
                    }
                }
            }
        }
        public void Can_Delete_Product_Service()
        {
            //Arrange
            List <Product> products = new List <Product>()
            {
                new Product()
                {
                    Description = "P1", ProductId = 1, ProductName = "p1Name"
                },
                new Product()
                {
                    Description = "P2", ProductId = 2, ProductName = "p2Name"
                },
                new Product()
                {
                    Description = "P3", ProductId = 3, ProductName = "p3Name"
                },
                new Product()
                {
                    Description = "P4", ProductId = 4, ProductName = "p4Name"
                },
                new Product()
                {
                    Description = "P5", ProductId = 5, ProductName = "p5Name"
                },
                new Product()
                {
                    Description = "P6", ProductId = 6, ProductName = "p6Name"
                },
            };
            Mock <IGenericRepository <Product> > mock1 = new Mock <IGenericRepository <Product> >();

            //Here we are going to mock repository FindById Method
            mock1.Setup(m => m.FindById(It.IsAny <int>())).Returns((int i) => products.Single(x => x.ProductId == i));

            //Here we are going to mock repository Delete method
            mock1.Setup(m => m.Delete(It.IsAny <Product>())).Returns((Product target) =>
            {
                var original = products.FirstOrDefault(
                    q => q.ProductId == target.ProductId);

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

                products.Remove(target);

                return(true);
            });

            //Now we have our repository ready for property injection

            //Here we are going to mock our IUnitOfWork
            Mock <IUnitOfWork> mock = new Mock <IUnitOfWork>();

            //Here we are going to inject our repository to the property
            mock.Setup(m => m.ProductRepository).Returns(mock1.Object);


            //Now our UnitOfWork is ready to be injected to the service
            //Here we inject UnitOfWork to constractor of our service
            ProductService productService = new ProductService(mock.Object);


            //Act

            productService.DeleteProduct(6);
            var result = products.FirstOrDefault(t => t.ProductId == 6);

            //Assert
            Assert.IsNull(result);
            Assert.IsTrue(products.Count == 5);
        }
Example #39
0
 // GET: Employees/Details/5
 public ActionResult Details(int id)
 {
     return(View(employees.Single(x => x.Id == id)));
 }
Example #40
0
        public static void Executar()
        {
            var alunos = new List <Aluno>
            {
                new Aluno()
                {
                    Nome = "Pedro", Idade = 24, Nota = 8.0
                },
                new Aluno()
                {
                    Nome = "Andre", Idade = 21, Nota = 4.3
                },
                new Aluno()
                {
                    Nome = "Ana", Idade = 25, Nota = 9.5
                },
                new Aluno()
                {
                    Nome = "Jorge", Idade = 20, Nota = 8.5
                },
                new Aluno()
                {
                    Nome = "Ana", Idade = 21, Nota = 7.7
                },
                new Aluno()
                {
                    Nome = "Júlia", Idade = 22, Nota = 7.5
                },
                new Aluno()
                {
                    Nome = "Márcio", Idade = 18, Nota = 6.8
                },
            };

            var pedro = alunos.Single(aluno => aluno.Nome.Equals("Pedro"));

            Console.WriteLine($"{pedro.Nome} {pedro.Nota}");

            var fulano = alunos.SingleOrDefault(aluno => aluno.Nome.Equals("Fulano"));

            if (fulano == null)
            {
                Console.WriteLine("Aluno inexistente");
            }

            var ana = alunos.First(aluno => aluno.Nome.Equals("Ana"));

            Console.WriteLine($"{ana.Nome} {ana.Nota}");

            var sicrano = alunos.FirstOrDefault(aluno => aluno.Nota.Equals("Sicrano"));

            if (sicrano == null)
            {
                Console.WriteLine("Aluno inexistente");
            }

            var outraAna = alunos.LastOrDefault(aluno => aluno.Nome.Equals("Ana"));

            Console.WriteLine(outraAna.Nota);

            var exemploSkip = alunos.Skip(1).Take(3);

            foreach (var item in exemploSkip)
            {
                Console.WriteLine(item.Nome);
            }

            var maiorNota = alunos.Max(aluno => aluno.Nota);

            Console.WriteLine(maiorNota);

            var menorNota = alunos.Min(aluno => aluno.Nota);

            Console.WriteLine(menorNota);

            var somatorioNotas = alunos.Sum(aluno => aluno.Nota);

            Console.WriteLine(somatorioNotas);

            var mediaDosAprovados = alunos
                                    .Where(a => a.Nota >= 7.0)
                                    .Average(aluno => aluno.Nota);

            Console.WriteLine(mediaDosAprovados);
        }
        private string getStorePhoneNumber()
        {
            var phonenumberline = ReceiptLines.Single(g => g.text.ToLower().Contains("ph no") || g.text.ToLower().Contains("phone") || g.text.ToLower().Contains("tel no") || g.text.ToLower().Contains("ph")).text;

            return(new String(phonenumberline.Where(Char.IsDigit).ToArray()));
        }
Example #42
0
        static void Main(string[] args)
        {
            string[]       input    = Console.ReadLine().Split(';');
            List <Person>  persons  = new List <Person>();
            List <Product> products = new List <Product>();

            foreach (var p in input)
            {
                var input2 = p.Split('=');

                try
                {
                    persons.Add(new Person(input2[0], decimal.Parse(input2[1])));
                }
                catch (ArgumentException ex)
                {
                    Console.WriteLine(ex.Message);
                    return;
                }
            }

            input = Console.ReadLine().Split(';');

            foreach (var p in input)
            {
                var data = p.Split('=');

                try
                {
                    products.Add(new Product(data[0], decimal.Parse(data[1])));
                }
                catch (ArgumentException ex)
                {
                    Console.WriteLine(ex.Message);
                    return;
                }
            }

            string command;

            while ((command = Console.ReadLine()) != "END")
            {
                var data = command.Split();

                string personName  = data[0];
                string productName = data[1];

                var person  = persons.Single(p => p.Name == personName);
                var product = products.Single(p => p.Name == productName);

                if (!person.BuyProduct(product))
                {
                    Console.WriteLine($"{person.Name} can't afford {product.Name}");
                }
                else
                {
                    Console.WriteLine($"{person.Name} bought {product.Name}");
                }
            }

            foreach (var person in persons)
            {
                string productsBought;
                if (person.Products.Count == 0)
                {
                    productsBought = "Nothing bought";
                }
                else
                {
                    productsBought = ", " + person.Products.Select(p => p.Name);
                }
                Console.WriteLine($"{person.Name} - {productsBought}");
            }
            Console.ReadKey();
        }
Example #43
0
            public Matrix(string s)
            {
                for (int i = 0; i < 324; i++)
                {
                    columns.Add(new Node()
                    {
                        header = true
                    });
                }
                for (int i = 0; i < columns.Count; i++)
                {
                    var c = columns[i];
                    c.up    = c;
                    c.down  = c;
                    c.col   = c;
                    c.right = columns[i == columns.Count - 1 ? 0 : i + 1];
                    c.left  = columns[i == 0 ? columns.Count - 1 : i - 1];
                }
                for (int i = 0; i < 9; i++)         //the row
                {
                    for (int j = 0; j < 9; j++)     //the column
                    {
                        for (int k = 0; k < 9; k++) //the number being placed
                        {
                            Node n1 = new Node();
                            n1.up  = columns[j * 9 + i];
                            n1.col = columns[j * 9 + i];
                            n1.col.size++;
                            n1.down    = n1.up.down;
                            n1.down.up = n1;
                            n1.up.down = n1;

                            Node n2 = new Node();
                            n2.up  = columns[j * 9 + i + 81];
                            n2.col = columns[j * 9 + i + 81];
                            n2.col.size++;
                            n2.down    = n2.up.down;
                            n2.down.up = n2;
                            n2.up.down = n2;

                            Node n3 = new Node();
                            n3.up  = columns[j * 9 + i + 162];
                            n3.col = columns[j * 9 + i + 162];
                            n3.col.size++;
                            n3.down    = n3.up.down;
                            n3.down.up = n3;
                            n3.up.down = n3;

                            Node n4 = new Node();
                            n4.up  = columns[j * 9 + i + 243];
                            n4.col = columns[j * 9 + i + 243];
                            n4.col.size++;
                            n4.down    = n4.up.down;
                            n4.down.up = n4;
                            n4.up.down = n4;

                            n1.right = n2;
                            n2.right = n3;
                            n3.right = n4;
                            n4.right = n1;

                            n4.left = n3;
                            n3.left = n2;
                            n2.left = n1;
                            n1.left = n4;
                            Fill fill = new Fill()
                            {
                                number    = k,
                                row       = i,
                                col       = j,
                                box       = boxes[i, j],
                                firstNode = n1
                            };
                            fills.Add(fill);
                            n1.fill = fill;
                            n2.fill = fill;
                            n3.fill = fill;
                            n4.fill = fill;
                        }
                    }
                }
                head = columns[0];
                for (int j = 0; j < 9; j++)
                {
                    for (int i = 0; i < 9; i++)
                    {
                        if (s[i + j * 9] == '.')
                        {
                            continue;
                        }
                        int num  = int.Parse(s.Substring(i + j * 9, 1)) - 1;
                        var fill = fills.Single(q =>
                                                q.row == j &&
                                                q.col == i &&
                                                q.number == num
                                                );
                        var t = fill.firstNode;
                        set.Add(fill);
                        do
                        {
                            var t2 = t;
                            do
                            {
                                Cover(t2.col);
                                t2 = t2.right;
                            } while (t2 != t);
                            t = t.right;
                        } while (t != fill.firstNode);
                    }
                }
            }
Example #44
0
        static void Main(string[] args)
        {
            var departments = new List <Department>
            {
                new Department(1, "Бухгалтерия"),
                new Department(2, "Маркетинговый отдел"),
                new Department(3, "Финансовый отдел"),
                new Department(4, "Отдел управления поставками"),
                new Department(5, "Отдел технической поддержки"),
                new Department(6, "Отдел разработки программного обеспечения"),
                new Department(7, "Отдел тестирования")
            };

            var employees = new List <Employee>
            {
                new Employee(1, "Тураев", 6),
                new Employee(2, "Гаранин", 6),
                new Employee(3, "Ролдугин", 7),
                new Employee(4, "Климанов", 5),
                new Employee(5, "Жильцов", 1),
                new Employee(6, "Фонканц", 3),
                new Employee(7, "Болгова", 1),
                new Employee(8, "Журавлёва", 1),
                new Employee(9, "Евдокимов", 4),
                new Employee(10, "Нефёдова", 3),
                new Employee(11, "Щепицына", 7),
                new Employee(12, "Спицын", 5),
                new Employee(13, "Ерохин", 2),
                new Employee(14, "Никольский", 2)
            };

            Console.WriteLine("Выведите список всех сотрудников и отделов, отсортированный по отделам");

            var list1 =
                from employee in employees
                join department in departments on employee.DepartmentID equals department.ID
                orderby department.Name
                select new
            {
                employee.Surname,
                DepartmentName = department.Name
            };

            foreach (var item in list1)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine();
            Console.WriteLine("Выведите список всех сотрудников, у которых фамилия начинается с буквы «А»");

            var list2 =
                from employee in employees
                where employee.Surname[0] == 'А'
                select employee;

            foreach (var item in list2)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine();
            Console.WriteLine("Выведите список всех отделов и количество сотрудников в каждом отделе");

            var list3 =
                from department in departments
                join employee in employees on department.ID equals employee.DepartmentID into employeesOnDepartment
                select new
            {
                DepartmentID     = department.ID,
                DepartmentName   = department.Name,
                CountOfEmployees = employeesOnDepartment.Count()
            };


            foreach (var item in list3)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine();
            Console.WriteLine("Выведите список отделов, в которых у всех сотрудников фамилия начинается с буквы «А»");

            var list4 =
                from department in departments
                join employee in employees on department.ID equals employee.DepartmentID into employeesOnDepartment
                where employeesOnDepartment.All(employee => employee.Surname[0] == 'А')
                select department;

            foreach (var item in list4)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine();
            Console.WriteLine("Выведите список отделов, " +
                              "в которых хотя бы у одного сотрудника фамилия начинается с буквы «А»");


            var list5 =
                from department in departments
                join employee in employees on department.ID equals employee.DepartmentID into employeesOnDepartment
                where employeesOnDepartment.Any(employee => employee.Surname[0] == 'А')
                select department;

            foreach (var item in list5)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine();

            var departmentEmployees = new List <DepartmentEmployees>
            {
                new DepartmentEmployees(5, 3),
                new DepartmentEmployees(5, 1),
                new DepartmentEmployees(5, 3),
                new DepartmentEmployees(7, 5),
                new DepartmentEmployees(3, 2),
                new DepartmentEmployees(6, 7),
                new DepartmentEmployees(6, 7),
                new DepartmentEmployees(6, 7),
                new DepartmentEmployees(7, 5),
                new DepartmentEmployees(7, 2),
                new DepartmentEmployees(5, 1),
                new DepartmentEmployees(4, 6),
                new DepartmentEmployees(4, 5),
                new DepartmentEmployees(1, 4),
                new DepartmentEmployees(2, 3),
                new DepartmentEmployees(3, 3),
                new DepartmentEmployees(11, 2),
                new DepartmentEmployees(14, 5),
                new DepartmentEmployees(12, 4),
                new DepartmentEmployees(4, 7),
                new DepartmentEmployees(3, 5),
                new DepartmentEmployees(9, 2),
                new DepartmentEmployees(9, 4),
                new DepartmentEmployees(10, 6),
                new DepartmentEmployees(12, 4),
                new DepartmentEmployees(7, 2),
                new DepartmentEmployees(1, 1),
                new DepartmentEmployees(2, 1),
                new DepartmentEmployees(12, 5)
            };

            Console.WriteLine("Выведите список всех отделов и список сотрудников в каждом отделе");

            var list6 =
                from departmentEmployee in departmentEmployees
                group departmentEmployees by departmentEmployee.DepartmentID into deps
                select new
            {
                Department = departments.Single(dep => dep.ID == deps.Key),
                Employees  = string.Join(", ", employees.FindAll(employee => employee.DepartmentID == deps.Key))
            };

            foreach (var item in list6)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine();
            Console.WriteLine("Выведите список всех отделов и количество сотрудников в каждом отделе");

            var list7 =
                from departmentEmployee in departmentEmployees
                group departmentEmployees by departmentEmployee.DepartmentID into deps
                select new
            {
                Department     = departments.Single(dep => dep.ID == deps.Key),
                EmployeesCount = employees.FindAll(employee => employee.DepartmentID == deps.Key).Count
            };

            foreach (var item in list7)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
Example #45
0
    public string AsXml(List <SubstitutionArrayEntry> substitutionEntries, long parentOffset)
    {
        var sb = string.Empty;

        sb += ($"<{Name.Value}");

        var attrStrings = new List <string>();

        foreach (var attribute in Attributes)
        {
            var attrVal = attribute.AsXml(substitutionEntries, parentOffset);
            if (attrVal.Length > 0)
            {
                attrStrings.Add(attrVal);
            }
        }

        if (attrStrings.Count > 0)
        //at least one attribute with a value
        {
            sb += (" " + string.Join(" ", attrStrings));
        }

        foreach (var node in Nodes)
        {
            if (node is EndElementTag)
            {
                sb += ($"</{Name.Value}>");
            }
            else if (node is CloseEmptyElementTag)
            {
                sb += (node.AsXml(substitutionEntries, parentOffset));
            }
            else if (node is CloseStartElementTag)
            {
                sb += (node.AsXml(substitutionEntries, parentOffset));
            }
            else
            {
                if (node is OptionalSubstitution || node is NormalSubstitution)
                {
                    if (node is OptionalSubstitution os)
                    {
                        if (os.ValueType == TagBuilder.ValueType.BinXmlType)
                        {
                            var osData = substitutionEntries.Single(t => t.Position == os.SubstitutionId);
                            var ms     = new MemoryStream(osData.DataBytes);
                            var br     = new BinaryReader(ms);

                            while (br.BaseStream.Position < br.BaseStream.Length)
                            {
                                var nextTag = TagBuilder.BuildTag(parentOffset, br, _chunk);

                                if (nextTag is TemplateInstance te)
                                {
                                    sb += (te.AsXml(te.SubstitutionEntries, parentOffset));
                                }

                                if (nextTag is EndOfBXmlStream)
                                //nothing left to do, so exit
                                {
                                    break;
                                }
                            }
                        }
                        else
                        {
                            //optional sub
                            var escapedo = new XText(node.AsXml(substitutionEntries, parentOffset)).ToString();
                            sb += (escapedo);
                        }
                    }
                    else
                    {
                        //normal sub
                        var escapedn = new XText(node.AsXml(substitutionEntries, parentOffset)).ToString();
                        sb += (escapedn);
                        //sb.Append(node.AsXml(substitutionEntries,parentOffset));
                    }
                }
                else
                {
                    sb += (node.AsXml(substitutionEntries, parentOffset));
                }
            }
        }


        return(sb);
    }
Example #46
0
        /// <summary>
        /// Selects one item from the database that corresponds to the specified Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T Select(int id)
        {
            ThrowExceptionIfNotExists(id);

            return(data.Single(x => x.Id == id));
        }
 public Coffee Get(int id)
 {
     return(coffees.Single(x => x.Id == id));
 }
Example #48
0
        public virtual bool IsCleanInFront(IHardwareRobot hardwareRobot)
        {
            var positionInFrontOfRobot = directionMapper.GetPositionFacingRobot(hardwareRobot);

            return(cells.Single(cell => cell.IsAtPosition(positionInFrontOfRobot)).IsClean);
        }
 public JoinRequestStatus GetById(int joinRequestStatusId)
 {
     return(JoinRequestStatuses.Single(jrs => jrs.Id == joinRequestStatusId));
 }
Example #50
0
        public bool nondrantSearch(List <List <HashSet <int> > > grid)
        {
            var foundValue = false;

            for (var i = 0; i < 3; i++)
            {
                for (var j = 0; j < 3; j++)
                {
                    var nondrantNeeds = new List <int>()
                    {
                        1, 2, 3, 4, 5, 6, 7, 8, 9
                    };

                    //Get needed values
                    for (var x = i * 3; x < i * 3 + 3; x++)
                    {
                        for (var y = j * 3; y < j * 3 + 3; y++)
                        {
                            if (grid[x][y].Count == 1)
                            {
                                nondrantNeeds.Remove(grid[x][y].Single());
                            }
                        }
                    }

                    //See where we could put needed values
                    foreach (var need in nondrantNeeds)
                    {
                        var placesWeCouldPutNeededValue = new List <Tuple <int, int> >();

                        for (var x = i * 3; x < i * 3 + 3; x++)
                        {
                            for (var y = j * 3; y < j * 3 + 3; y++)
                            {
                                if (grid[x][y].Count != 1 && !rowContains(grid[x], need) && !columnContains(grid, y, need) && !nondrantContains(grid, x, y, need) && grid[x][y].Contains(need))
                                {
                                    placesWeCouldPutNeededValue.Add(new Tuple <int, int>(x, y));
                                }
                            }
                        }

                        if (placesWeCouldPutNeededValue.Count == 1)
                        {
                            grid[placesWeCouldPutNeededValue.Single().Item1][placesWeCouldPutNeededValue.Single().Item2].Clear();
                            grid[placesWeCouldPutNeededValue.Single().Item1][placesWeCouldPutNeededValue.Single().Item2].Add(need);

                            foundValue = true;
                        }
                        else if (placesWeCouldPutNeededValue.Count == 2 || placesWeCouldPutNeededValue.Count == 3)
                        {
                            var firstX = placesWeCouldPutNeededValue.First().Item1;
                            var firstY = placesWeCouldPutNeededValue.First().Item2;

                            if (placesWeCouldPutNeededValue.All(p => p.Item1 == firstX))
                            {
                                removePointingRow(grid[firstX], j, need);
                            }
                            else if (placesWeCouldPutNeededValue.All(p => p.Item2 == firstY))
                            {
                                var pivotRow = pivotColumn(grid, firstY);
                                removePointingRow(pivotRow, i, need);
                            }
                        }
                    }
                }
            }

            return(foundValue);
        }
Example #51
0
 private void OnCompanyDeleted(CompanyDeleted companyDeleted)
 {
     _companies.Remove(_companies.Single(c => c.Id == companyDeleted.CompanyId));
 }
Example #52
0
        public static async Task Run(
            [EventHubTrigger("table-update", Connection = "eventHubConnection")] EventData[] events,
            [CosmosDB(
                 databaseName: "Temenos",
                 collectionName: "Events",
                 ConnectionStringSetting = "CosmosDBConnection")]
            IAsyncCollector <JObject> eventsOut,
            ILogger log)
        {
            log.LogInformation($"ProcessAvroEvent triggered with {events.Count()} events");

            var exceptions = new List <Exception>();

            foreach (EventData eventData in events)
            {
                try
                {
                    // convert messageBody of this event to a stream
                    MemoryStream stream = new MemoryStream(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);

                    // skip the first 2 bytes
                    stream.Position = 3;

                    // decode the stream and get the schema number
                    BinaryDecoder decoder      = new BinaryDecoder(stream);
                    var           magicCode    = (decoder.ReadBoolean() == false);
                    var           schemaNumber = decoder.ReadLong();

                    // get the appropriate schema
                    Schema schema = null;
                    switch (schemaNumber)
                    {
                    case 23:
                        schema = Schema.Parse(File.ReadAllText(@"SerializationID-46-CUSTOMER.avsc"));
                        break;

                    case -21:
                        schema = Schema.Parse(File.ReadAllText(@"SerializationID-41-DE_ADDRESS.avsc"));
                        break;

                    default:
                        throw new Exception("Unknown schema nuumber: " + schemaNumber);
                    }

                    // read the avro message using the identified schema
                    var           reader = new DefaultReader(schema, schema);
                    GenericRecord record = reader.Read(null, schema, schema, decoder) as GenericRecord;

                    // convert to JSON and return
                    JObject outputData = ConvertToJson(record);
                    eventsOut.AddAsync(outputData).Wait();

                    // Replace these two lines with your processing logic.
                    await Task.Yield();
                }
                catch (Exception e)
                {
                    // We need to keep processing the rest of the batch - capture this exception and continue.
                    // TODO: consider capturing details of the message that failed processing so it can be processed again later.
                    exceptions.Add(e);
                }
            }

            // Once processing of the batch is complete, if any messages in the batch failed processing throw an exception so that there is a record of the failure.

            if (exceptions.Count > 1)
            {
                throw new AggregateException(exceptions);
            }

            if (exceptions.Count == 1)
            {
                throw exceptions.Single();
            }
        }
Example #53
0
 public MethodResult Get(string methodName)
 {
     return(Values.Single(x => x.MethodName == methodName));
 }
Example #54
0
        protected void imgGenMultipleEnglish_Click(object sender, EventArgs e)
        {
            //multiple invite (clicking on the Generate Multiple Invitations button)
            ArrayList prog = new ArrayList();
            //GridViewCommandColumn ShowSelectCheckbox="true" display a checkbox for selection
            // gvCardiologists.GetSelectedFieldValues("UniqueID") get all selected values
            //once you define a commandcolumn you must define KeyFieldName, so that a selection can be uniquely identified by KeyFieldName
            //Getting all selected values in Grid, they are identified by the physicianID as set in KeyFieldName
            List <object> keyValues = gvCardiologists.GetSelectedFieldValues("PhysicianID");
            List <object> tmpList   = new List <object>();

            if (keyValues.Count == 0)
            {
                return;
            }

            List <Invitee> lst = gvCardiologists.DataSource as List <Invitee>;

            foreach (object key in keyValues)
            {
                int docID = Int32.Parse(key.ToString());
                var doc   = lst.Single(i => i.PhysicianID == docID);

                if (doc.PhysicianType != Enums.PhysicianType.CS)
                {
                    tmpList.Add(key);
                }
            }

            keyValues.Clear();
            keyValues.AddRange(tmpList);

            if (keyValues.Count == 0)
            {
                return;
            }

            string idlst = "";

            foreach (object key in keyValues)
            {
                idlst += key + ",";
            }
            idlst = idlst.Substring(0, idlst.Length - 1);

            foreach (object key in keyValues)
            {
                //UpdateInvitationSentDate(Int32.Parse(key.ToString()), false, user.Roles.Contains(Constants.ADMIN_ROLE));
                UpdateInvitationSentDate(Int32.Parse(key.ToString()), false, true);
            }

            //string link = "window.open('GenerateInvitation.aspx?physlst=" + idlst;
            //link += "');";

            string link = string.Format("window.open('GenerateInvitation.aspx?physlst={0}&{1}={2}');", idlst.ToString(), Constants.ISFRENCH, 0);


            showscript(link);


            gvCardiologists.Selection.UnselectAll();

            if (provinceID == -1)
            {
                LoadData(isPCP);
            }
            else
            {
                LoadData(provinceID, isPCP);
            }
        }
Example #55
0
        public ThresholdResult Get(double threshold)
        {
            string thresholdStr = threshold.ToString("0.0");

            return(Values.Single(x => x.Threshold == thresholdStr));
        }
Example #56
0
        protected override void Seed(BabyStore.DAL.StoreContext context)
        {
            var categories = new List <Category>
            {
                new Category {
                    Name = "Clothes"
                },
                new Category {
                    Name = "Play and Toys"
                },
                new Category {
                    Name = "Feeding"
                },
                new Category {
                    Name = "Medicine"
                },
                new Category {
                    Name = "Travel"
                },
                new Category {
                    Name = "Sleeping"
                }
            };

            categories.ForEach(c => context.Categories.AddOrUpdate(p => p.Name, c));
            context.SaveChanges();

            var products = new List <Product>
            {
                new Product {
                    Name = "Sleep Suit", Description = "For sleeping or general wear", Price = 4.99M, CategoryID = categories.Single(c => c.Name == "Clothes").ID
                },
                new Product {
                    Name = "Vest", Description = "For sleeping or general wear", Price = 2.99M, CategoryID = categories.Single(c => c.Name == "Clothes").ID
                },
                new Product {
                    Name = "Orange and Yellow Lion", Description = "Makes a squeaking noise", Price = 1.99M, CategoryID = categories.Single(c => c.Name == "Play and Toys").ID
                },
                new Product {
                    Name = "Blue Rabbit", Description = "Baby comforter", Price = 2.99M, CategoryID = categories.Single(c => c.Name == "Play and Toys").ID
                },
                new Product {
                    Name = "3 Pack of Bottles", Description = "For a leak free drink everytime", Price = 24.99M, CategoryID = categories.Single(c => c.Name == "Feeding").ID
                },
                new Product {
                    Name = "3 Pack of Bibs", Description = "Keep your baby dry when feeding", Price = 8.99M, CategoryID = categories.Single(c => c.Name == "Feeding").ID
                },
                new Product {
                    Name = "Powdered Baby Milk", Description = "Nutritional and Tasty", Price = 9.99M, CategoryID = categories.Single(c => c.Name == "Feeding").ID
                },
                new Product {
                    Name = "Pack of 70 Disposable Nappies", Description = "Dry and secure nappies with snug fit", Price = 19.99M, CategoryID = categories.Single(c => c.Name == "Feeding").ID
                },
                new Product {
                    Name = "Colic Medicine", Description = "For helping with baby colic pains", Price = 4.99M, CategoryID = categories.Single(c => c.Name == "Medicine").ID
                },
                new Product {
                    Name = "Reflux Medicine", Description = "Helps to prevent milk regurgitation and sickness", Price = 4.99M, CategoryID = categories.Single(c => c.Name == "Medicine").ID
                },
                new Product {
                    Name = "Black Pram and Pushchair System", Description = "Convert from pram to pushchair, with raincover", Price = 299.99M, CategoryID = categories.Single(c => c.Name == "Travel").ID
                },
                new Product {
                    Name = "Car Seat", Description = "For safe car travel", Price = 49.99M, CategoryID = categories.Single(c => c.Name == "Travel").ID
                },
                new Product {
                    Name = "Moses Basket", Description = "Plastic moses basket", Price = 75.99M, CategoryID = categories.Single(c => c.Name == "Sleeping").ID
                },
                new Product {
                    Name = "Crib", Description = "Wooden crib", Price = 35.99M, CategoryID = categories.Single(c => c.Name == "Sleeping").ID
                },
                new Product {
                    Name = "Cot Bed", Description = "Converts from cot into bed for older children", Price = 149.99M, CategoryID = categories.Single(c => c.Name == "Sleeping").ID
                },
                new Product {
                    Name = "Circus Crib Bale", Description = "Contains sheet, duvet and bumper", Price = 29.99M, CategoryID = categories.Single(c => c.Name == "Sleeping").ID
                },
                new Product {
                    Name = "Loved Crib Bale", Description = "Contains sheet, duvet and bumper", Price = 35.99M, CategoryID = categories.Single(c => c.Name == "Sleeping").ID
                }
            };

            products.ForEach(c => context.Products.AddOrUpdate(p => p.Name, c));
            context.SaveChanges();
        }
Example #57
0
 //
 // 8) Complete the method FindTheNeedle that accepts a list of
 //    strings and returns the one string that contains the word
 //    `needle`.
 //
 public static string FindTheNeedle(List<string> sentences)
 {
     return sentences.Single(sentence => sentence.Contains("needle"));
 }
Example #58
0
 public ProjectResult Get(string projectName)
 {
     return(Values.Single(x => x.ProjectName == projectName));
 }
Example #59
0
        protected override void Seed(ContosoUniversity.DAL.SchoolContext context)
        {
            //构建学生数据
            var students = new List <Student>
            {
                new Student {
                    FirstMidName   = "Carson", LastName = "Alexander",
                    EnrollmentDate = DateTime.Parse("2010-09-01")
                },
                new Student {
                    FirstMidName   = "Meredith", LastName = "Alonso",
                    EnrollmentDate = DateTime.Parse("2012-09-01")
                },
                new Student {
                    FirstMidName   = "Arturo", LastName = "Anand",
                    EnrollmentDate = DateTime.Parse("2013-09-01")
                },
                new Student {
                    FirstMidName   = "Gytis", LastName = "Barzdukas",
                    EnrollmentDate = DateTime.Parse("2012-09-01")
                },
                new Student {
                    FirstMidName   = "Yan", LastName = "Li",
                    EnrollmentDate = DateTime.Parse("2012-09-01")
                },
                new Student {
                    FirstMidName   = "Peggy", LastName = "Justice",
                    EnrollmentDate = DateTime.Parse("2011-09-01")
                },
                new Student {
                    FirstMidName   = "Laura", LastName = "Norman",
                    EnrollmentDate = DateTime.Parse("2013-09-01")
                },
                new Student {
                    FirstMidName   = "Nino", LastName = "Olivetto",
                    EnrollmentDate = DateTime.Parse("2005-08-11")
                }
            };

            students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, s));
            context.SaveChanges();
            //构建课程数据
            var courses = new List <Course>
            {
                new Course {
                    CourseID = 1050, Title = "Chemistry", Credits = 3,
                },
                new Course {
                    CourseID = 4022, Title = "Microeconomics", Credits = 3,
                },
                new Course {
                    CourseID = 4041, Title = "Macroeconomics", Credits = 3,
                },
                new Course {
                    CourseID = 1045, Title = "Calculus", Credits = 4,
                },
                new Course {
                    CourseID = 3141, Title = "Trigonometry", Credits = 4,
                },
                new Course {
                    CourseID = 2021, Title = "Composition", Credits = 3,
                },
                new Course {
                    CourseID = 2042, Title = "Literature", Credits = 4,
                }
            };

            courses.ForEach(s => context.Courses.AddOrUpdate(p => p.Title, s));
            context.SaveChanges();

            var enrollments = new List <Enrollment>
            {
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alexander").ID,
                    CourseID  = courses.Single(c => c.Title == "Chemistry").CourseID,
                    Grade     = Grade.A
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alexander").ID,
                    CourseID  = courses.Single(c => c.Title == "Microeconomics").CourseID,
                    Grade     = Grade.C
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alexander").ID,
                    CourseID  = courses.Single(c => c.Title == "Macroeconomics").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alonso").ID,
                    CourseID  = courses.Single(c => c.Title == "Calculus").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alonso").ID,
                    CourseID  = courses.Single(c => c.Title == "Trigonometry").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Alonso").ID,
                    CourseID  = courses.Single(c => c.Title == "Composition").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Anand").ID,
                    CourseID  = courses.Single(c => c.Title == "Chemistry").CourseID
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Anand").ID,
                    CourseID  = courses.Single(c => c.Title == "Microeconomics").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Barzdukas").ID,
                    CourseID  = courses.Single(c => c.Title == "Chemistry").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Li").ID,
                    CourseID  = courses.Single(c => c.Title == "Composition").CourseID,
                    Grade     = Grade.B
                },
                new Enrollment {
                    StudentID = students.Single(s => s.LastName == "Justice").ID,
                    CourseID  = courses.Single(c => c.Title == "Literature").CourseID,
                    Grade     = Grade.B
                }
            };

            foreach (Enrollment e in enrollments)
            {
                var enrollmentInDataBase = context.Enrollments.Where(
                    s =>
                    s.Student.ID == e.StudentID &&
                    s.Course.CourseID == e.CourseID).SingleOrDefault();
                if (enrollmentInDataBase == null)
                {
                    context.Enrollments.Add(e);
                }
            }
            context.SaveChanges();
        }
 /// <summary>
 /// Retrieves the item from the store with the given identifier.
 /// </summary>
 /// <returns>
 /// A task that represents the asynchronous operation.
 /// The task result contains the retrieved item.
 /// </returns>
 /// <param name="id">The identifier of the item to retrieve.</param>
 public Task <T> GetItemAsync(string id)
 {
     return(Task <T> .FromResult(_items.Single(item => item.Id == id)));
 }