Example #1
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;
            }
        }
        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
        //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;
        }
        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));
        }
        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;
        }
        /// <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;
        }
        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;
        }
        /// <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 #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;
        }
		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."
        }
        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 #16
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;
        }
Example #17
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();

            }
        }
 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 #19
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);
        }
Example #20
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 #21
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 #22
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);
        }
Example #23
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 #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 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 #26
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 #29
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 #30
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;
 }