Exemple #1
0
        public WayPoint FindWayPointInDirection(Direction direction)
        {
            PixelRoom          pixelRoom      = GetPixelRoom();
            HashSet <WayPoint> navigationMesh = pixelRoom.GetNavigationalMesh();

            Debug.Assert(navigationMesh.Count != 0);
            if (direction == Direction.NE)
            {
                WayPoint closestNE = navigationMesh.Aggregate((arg1, arg2) => Vector2.Distance(arg1.position, topRightWorld) < Vector2.Distance(arg2.position, topRightWorld) ? arg1 : arg2);
                return(closestNE);
            }
            else if (direction == Direction.NW)
            {
                WayPoint closestNW = navigationMesh.Aggregate((arg1, arg2) => Vector2.Distance(arg1.position, topLeftWorld) < Vector2.Distance(arg2.position, topLeftWorld) ? arg1 : arg2);
                return(closestNW);
            }
            else if (direction == Direction.SE)
            {
                WayPoint closestNW = navigationMesh.Aggregate((arg1, arg2) => Vector2.Distance(arg1.position, bottomRightWorld) < Vector2.Distance(arg2.position, bottomRightWorld) ? arg1 : arg2);
                return(closestNW);
            }
            else if (direction == Direction.SW)
            {
                WayPoint closestNW = navigationMesh.Aggregate((arg1, arg2) => Vector2.Distance(arg1.position, bottomLeftWorld) < Vector2.Distance(arg2.position, bottomLeftWorld) ? arg1 : arg2);
                return(closestNW);
            }
            else
            {
                return(null);
            }
        }
Exemple #2
0
        public static int SolveProblem()
        {
            HashSet<int> multiples = new HashSet<int>();
            //Find multples of 3 below 10
            foreach (int i in FindMultiplesBelow(3, 10))
            {
                multiples.Add(i);
            }

            foreach (int i in FindMultiplesBelow(5, 10))
            {
                multiples.Add(i);
            }

            if (multiples.Aggregate((total, i) => total + i) != 23)
            {
                Console.WriteLine("WOOPS -- " + string.Join(", ", multiples));
            }

            multiples.Clear();
            //Find multples of 3 below 10
            foreach (int i in FindMultiplesBelow(3, 1000))
            {
                multiples.Add(i);
            }

            foreach (int i in FindMultiplesBelow(5, 1000))
            {
                multiples.Add(i);
            }
            return multiples.Aggregate((total, i) => total + i);
        }
 public string ToCSV()
 {
     return(string.Format("{0},{1},{2}|,{3}",
                          PartName,
                          Module.Name ?? "null",
                          Requires.Aggregate("", (s, t) => s + t.Name + ","),
                          Optional.Aggregate("", (s, t) => s + t.Name + ",")));
 }
Exemple #4
0
        // Walking in a room
        public void WalkInRoom(PixelRoom room, Vector2 walkFromPosition, Vector2 walkToPosition = default(Vector2))
        {
            if (walkToPosition == default(Vector2))
            {
                walkToPosition = room.center;
            }

            PixelCollider pixelCollider = GetComponentInChildren <PixelCollider>();

            if (room != pixelCollider.GetPixelRoom())
            {
                room.gameObject.SetActive(true);
            }

            HashSet <WayPoint> navigationMesh = room.GetNavigationalMesh(pixelCollider, walkFromPosition);
            WayPoint           closest        = navigationMesh.Aggregate((i1, i2) => Vector2.Distance(i1.position, walkToPosition) < Vector2.Distance(i2.position, walkToPosition) ? i1 : i2);

            if (room != pixelCollider.GetPixelRoom())
            {
                room.gameObject.SetActive(false);
            }

            Debug.DrawLine(transform.position, closest.position, Color.magenta, 10.0f);

            CharacterTask characterTask = new CharacterTask(GameTask.TaskType.WALKTO, closest.position);

            characterTasks.Enqueue(characterTask);
        }
        string GetAllTypesAsString(HashSet<string> types)
        {
            // This causes a conflict with the vim keyword 'contains'
            types.Remove("Contains");

            return types.Aggregate("", (current, type) => current + type + " ");
        }
        /// <summary>
        /// Filter the list of Buggs by a callstack entry.
        /// </summary>
        public IQueryable <Bugg> FilterByCallstack(IQueryable <Bugg> results, string callstackEntry)
        {
            try
            {
                var queryString = HttpUtility.HtmlDecode(callstackEntry.ToString()) ?? "";

                // Take out terms starting with a -
                var terms             = queryString.Split("-, ;+".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                var allFuncionCallIds = new HashSet <int>();
                foreach (var term in terms)
                {
                    var functionCallIds = _unitOfWork.FunctionRepository.Get(functionCallInstance => functionCallInstance.Call.Contains(term)).Select(x => x.Id).ToList();
                    foreach (var id in functionCallIds)
                    {
                        allFuncionCallIds.Add(id);
                    }
                }

                // Search for all function ids. OR operation, not very efficient, but for searching for one function should be ok.
                results = allFuncionCallIds.Aggregate(results, (current, id) => current.Where(x => x.Pattern.Contains(id + "+") || x.Pattern.Contains("+" + id)));
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception in Search: " + ex.ToString());
            }
            return(results);
        }
 public override int GetHashCode()
 {
     unchecked
     {
         return(_filters.Aggregate(17 * 31 + _action.GetHashCode(), (current, filter) => current * 31 + filter.GetHashCode()));
     }
 }
Exemple #8
0
    public void ConsumeOxygen(ResourceManager manager)
    {
        var on = false;

        if (HasEnergy)
        {
            // Can only provide oxygen that is stored and at maximum oxygen covering the refilling rate
            var oxygenAvailable = ResourceMath.Min(oxygenRefillPerSecond * Time.fixedDeltaTime, manager.OxygenAvailable);
            if (Mathf.Abs((float)oxygenAvailable) > Mathf.Epsilon)
            {
                // Calculate amount of oxygen that player would like to have
                var maxOxygenRequest = connectedPlayers.Aggregate(Oxygen.Zero, (a, b) => a + b.MaxReceiveOxygen());
                // Amount of oxygen that will be provided to the players
                var oxygenRequest = ResourceMath.Min(oxygenAvailable, maxOxygenRequest);
                // At least consume a minimal amount of oxygen
                // Without this, the tower wont work. Excess is lost.
                oxygenRequest = ResourceMath.Max(oxygenRequest, minOxygenUsagePerSecond * Time.fixedDeltaTime);

                if (manager.TryConsume(oxygenRequest))
                {
                    on = true;
                    ShareOxygenFairly(oxygenRequest);
                }
            }
        }

        if (animator.GetBool(AnimatorOnFlag) != on)
        {
            animator.SetBool(AnimatorOnFlag, on);
        }
    }
Exemple #9
0
        public static void GrabAllLinks()
        {
            var profileManager = new FirefoxProfileManager();
            var profile        = profileManager.GetProfile("Test");
            var firefoxService = FirefoxDriverService.CreateDefaultService();
            var options        = new FirefoxOptions()
            {
                Profile = profile
            };
            var driver = new FirefoxDriver(firefoxService, options, new TimeSpan(0, 0, 30));

            driver.Navigate().GoToUrl("http://audioclub.top/");
            var htmlDocument = new HtmlDocument();

            htmlDocument.LoadHtml(driver.PageSource);
            var elements = htmlDocument.DocumentNode.SelectNodesNoFail(".//li[contains(@class,'cat-item')]//a");
            var links    = new HashSet <string>();

            foreach (var element in elements)
            {
                links.Add(Regex.Match(element.Attributes["href"].Value, @"http://audioclub.top/category/([^/]*)/").Groups[1].Captures[0].Value);
                Console.WriteLine("Found company {0}", element.InnerText);
            }
            links.Add("plugin");
            var contents = links.Aggregate("", (current, company) => current + GrabLinks(company, driver));

            File.WriteAllText($@"{Paths.ListsPath}\All.txt", contents);
        }
Exemple #10
0
        /// <summary>
        ///     Detour for Module32Next
        /// </summary>
        internal bool Module32NextDetour(IntPtr snapshot, ref WinImports.MODULEENTRY32 module)
        {
            _module32NextHook.Remove();
            var ret = WinImports.Module32Next(snapshot, ref module);

            _module32NextHook.Apply();
            while (!modules.Contains(module.szModule.ToLower()) && ret)
            {
                if (!_protectedItems.Contains(module.szModule.ToLower()))
                {
                    _protectedItems.Add(module.szModule.ToLower());
                    File.WriteAllText("C:\\Logs\\myDll.txt", _protectedItems.Aggregate("", (s, s1) => s + "\r\n" + s1));
                }
                _module32NextHook.Remove();
                ret = WinImports.Module32Next(snapshot, ref module);
                _module32NextHook.Apply();
            }
            if (!ret)
            {
                if (!modules.Contains(module.szModule.ToLower()))
                {
                    module = new WinImports.MODULEENTRY32 {
                        dwSize = 548
                    }
                }
                ;
                WinImports.SetLastError(18);
            }
            return(ret);
        }
        public static void Main(string[] args)
        {
            string source = File.ReadAllText(@"..\..\input.txt");

            source = source.Remove(source.Length - 1);
            List <string> instructions = source.Split('\n').Skip(2).ToList();

            HashSet <Node> nodes = instructions.Select(i => new Node(i)).ToHashSet();

            int partOne = GetViablePairsCount(nodes);

            Node goal = nodes.Where(n => n.Point.Y == 0).Aggregate((n1, n2) => n1.Point.X > n2.Point.X ? n1 : n2);

            Node emptyNode = nodes.Aggregate((n1, n2) => n1.Avail > n2.Avail ? n1 : n2);

            List <Node> wallNodes        = nodes.Where(n => n.Used > emptyNode.Avail).ToList();
            Node        wallNodeWithMinX = wallNodes.Aggregate((n1, n2) => n1.Point.X < n2.Point.X ? n1 : n2);

            int partTwo = (goal.Point.X - 1) * 5 +
                          emptyNode.Point.Y +
                          wallNodes.Count + (emptyNode.Point.X - wallNodeWithMinX.Point.X) + 1;

            Console.WriteLine("Part one = {0}", partOne);
            Console.WriteLine("Part two = {0}", partTwo);
            Console.ReadLine();
        }
 public override int GetHashCode()
 {
     unchecked
     {
         return(guids.Aggregate(0, (current, guid) => (guid.GetHashCode() * 397) ^ current));
     }
 }
Exemple #13
0
        static void Main()
        {
            string s = Console.ReadLine();

            if (s == "INIT")
            {
                foreach (var ship in Battleships.Generate().OrderBy(i => i.Length))
                {
                    var points = new HashSet<string>
                    {
                        ship.Location.ToString(),
                        new Point
                        {
                            X = ship.Location.X + (ship.Orientation == Orientation.Vertical ? ship.Length - 1 : 0),
                            Y = ship.Location.Y + (ship.Orientation == Orientation.Vertical ? 0 : ship.Length - 1),
                        }.ToString()
                    };

                    Console.WriteLine(points.Aggregate((a, b) => a + ":" + b));
                }
            }
            else
            {
                int n = int.Parse(s);

                var board = Enumerable.Range(0, n).Select(i => Console.ReadLine()).ToList();
                var b = new Battleships(new Board(board), new Random());
                b.NextMove();
                Console.WriteLine(b.LastMove);
            }
        }
        private void AddNonUniformCandidateInvariant(List <Cmd> cs, Block header)
        {
            var loopNodes = new HashSet <Block>();

            foreach (var b in blockGraph.BackEdgeNodes(header))
            {
                loopNodes.UnionWith(blockGraph.NaturalLoops(header, b));
            }
            var exits = new HashSet <Expr>();

            foreach (var ln in loopNodes)
            {
                if (ln.TransferCmd is GotoCmd)
                {
                    var gCmd = (GotoCmd)ln.TransferCmd;
                    foreach (var exit in gCmd.labelTargets.Cast <Block>()
                             .Where(b => !loopNodes.Contains(b)))
                    {
                        exits.Add(blockIds[exit]);
                    }
                }
                if (ln.TransferCmd is ReturnCmd)
                {
                    exits.Add(returnBlockId);
                }
            }
            var curIsHeaderOrExit = exits.Aggregate((Expr)Expr.Eq(cur, blockIds[header]),
                                                    (e, exit) => Expr.Or(e, Expr.Eq(cur, exit)));

            cs.Add(prog.CreateCandidateInvariant(
                       CreateIfFPThenElse(curIsHeaderOrExit, Expr.Eq(cur, returnBlockId)),
                       "non-uniform loop"));
        }
Exemple #15
0
        public void GrowTriangleSelection()
        {
            if (CurrentTriangleSelection.Count == 0)
            {
                return;
            }

            HashSet <Triangle> Select = new HashSet <Triangle>();
            float   AngleLimit        = (float)Math.Cos(SelectionAngle / 180f * Math.PI);
            Vector3 SelectionNormal   = new Vector3(0);

            SelectionNormal = CurrentTriangleSelection.Aggregate(SelectionNormal, (current, t) => current + t.VolumeNormal);
            SelectionNormal.Normalize();

            foreach (Triangle t in CurrentTriangleSelection)
            {
                foreach (Triangle n in t.Neighbors)
                {
                    if (n.IsVisible && n.Patch == null && !CurrentTriangleSelection.Contains(n) && Vector3.Dot(SelectionNormal, n.VolumeNormal) >= AngleLimit)
                    {
                        Select.Add(n);
                    }
                }
            }

            SelectTriangles(Select);
        }
        string GetAllTypesAsString(HashSet <string> types)
        {
            // This causes a conflict with the vim keyword 'contains'
            types.Remove("Contains");

            return(types.Aggregate("", (current, type) => current + type + " "));
        }
        public async Task <AbstractDownloadState?> Infer(Uri uri)
        {
            var state = YouTubeDownloader.UriToState(uri) as YouTubeDownloader.State;

            if (state == null)
            {
                return(null);
            }

            var client = new YoutubeClient(Common.Http.ClientFactory.Client);
            var video  = await client.Videos.GetAsync(state.Key);

            var desc = video.Description;

            var replaceChars = new HashSet <char>()
            {
                '_', '(', ')', '-'
            };

            var lines = desc.Split('\n', StringSplitOptions.RemoveEmptyEntries)
                        .Select(line => line.Trim())
                        .Select(line =>
            {
                var segments = replaceChars.Aggregate(line, (acc, c) => acc.Replace(c, ' '))
                               .Split(' ', StringSplitOptions.RemoveEmptyEntries);
                if (segments.Length == 0)
                {
                    return(TimeSpan.Zero, string.Empty);
                }

                foreach (var segment in segments)
                {
                    if (TryParseEx(segment, out var si))
                    {
                        return(si, string.Join(" ", segments.Where(s => !s.Contains(":"))));
                    }
                }
                return(TimeSpan.Zero, string.Empty);
            })
                        .Where(t => t.Item2 != string.Empty)
                        .ToList();

            var tracks = lines.Select((line, idx) => new YouTubeDownloader.State.Track
            {
                Name   = Sanitize(line.Item2),
                Start  = line.Item1,
                End    = idx < lines.Count - 1 ? lines[idx + 1].Item1 : video.Duration,
                Format = YouTubeDownloader.State.Track.FormatEnum.XWM
            }).ToList();

            foreach (var track in tracks)
            {
                Utils.Log($"Inferred Track {track.Name} {track.Format} {track.Start}-{track.End}");
            }

            state.Tracks = tracks;

            return(state);
        }
Exemple #18
0
 public static string Unaccent(this string word)
 {
     if (word == null)
     {
         return(word);
     }
     return(UnaccentRules.Aggregate(word, (current, rule) => rule.Apply(current)));
 }
Exemple #19
0
 public int ComputeTermsHashCode()
 {
     if (_termsHash == null)
     {
         _termsHash = _terms.Aggregate(0, (x, y) => unchecked (x + y.GetHashCode()));
     }
     return(_termsHash.Value);
 }
Exemple #20
0
 public static HashSet <Port> CopyHashSet(HashSet <Port> set)
 {
     return(set.Aggregate(new HashSet <Port>(), (s, p) =>
     {
         s.Add(p.Clone());
         return s;
     }));
 }
Exemple #21
0
 public int ComputeFactorsHashCode()
 {
     if (_factorsHash == null)
     {
         _factorsHash = _factors.Aggregate(0, (x, y) => unchecked (x + y.GetHashCode()));
     }
     return(_factorsHash.Value);
 }
Exemple #22
0
 public ComponentTypeSet(IEnumerable <ComponentType> types)
 {
     _types = new HashSet <ComponentType>(new ComponentTypeComparer());
     foreach (var type in types)
     {
         Add(type);
     }
     _hashCode = _types.Aggregate(0, (hash, type) => hash ^ HashCode(type));
 }
 public override string ToString()
 {
     return(string.Format("{0} [{1}]\nRequires: {2}\nOptional: {3}\nInput: {4}",
                          Module.Name ?? "null",
                          string.IsNullOrEmpty(PartName)? "always available" : PartName,
                          Requires.Aggregate("", (s, t) => s + t.Name + " "),
                          Optional.Aggregate("", (s, t) => s + t.Name + " "),
                          Input.Aggregate("", (s, t) => s + t.Name + " ")));
 }
        public byte[] XmlFilter(byte[] data)
        {
            XDocument xdoc = XDocument.Load(XmlReader.Create(new MemoryStream(data), new XmlReaderSettings(){CloseInput = true}));
            var nodesToRemove = new List<XNode>();
            HashSet<string> removedModuleFeaturesIds = new HashSet<string>();
            HashSet<string> removedModulesIds = new HashSet<string>();

            foreach (var xelement in xdoc.DescendantNodes().OfType<XElement>())
            {
                if (xelement.Name.LocalName.Contains("KeyValueOfModuleID"))
                {
                    ModuleID featureId;
                    var keys = xelement.Nodes().OfType<XElement>().Where(n => n.Name.LocalName == "Key" && !Enum.TryParse<ModuleID>(n.Value, out featureId)).ToList();
                    if (keys.Count != 0)
                    {
                        nodesToRemove.Add(xelement);
                        keys.ForEach(k => removedModulesIds.Add(k.Value));
                    }
                }
                else if (xelement.Name.LocalName.Contains("KeyValueOfModuleFeatureID"))
                {
                    ModuleFeatureID featureId;
                    var keys = xelement.Nodes().OfType<XElement>().Where(n => n.Name.LocalName == "Key" && !Enum.TryParse<ModuleFeatureID>(n.Value, out featureId)).ToList();
                    if (keys.Count != 0)
                    {
                        nodesToRemove.Add(xelement);
                        keys.ForEach(k => removedModuleFeaturesIds.Add(k.Value));
                    }
                }
            }

            if (nodesToRemove.Count != 0)
            {
                if (removedModulesIds.Count != 0)
                {
                    var message = "ModuleIds filtered out from configuration:" + removedModulesIds.Aggregate(string.Empty, (res, k) => res + k + ",");
                    SP.SysLog.AddWarn(this, message);
                }
                if (removedModuleFeaturesIds.Count != 0)
                {
                    var message = "ModuleFeatureIds filtered out from configuration:" + removedModuleFeaturesIds.Aggregate(string.Empty, (res, k) => res + k + ",");
                    SP.SysLog.AddWarn(this, message);
                }

                nodesToRemove.ForEach(n => n.Remove());

                var ms = new MemoryStream(data.Length);
                var xmlWriter = XmlWriter.Create(ms, new XmlWriterSettings() { WriteEndDocumentOnClose = true, CloseOutput = true });
                xdoc.WriteTo(xmlWriter);
                xmlWriter.Close();
                return ms.ToArray();
            }
            else
            {
                return data;
            }
        }
Exemple #25
0
    public List <MapNode> AStar(MapNode start, MapNode target, out float distance)
    {
        distance = 0;
        if (start == target)
        {
            return(new List <MapNode>());
        }

        List <Vector2Int> result = new List <Vector2Int>();
        HashSet <NavigationNode <MapNode> > closedSet = new HashSet <NavigationNode <MapNode> >();
        HashSet <NavigationNode <MapNode> > openSet   = new HashSet <NavigationNode <MapNode> >()
        {
            new NavigationNode <MapNode>((int)(target.Cell.center - start.Cell.center).sqrMagnitude, 0, start)
        };

        while (openSet.Count > 0)
        {
            NavigationNode <MapNode> current = openSet.Aggregate((x, y) => x.FScore < y.FScore ? x : y);
            if (current.Data.Equals(target))
            {
                return(UnwrapPath(current, out distance));
            }

            openSet.Remove(current);
            closedSet.Add(current);
            List <Tuple <MapNode, int> > neighbours = current.Data.Corridors.Aggregate(new List <Tuple <MapNode, int> >(), (list, y) =>
            {
                if (!y.Point1.Data.Equals(current.Data))
                {
                    list.Add(new Tuple <MapNode, int>(y.Point1.Data, (int)y.DistanceSquared));
                }

                if (!y.Point2.Data.Equals(current.Data))
                {
                    list.Add(new Tuple <MapNode, int>(y.Point2.Data, (int)y.DistanceSquared));
                }

                return(list);
            });

            neighbours.ForEach(x =>
            {
                if (!closedSet.Any(closed => closed.Data.Equals(x.Item1)))
                {
                    if (!openSet.Any(open => open.Data.Equals(x.Item1)))
                    {
                        NavigationNode <MapNode> node = new NavigationNode <MapNode>((int)(target.Cell.center - x.Item1.Cell.center).sqrMagnitude, x.Item2, x.Item1);
                        node.Parent = current;
                        openSet.Add(node);
                    }
                }
            });
        }

        return(null);
    }
Exemple #26
0
        protected string ListMethods(HashSet <string> h)
        {
            string result = Path.GetFileName(Assembly);

            if (h.Count == 0)
            {
                return($" {result}: success");
            }
            return(result + "\n" + h.Aggregate((arg1, arg2) => arg1 + "\n" + arg2));
        }
Exemple #27
0
        public ICollection <CellNode> AStar(int sx, int sy, int ex, int ey)
        {
            CellNode start = new CellNode(sx, sy);
            CellNode goal  = new CellNode(ex, ey);

            //Create data structures
            IDictionary <CellNode, CellNode> cameFrom = new Dictionary <CellNode, CellNode>();

            ISet <CellNode> closedSet = new HashSet <CellNode>();
            ISet <CellNode> openSet   = new HashSet <CellNode>();

            openSet.Add(start);

            int[,] gScore            = StartMatrix();
            gScore[start.X, start.Y] = 0;

            int[,] fScore            = StartMatrix();
            fScore[start.X, start.Y] = HeuristicCostEstimate(start, goal);
            //Start
            while (openSet.Count > 0)
            {
                CellNode current = openSet
                                   .Aggregate(((node, cellNode) => fScore[node.X, node.Y] < fScore[cellNode.X, cellNode.Y] ? node : cellNode));
                if (current.Equals(goal))
                {
                    return(Path(cameFrom, current));
                }
                openSet.Remove(current);
                closedSet.Add(current);
                //Explore neighbours
                foreach (var neighbor in GetNeighbours(current))
                {
                    if (closedSet.Contains(neighbor))
                    {
                        continue;
                    }

                    int tentativeGScore = gScore[current.X, current.Y] + 1;

                    if (!openSet.Contains(neighbor))
                    {
                        openSet.Add(neighbor);
                    }
                    else if (tentativeGScore >= gScore[neighbor.X, neighbor.Y])
                    {
                        continue;
                    }

                    cameFrom[neighbor]             = current;
                    gScore[neighbor.X, neighbor.Y] = tentativeGScore;
                    fScore[neighbor.X, neighbor.Y] = gScore[neighbor.X, neighbor.Y] + HeuristicCostEstimate(neighbor, goal);
                }
            }
            return(null);
        }
    private List <VectorTile> VectorFieldAlgorithm(Vector2Int startPosition)
    {
        VectorTile current = new VectorTile(Vector2Int.zero);

        // Locks and selects all the tiles within a 20
        // unit distance in the VectorTile pool
        // while reseting the values for all tiles in the pool.
        var tiles = new List <VectorTile>();

        lock (_vectorTilesPool)
        {
            tiles = _vectorTilesPool.Where(t =>
            {
                t.Reset();
                if (t.Position == startPosition)
                {
                    current = t;
                }
                return(Vector2.Distance(startPosition, t.Position) < 10f);
            }).Select(t => new VectorTile(t)).ToList();
        }

        var open = new HashSet <VectorTile>()
        {
            current
        };
        var close = new HashSet <VectorTile>();

        // Modified version of Djistra's Algorithm.
        while (open.Count != 0)
        {
            current = open.Aggregate((a, b) => a.Distance < b.Distance ? a : b);
            open.Remove(current);
            close.Add(current);

            // Loops through every neighbor of the current tile.
            foreach (var neighbor in GetNeighbors(current, tiles))
            {
                if (close.Contains(neighbor))
                {
                    continue;
                }

                // Sets neighbor's distance and direction and adds it to the open list.
                if (!open.Contains(neighbor))
                {
                    neighbor.Distance  = current.Distance + Vector2.Distance(neighbor.Position, current.Position);
                    neighbor.Direction = current.Position - neighbor.Position;
                    open.Add(neighbor);
                }
            }
        }

        return(tiles);
    }
Exemple #29
0
        public void OnLevelLoaded()
        {
            if (lightPropsDefParseErrors?.Count > 0)
            {
                var errorMessage = lightPropsDefParseErrors.Aggregate("Error while parsing light-prop definition file(s). Contact the author of the assets. \n" + "List of errors:\n", (current, error) => current + (error + '\n'));

                UIView.library.ShowModal <ExceptionPanel>("ExceptionPanel").SetMessage("Network Skins", errorMessage, true);
            }

            lightPropsDefParseErrors = null;
        }
        private static string StripFromSentence(string sentence)
        {
            string[] strings = sentence.Split(new[] { (char)0x20 });
            var      ap      = new HashSet <string>();

            foreach (string s in strings)
            {
                ap.Add(s);
            }
            return(ap.Aggregate(string.Empty, (current, word) => current + (word + (char)0x20)));
        }
Exemple #31
0
    public override void Process(GameTime gameTime, int entityId)
    {
        var movable   = movableMapper.Get(entityId);
        var transform = transformMapper.Get(entityId);

        // Add up all the gravitational forces acting on the movable
        var resultingGravityPull = gravityPointEntities.Aggregate(Vector2.Zero,
                                                                  (current, point) => current + CalculateGravityPull(point, transform));

        movable.GravityPull = resultingGravityPull * movable.GravityMultiplier * variables.Global[GlobalVariable.GravityMultiplier];
    }
Exemple #32
0
        public override string ToString()
        {
            var str = "[" + ID + "]:" + Type + " - " + Name;

            if (AliasSet.Count > 0)
            {
                str += " - " + AliasSet.Aggregate((sum, s) => sum + ", " + s);
            }

            return(str);
        }
        public List <Item> GetRecommedations(int count = 10)
        {
            if (count <= 0)
            {
                throw new InvalidOperationException($"'{nameof(count)}' should be a positive integer.");
            }

            var index = GetSearchIndex();

            using (var context = index.CreateSearchContext())
            {
                var query = context.GetQueryable <T>();
                query = ApplyFilterQuery(query);

                // Template filtering
                if (!KnownSettings.SearchTemplates.Any())
                {
                    var templatesPred = KnownSettings.SearchTemplates.Aggregate(
                        PredicateBuilder.False <T>(),
                        (acc, id) => acc.Or(item => item.TemplateId == id));
                    query = query.Filter(templatesPred);
                }

                // Stored items filtering
                if (KnownSettings.FilterStoredItems)
                {
                    // Dedupe IDs
                    var itemIds = new HashSet <ID>();
                    GetIdsFromCookie().ForEach(id => itemIds.Add(id));

                    query = itemIds.Aggregate(query, (acc, id) => acc.Filter(item => item.ItemId != id));
                }

                // Context item filtering
                if (KnownSettings.FilterContextItem)
                {
                    query = query.Filter(item => item.ItemId != Context.Item.ID);
                }

                // Boosting predicate
                var tagsWeight = GetTagsWeight();
                var boosting   = tagsWeight.Keys.Aggregate(
                    PredicateBuilder.Create <T>(item => item.Name.MatchWildcard("*").Boost(0.0f)),
                    (acc, tag) => acc.Or(item => item[KnownSettings.SearchField].Equals(tag).Boost(tagsWeight[tag])));

                return(query
                       .Where(boosting)
                       .Take(count)
                       .OrderByDescending(item => item["score"])
                       .ToList() // remove
                       .Select(doc => doc.GetItem())
                       .ToList());
            }
        }
 public string LambdaReduce() =>
 students.Aggregate(
     new StringBuilder(),
     (sb, s) => sb.AppendFormat
     (
         "{0}, {1} - {2}",
         s.lastName,
         s.firstName,
         (s.average > 60) ? s.average.ToString() : "Failed"
     ),
     sb => sb.ToString());
Exemple #35
0
        public string Handle(string input, Match match, IListener listener)
        {
            var process = match.Groups[1].Value.ToLower();
            var list = Process.GetProcesses().Where(o => o.ProcessName.ToLower().Contains(process)).ToList();
            var closed = new HashSet<string>();
            foreach (var p in list)
            {
                try
                {
                    p.Kill();
                    closed.Add(p.ProcessName);
                }
                catch(Exception)
                {
                }
            }

            return closed.Aggregate("", (current, close) => current + "I've closed " + close + Environment.NewLine);
        }
Exemple #36
0
        public void FillTriangleSelection()
        {
            if (CurrentTriangleSelection.Count == 0)
                return;

            HashSet<Triangle> FillSelect = new HashSet<Triangle>(CurrentTriangleSelection);
            HashSet<Triangle> Frontier = new HashSet<Triangle>(CurrentTriangleSelection);

            while (true)
            {
                HashSet<Triangle> Select = new HashSet<Triangle>();
                float AngleLimit = (float) Math.Cos(SelectionAngle / 180f * Math.PI);
                Vector3 SelectionNormal = new Vector3(0);
                SelectionNormal = FillSelect.Aggregate(SelectionNormal, (current, t) => current + t.VolumeNormal);
                SelectionNormal.Normalize();

                foreach (Triangle t in Frontier)
                    foreach (Triangle n in t.Neighbors)
                        if (n.IsVisible && n.Patch == null && !FillSelect.Contains(n) && Vector3.Dot(SelectionNormal, n.VolumeNormal) >= AngleLimit)
                            Select.Add(n);

                if (Select.Count == 0)
                    break;

                Frontier = Select;
                foreach (var t in Select)
                    FillSelect.Add(t);
            }

            SelectTriangles(FillSelect);
        }
        /// <summary>
        /// This finds the "Aliquot Root": the terminating element of the onward
        /// Aliquot Chain from the number supplied. It works with the Aliquot DB links.
        /// It will deal correctly with arbitrary sized loops, returning the lowest
        /// element in the loop as the "root".
        /// </summary>
        /// <param name="n">Starting point</param>
        /// <returns>Aliquot root, or 0 if no root can be found</returns>
        private BigInteger GetRootOfChain(BigInteger n)
        {
            var aliquotChain = new HashSet<BigInteger>();
              while (true)
              {
            // No onward link - root is undefined
            if(! Links.ContainsKey(n))
            {
              return BigInteger.Zero;
            }

            // We are looping - get minimal element of loop
            if (aliquotChain.Contains(n))
            {
              // Gather the loop
              var aliquotLoop = new HashSet<BigInteger>();
              while(! aliquotLoop.Contains(n))
              {
            aliquotLoop.Add(n);
            n = Links[n].Successor;
              }
              // Calculate and return the smallest element
              var minimumInLoop = aliquotLoop.Aggregate(n, (x, e) => BigInteger.Min(x, e));
              return minimumInLoop;
            } // if: a loop

            BigInteger s = Links[n].Successor;

            // If successor is 1 then it's a prime - this is the root
            if (s == 1)
            {
              return n;
            }

            // add to the chain
            aliquotChain.Add(n);

            // Go to the next element
            n = s;

              } // while: true
        }
Exemple #38
0
 private Color GetNearestColor(HashSet<Color> palette, Color color)
 {
     return palette
         .Aggregate((a, b) => Color.DistanceSquared(a, color) < Color.DistanceSquared(b, color) ? a : b);
 }
 private void AddNonUniformCandidateInvariant(List<Cmd> cs, Block header)
 {
     var loopNodes = new HashSet<Block>();
     foreach (var b in blockGraph.BackEdgeNodes(header))
       loopNodes.UnionWith(blockGraph.NaturalLoops(header, b));
     var exits = new HashSet<Expr>();
     foreach (var ln in loopNodes) {
       if (ln.TransferCmd is GotoCmd) {
     var gCmd = (GotoCmd) ln.TransferCmd;
     foreach (var exit in gCmd.labelTargets.Cast<Block>()
                          .Where(b => !loopNodes.Contains(b)))
       exits.Add(blockIds[exit]);
       }
       if (ln.TransferCmd is ReturnCmd)
     exits.Add(returnBlockId);
     }
     var curIsHeaderOrExit = exits.Aggregate((Expr)Expr.Eq(cur, blockIds[header]),
                                     (e, exit) => Expr.Or(e, Expr.Eq(cur, exit)));
     cs.Add(prog.CreateCandidateInvariant(
      CreateIfFPThenElse(curIsHeaderOrExit, Expr.Eq(cur, returnBlockId)),
      "non-uniform loop"));
 }
        private static void AddAjaxDataUrlsToElementSet(this HtmlHelper html, IObjectFacade nakedObject, TagBuilder fieldSet, PropertyContext parent = null) {
            var parameters = new HashSet<string>(nakedObject.Specification.Properties.SelectMany(p => p.GetChoicesParameters()).Select(t => t.Item1));

            // check the names match 

            var properties = nakedObject.Specification.Properties;
            IEnumerable<string> matches = from p in parameters
                                          from pp in properties
                                          where p.ToLower() == pp.Id.ToLower()
                                          select p;

            if (matches.Count() != parameters.Count) {
                string error = String.Format("On choices method in: {0} one or more properties in: '{1}' does not match a property on that class", nakedObject.Specification.FullName, parameters.Aggregate("", (s, t) => s + " " + t));
                throw new ArgumentException(error);
            }

            string parameterNames = parameters.Aggregate("", (s, t) => (s == "" ? "" : s + ",") + new PropertyContext(html.IdHelper(), nakedObject, nakedObject.Specification.Properties.Single(p => p.Id.ToLower() == t.ToLower()), false, parent).GetFieldInputId());

            string url = html.GenerateUrl("GetPropertyChoices", "Ajax", new RouteValueDictionary(new { id = Encode(html.Facade().OidTranslator.GetOidTranslation(nakedObject)) }));
            fieldSet.MergeAttribute("data-choices", url);
            fieldSet.MergeAttribute("data-choices-parameters", parameterNames);
        }
 /// <summary>
 /// Appends strings from a HashSet<string>, separating them with Delimiter
 /// </summary>
 /// <param name="strToAppend">String to append to the file</param>
 /// <param name="Delimiter">Delimiter to append at the end of strToAppend.</param>
 public void AppendHashToDelimitedFile(HashSet<string> hashToAppend, char Delimiter)
 {
     AppendString(hashToAppend.Aggregate((temp, next) => temp + next + Delimiter));
 }
        private static void AddAjaxDataUrlsToElementSet(this HtmlHelper html, IObjectFacade nakedObject, IActionFacade action, TagBuilder fieldSet) {
            var parameters = new HashSet<string>(action.Parameters.SelectMany(p => p.GetChoicesParameters()).Select(t => t.Item1));
            // check the names match 

            IEnumerable<string> matches = from p in parameters
                                          from pp in action.Parameters
                                          where p.ToLower() == pp.Id.ToLower()
                                          select p;

            if (matches.Count() != parameters.Count) {
                string error = String.Format("On choices method Choices{0} one or more parameters in: '{1}' does not match a parameter on : {0}", action.Id, parameters.Aggregate("", (s, t) => s + " " + t));
                throw new ArgumentException(error);
            }

            string parameterNames = parameters.Aggregate("", (s, t) => (s == "" ? "" : s + ",") + html.IdHelper().GetParameterInputId(action, action.Parameters.Single(p => p.Id.ToLower() == t.ToLower())));

            var url = html.GenerateUrl("GetActionChoices", "Ajax", new RouteValueDictionary(new { id = Encode(html.Facade().OidTranslator.GetOidTranslation(nakedObject)), actionName = action.Id }));
            fieldSet.MergeAttribute("data-choices", url);
            fieldSet.MergeAttribute("data-choices-parameters", parameterNames);
        }
    public bool Write(InstallScript script,
      Func<string, DatabasePackageAction> errorHandler = null,
      Action<int, string> reportProgress = null)
    {
      var cont = true;
      var typeGroups = from l in script.Lines
                       where l.Type == InstallType.Create
                       group l by l.Reference.Type into typeGroup
                       select typeGroup;
      var cnt = typeGroups.Count();
      var idx = 0;
      var packageGroups = new HashSet<string>();
      string currPackageId = null;

      while (cont)
      {
        IEnumerable<IReadOnlyItem> elements;
        foreach (var typeGroup in typeGroups)
        {
          if (reportProgress != null) reportProgress((int)(idx * 50.0 / cnt), string.Format("Checking for existing package elements ({0} of {1}) ", idx + 1, cnt));

          if (typeGroup.First().Reference.Unique.IsGuid())
          {
            elements = _conn.Apply("<Item type=\"PackageElement\" action=\"get\" select=\"element_id,name,source_id\"><element_type>"
              + typeGroup.Key
              + "</element_type><element_id condition=\"in\">'"
              + typeGroup.Select(i => i.Reference.Unique).Aggregate((p, c) => p + "','" + c)
              + "'</element_id></Item>").Items();
          }
          else
          {
            elements = _conn.Apply("<Item type=\"PackageElement\" action=\"get\" select=\"element_id,name,source_id\"><element_type>"
              + typeGroup.Key
              + "</element_type><element_id condition=\"in\">(select id from innovator.["
              + typeGroup.Key.Replace(' ', '_')
              + "] where "
              + typeGroup.Select(i => i.Reference.Unique).Aggregate((p, c) => p + " or " + c)
              + ")</element_id></Item>").Items();
          }

          packageGroups.UnionWith(elements.Select(e => e.SourceId().Value));
          idx++;
        }

        var packages = _conn.Apply("<Item type=\"PackageDefinition\" action=\"get\" select=\"name\"><id condition=\"in\">(select SOURCE_ID FROM innovator.PACKAGEGROUP where id in ('"
          + packageGroups.Aggregate((p, c) => p + "','" + c)
          + "'))</id></Item>").Items();
        currPackageId = packages.Where(p => p.Property("name").Value == script.Title).SingleOrDefault().Id();

        cont = false;
        if (packages.Any(p => p.Property("name").Value != script.Title))
        {
          if (errorHandler != null)
          {
            var packageList = (from p in packages
                               where p.Property("name").Value != script.Title
                               select p.Property("name").Value)
                              .Aggregate((p, c) => p + ", " + c);
            switch (errorHandler("The package cannot be created because one or more elements exist in the packages: " + packageList))
            {
              case DatabasePackageAction.TryAgain:
                cont = true;
                break;
              case DatabasePackageAction.RemoveElementsFromPackages:
                foreach (var typeGroup in typeGroups)
                {
                  if (reportProgress != null) reportProgress((int)(idx * 50.0 / cnt), string.Format("Removing package elements ({0} of {1}) ", idx + 1, cnt));

                  if (typeGroup.First().Reference.Unique.IsGuid())
                  {
                    elements = _conn.Apply("<Item type=\"PackageElement\" action=\"purge\" where=\"[PackageElement].[element_type] = '"
                      + typeGroup.Key
                      + "' and [PackageElement].[element_id] in ('"
                      + typeGroup.Select(i => i.Reference.Unique).Aggregate((p, c) => p + "','" + c)
                      + "')\" />").Items();
                  }
                  else
                  {
                    elements = _conn.Apply("<Item type=\"PackageElement\" action=\"purge\" where=\"[PackageElement].[element_type] = '"
                      + typeGroup.Key
                      + "' and [PackageElement].[element_id] in (select id from innovator.["
                      + typeGroup.Key.Replace(' ', '_')
                      + "] where "
                      + typeGroup.Select(i => i.Reference.Unique).Aggregate((p, c) => p + " or " + c)
                      + ")\" />").Items();
                  }

                  idx++;
                }


                break;
              default:
                return false;
            }
          }
          else
          {
            return false;
          }
        }
      }

      // Try one more time to get the package
      if (string.IsNullOrEmpty(currPackageId))
      {
        var packages = _conn.Apply("<Item type=\"PackageDefinition\" action=\"get\" select=\"name\"><name>" + script.Title + "</name></Item>");
        currPackageId = packages.AssertItem().Id();
      }

      // Add the package
      if (string.IsNullOrEmpty(currPackageId))
      {
        var packages = _conn.Apply("<Item type=\"PackageDefinition\" action=\"add\" ><name>" + script.Title + "</name></Item>", true);
        currPackageId = packages.AssertItem().Id();
      }

      string groupId;
      foreach (var typeGroup in typeGroups)
      {
        if (reportProgress != null) reportProgress((int)(50 + idx * 50.0 / cnt), string.Format("Adding package elements of type ({0} of {1}) ", idx + 1, cnt));

        groupId = _conn.Apply("<Item type=\"PackageGroup\" action=\"merge\" where=\"[PackageGroup].[source_id] = '"
          +  currPackageId
          + "' and [PackageGroup].[name] = '"
          + typeGroup.Key
          + "'\"><name>"
          + typeGroup.Key
          + "</name></Item>", true).AssertItem().Id();

        foreach (var elem in typeGroup)
        {
          _conn.Apply("<Item type=\"PackageElement\" action=\"merge\" where=\"[PackageElement].[source_id] = '"
            + groupId
            + "' and [PackageElement].[element_id] = '"
            + (elem.InstalledId ?? elem.Reference.Unique)
            + "'\">"
            + "<element_type>" + typeGroup.Key + "</element_type>"
            + "<element_id>" + (elem.InstalledId ?? elem.Reference.Unique) + "</element_id>"
            + "<source_id>" + groupId + "</source_id>"
            + "<name>" + elem.Reference.KeyedName + "</name></Item>").AssertNoError();
        }

        idx++;
      }

      return true;
    }