Ejemplo n.º 1
0
        public string UpdateParamsWithValues(string originalSql)
        {
            string[] parts = originalSql.Replace("N'", "'").Replace("''", "'").Split(';');
            if (parts.Length <= 1)
                return originalSql;

            string sql = String.Join(";", parts.Take(parts.Length - 1).ToArray());
            string paramList = parts.Last();

            var parameters = new Dictionary<string, string>();
            ITokenizer tokenizer = new SqlTokenizer(paramList);
            tokenizer.ReadNextToken();
            do
            {
                string parameter = tokenizer.Current.Value;

                tokenizer.ReadNextToken();
                tokenizer.ExpectToken(Constants.Assignment);

                parameters.Add(parameter, ProcessParameter(tokenizer, parameter));
            }
            while (tokenizer.TokenEquals(Constants.Comma));

            foreach (var item in parameters.Reverse())
                sql = sql.Replace(item.Key, item.Value);

            return sql;
        }
Ejemplo n.º 2
0
        public static void DataBind(this Motor engine, Route route)
        {
            var list = new Dictionary<string, object>();

            var function = engine.RuntimeContext.Runnable.FunctionTable[route.Action];

            var instructions = engine.RuntimeContext.Runnable.Instructions;

            for (int i = function.EntryPoint; i < instructions.Length; i++)
            {
                var inst = instructions[i];

                if (inst.OpCode == OpCode.DCL)
                {
                    var value = route.Context.Request[inst.Operands[0].Value.ToString()] ?? string.Empty;

                    list.Add(inst.Operands[0].Value.ToString(), value);
                }

                if (inst.OpCode == OpCode.EMP) break;
            }

            foreach (var keypar in list.Reverse())
            {
                var op = new Operand(OperandType.Literal, keypar.Value);

                engine.RuntimeContext.Runnable.ParamStack.Push(op);
            }
        }
Ejemplo n.º 3
0
        internal static void CreateSearchNavigationNodes(ClientContext clientContext, Web web, Dictionary<string, string> searchNavigationNodes)
        {
            if (searchNavigationNodes == null || searchNavigationNodes.Count == 0) return;

            var searchNavigation = web.Navigation.GetNodeById(1040);
            NavigationNodeCollection nodeCollection = searchNavigation.Children;

            clientContext.Load(searchNavigation);
            clientContext.Load(nodeCollection);
            clientContext.ExecuteQuery();

            for (int i = nodeCollection.Count - 1; i >= 0; i--)
            {
                nodeCollection[i].DeleteObject();
            }

            foreach (KeyValuePair<string, string> newNode in searchNavigationNodes.Reverse<KeyValuePair<string, string>>())
            {
                nodeCollection.Add(new NavigationNodeCreationInformation
                {
                    Title = newNode.Key,
                    Url = newNode.Value
                });
            }

            clientContext.ExecuteQuery();
        }
Ejemplo n.º 4
0
        static void ValidateUserNames(string input)
        {
            string pattern = @"(?<=[\s\\\/]|^)([A-Za-z][A-Za-z0-9_]{3,25})";
            Regex regex = new Regex(pattern);
            MatchCollection matchCollection = regex.Matches(input);

            Dictionary<int, string> sumOfUsernames = new Dictionary<int, string>();

            for(int i = 0; i < matchCollection.Count - 1; i++)
            {
                string userNames = matchCollection[i].Value + " " + matchCollection[i + 1].Value;
                int sumOfUsers = GetSumOfUserNames(userNames);
                if(!sumOfUsernames.ContainsKey(sumOfUsers))
                    sumOfUsernames.Add(sumOfUsers, userNames);
            }

            SortedDictionary<int, string> sortedSum = new SortedDictionary<int, string>(sumOfUsernames);

            foreach(KeyValuePair<int, string> key in sumOfUsernames.Reverse())
            {
                string[] userNames = key.Value.Split(' ').ToArray();
                Console.WriteLine(userNames[0]);
                Console.WriteLine(userNames[1]);
                break;
            }
        }
Ejemplo n.º 5
0
    static void MakeSchedule()
    {
        int currentDuration = 0;

        trainScheduleForward = stationsInfo.ToDictionary(
            kvp => stationsByName[kvp.Key],
            kvp => currentDuration += kvp.Value
        );

        trainScheduleDuration = currentDuration;

        trainScheduleBackwards = trainScheduleForward.Reverse().ToDictionary(
            kvp => kvp.Key,
            kvp => trainScheduleDuration - kvp.Value
        );

        #if DEBUG
        Console.WriteLine("# Schedule");

        Console.WriteLine(string.Join(Environment.NewLine, trainScheduleForward));
        Console.WriteLine();

        Console.WriteLine(string.Join(Environment.NewLine, trainScheduleBackwards));
        Console.WriteLine();
        #endif
    }
        private void TickAllTimers()
        {
            float time = Time.deltaTime;

            // Purpose of this is the same as a reverse for loop, if a timer is removed, shifting would occur
            // If we iterate backwards we won't get a CollectionWasModifier error
            // Placeholder to prevent table head smacking
            foreach (var kvp in timers.Reverse())
            {
                kvp.Value.TryTick(time);
            }
        }
Ejemplo n.º 7
0
        public Dictionary <string, int> GetTotalFiles()
        {
            Dictionary <string, int> totalFiles = new Dictionary <string, int>();

            try
            {
                StringBuilder sbQuery = new StringBuilder();

                //select
                sbQuery.Append("select create_at, count(*) Count ");
                //from
                sbQuery.Append("from files ");
                //group by
                sbQuery.Append($"group by create_at ");
                //order by
                sbQuery.Append($"order by create_at desc ");
                //limit
                sbQuery.Append($"limit 5 ");

                SQLiteCommand    command     = new SQLiteCommand(sbQuery.ToString(), connect);
                SQLiteDataReader queryReader = command.ExecuteReader();

                while (queryReader.Read())
                {
                    string dateName = string.Empty;

                    //2020908 -> 9.8
                    dateName = queryReader[0].ToString();

                    dateName = dateName.Substring(4, 4).Insert(2, ".");

                    if (dateName[3] == '0')
                    {
                        dateName = dateName.Remove(3, 1);
                    }

                    if (dateName[0] == '0')
                    {
                        dateName = dateName.Remove(0, 1);
                    }

                    totalFiles.Add(dateName, Convert.ToInt32(queryReader[1]));
                }

                totalFiles = totalFiles.Reverse().ToDictionary(dict => dict.Key, dict => dict.Value);
            }
            catch
            {
                return(null);
            }

            return(totalFiles);
        }
Ejemplo n.º 8
0
        protected void AddANewShortCutToEndOfList()
        {
            var ShortCuts = GetWindowShortCuts();
            var CanUsed   = (from x in WinList.Reverse()
                             where !(ShortCuts.FindIndex(y => y.WindowGuid == x.Key) > -1)
                             select x).ToList();

            if (CanUsed.Count > 0)
            {
                AddNewShortCutWindow(CanUsed[0].Key, false);
            }
        }
Ejemplo n.º 9
0
        internal static string ContractToString(double value)
        {
            foreach (var m in Multipliers.Reverse())
            {
                if (value >= m.Value)
                {
                    return((value / m.Value).ToString() + m.Key);
                }
            }

            return(value.ToString());
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Returns a <see cref="string"/> that represents this instance.
        /// </summary>
        /// <returns>A <see cref="string"/> that represents this instance.</returns>
        public override string ToString()
        {
            foreach (var multiplier in multipliers.Reverse())
            {
                if (Value >= multiplier.Value && Value % ((decimal)multiplier.Value / 1000) == 0)
                {
                    return($"{Value / (decimal)multiplier.Value}{multiplier.Key}".ToString(CultureInfo.CurrentCulture));
                }
            }

            return($"{Value.ToString(CultureInfo.CurrentCulture)}{B}");
        }
Ejemplo n.º 11
0
    public static void Main()
    {
        string input = Console.ReadLine();
        var    nameAndDateInDictionary = new Dictionary <string, DateTime>();

        while (input != "end")
        {
            List <string> NameAndDate = input
                                        .Split(' ') //! like Yoan Enchev -> 27.04.2017
                                        .ToList();

            string name    = NameAndDate[0];
            string Getdate = NameAndDate[2]; //[1] ->

            var date = DateTime.ParseExact(Getdate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            nameAndDateInDictionary[name] = date;

            input = Console.ReadLine();
        }

        int howManyEqualPairs = 0;

        foreach (var kvp_1 in nameAndDateInDictionary)
        {
            DateTime date_1 = kvp_1.Value;
            string   name_1 = kvp_1.Key;

            foreach (var kvp_2 in nameAndDateInDictionary)
            {
                DateTime date_2 = kvp_2.Value;
                string   name_2 = kvp_2.Key;

                if (date_1 == date_2 && name_1 != name_2)
                {
                    howManyEqualPairs++;
                }
            }
        }

        Dictionary <string, DateTime> DescendingDate;

        DescendingDate = nameAndDateInDictionary
                         .Reverse()
                         .OrderByDescending(d => d.Value)
                         .ToDictionary(x => x.Key, y => y.Value);

        var takeFiveOrLess = DescendingDate
                             .Skip(DescendingDate.Count - 5)
                             .Take(5)
                             .ToDictionary(x => x.Key, y => y.Value);

        Console.WriteLine(string.Join(Environment.NewLine, takeFiveOrLess.Keys));
    }
Ejemplo n.º 12
0
        private static void PrintUsers(Dictionary <string, DateTime> registeredUsers)
        {
            var result = registeredUsers
                         .Reverse()
                         .OrderBy(e => e.Value)
                         .Take(5)
                         .OrderByDescending(e => e.Value)
                         .ToDictionary(e => e.Key, e => e.Value)
                         .Keys;

            Console.Write(string.Join(Environment.NewLine, result));
        }
Ejemplo n.º 13
0
    static void ReplaceUppercaseWords(StringBuilder text, Dictionary <Match, string> replacementsByMatches)
    {
        foreach (KeyValuePair <Match, string> pair in replacementsByMatches.Reverse())
        {
            string upcaseWord  = pair.Key.Value;
            int    index       = pair.Key.Index;
            string replacement = pair.Value;

            text.Remove(index, upcaseWord.Length);
            text.Insert(index, replacement);
        }
    }
Ejemplo n.º 14
0
    public string IntToRoman(int num)
    {
        string s = "";

        while (num > 0)
        {
            var rom = Dict.Reverse().Where(x => num - x.Value >= 0).FirstOrDefault();
            s   += rom.Key;
            num -= rom.Value;
        }
        return(s);
    }
Ejemplo n.º 15
0
        public void InsertCash(float value)
        {
            if (RemainingCosts <= 0)
            {
                MessageBox.Show("No remaining costs, buy a ticket below.");
                return;
            }

            if (Balance <= 0)
            {
                MessageBox.Show("Out of cash.");
                return;
            }

            if (_money[value].Amount > 0)
            {
                RemainingCosts       -= value;
                _money[value].Amount -= 1;
                CalculateBalance();

                // Check if Tickets are paid off and calculate exchange
                if (RemainingCosts <= 0)
                {
                    float returnMoney = (float)Math.Round(Math.Abs(RemainingCosts), 2);
                    var   exchange    = returnMoney;

                    foreach (KeyValuePair <float, MoneyItem> entry in _money.Reverse())
                    {
                        returnMoney = (float)Math.Round(returnMoney, 2);
                        float rest = returnMoney / entry.Key;
                        if (rest >= 1)
                        {
                            returnMoney -= (float)Math.Floor(rest) * entry.Key;
                            _money[entry.Key].Amount += (int)Math.Floor(rest);
                        }
                    }

                    RemainingCosts = 0;
                    CalculateBalance();

                    // Output
                    string output = "";
                    output += "Ticket(s) purchased!\n";
                    output += "--------------------\n";
                    output += $"{this.ticketOutput}\n";
                    output += $"Exchange: \t{exchange.ToString("0.00")}€";

                    MessageBox.Show(output);
                    this.ticketOutput = "";
                }
            }
        }
Ejemplo n.º 16
0
        public static IDictionary <string, string> GetIrregularPlurals()
        {
            var result = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            foreach (KeyValuePair <string, string> item in dictionary.Reverse())
            {
                if (!result.ContainsKey(item.Value))
                {
                    result.Add(item.Value, item.Key);
                }
            }
            return(result);
        }
        private static string GetSubjectNameItemString(Dictionary <string, string> dic)
        {
            var rev = dic.Reverse();

            var sb = new StringBuilder();

            foreach (var item in rev)
            {
                sb.Append(item.Key + "=" + item.Value + ",");
            }
            sb.Length--;
            return(sb.ToString());
        }
Ejemplo n.º 18
0
        internal static Dictionary <string, string> GetIrregularPlurals()
        {
            var result = new Dictionary <string, string>();

            foreach (var item in dictionary.Reverse())
            {
                if (!result.ContainsKey(item.Value))
                {
                    result.Add(item.Value, item.Key);
                }
            }
            return(result);
        }
Ejemplo n.º 19
0
        public IList <IList <int> > LevelOrderBottom(TreeNode root)
        {
            RunLevelOrderBottom(root, 0);
            var reversed = treeValueCol.Reverse();
            IList <IList <int> > results = new List <IList <int> >();

            foreach (KeyValuePair <int, IList <int> > level in reversed)
            {
                results.Add(level.Value);
            }

            return(results);
        }
Ejemplo n.º 20
0
        public static AssemblyResourceStore GetResourceStoreFromVirtualPath(string virtualPath)
        {
            string path = VirtualPathUtility.ToAppRelative(virtualPath).ToLower();

            foreach (var pair in AssemblyResourceStores.Reverse())
            {
                if (path.Contains(pair.Key) && pair.Value.IsPathResourceStream(path))
                {
                    return(pair.Value);
                }
            }
            return(null);
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            string path = null;

            try
            {
                path = Directory.GetCurrentDirectory() + @"\text.txt";
            }
            catch
            {
                Console.WriteLine("File not found!");
            }
            string text = null;

            if (path != null)
            {
                text = ReadInfo(path);
            }

            var wordsAndCounter = new Dictionary <string, int>();

            if (text != null)
            {
                int value = 0;
                var words = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                words = words.OrderBy(s => s).ToArray();
                words = words.Reverse().ToArray();
                foreach (var word in words)
                {
                    if (wordsAndCounter.TryGetValue(word, out value))
                    {
                        wordsAndCounter[word]++;
                    }
                    else
                    {
                        wordsAndCounter.Add(word, 1);
                    }
                }
                wordsAndCounter = wordsAndCounter.OrderBy(pair => pair.Value).ToDictionary(pair => pair.Key, pair => pair.Value);
                wordsAndCounter = wordsAndCounter.Reverse().ToDictionary(pair => pair.Key, pair => pair.Value);
                int cnt = 0;
                foreach (var word in wordsAndCounter)
                {
                    if (cnt < 10)
                    {
                        Console.WriteLine(word.Key + " - " + word.Value);
                    }
                    cnt++;
                }
            }
        }
Ejemplo n.º 22
0
    public void ModifyDashSequence(BaseBrick brick, int brickLimit, out BaseBrick lastBrick)
    {
        lastBrick = brick;
        if (dashSequence != null)
        {
            //checking if sequence already has the brick in sequence or not. If not then we will add it to sequence
            if (!dashSequence.ContainsKey(brick.ID) && brick != null)
            {
                brick.ToggleSelectState(true);
                dashSequence.Add(brick.ID, brick);
                Debug.Log("Added to seq brick ID : " + brick.ID);
            }
            else
            {
                //if brick is already present then we want to remove it from the sequence if user selected the brick again
                List <string> toRemove = new List <string>();
                //finding all the bricks from the end of the sequence to the point user has touched
                foreach (KeyValuePair <string, BaseBrick> pair in dashSequence.Reverse())
                {
                    if (pair.Key != brick.ID)
                    {
                        toRemove.Add(pair.Key);
                    }

                    if (pair.Key == brick.ID)
                    {
                        toRemove.Add(pair.Key);
                        break;
                    }
                }
                //removing it from the sequence
                foreach (string key in toRemove)
                {
                    dashSequence[key].ToggleSelectState(false);
                    dashSequence.Remove(key);
                    Debug.Log("Brick removed with ID : " + key);
                }

                //last brick is needed to find the next adjacent bricks to avoid adjacent movements
                if (dashSequence.Count > 0)
                {
                    lastBrick = dashSequence[dashSequence.Keys.Last()];
                }
                else
                {
                    //if all the items were removed then we want the current cell player is in to be returned
                    lastBrick = currentBrickCell;
                }
            }
        }
    }
Ejemplo n.º 23
0
 void MineLonger(IEnumerable <string> previous, double minSupport, Dictionary <string, double> subFList, List <ItemSet> SubFreqKey)
 {
     foreach (var kvpair in subFList.Reverse())
     {
         var items = previous.ToList();
         items.Add(kvpair.Key); // add all (n+1)-itemsets containing previous and where n = previous.Count
         ItemSet its = new ItemSet(items, kvpair.Value);
         if (its.Support >= minSupport)
         {
             patterns.Add(its);
         }
     }
     foreach (var kvpair in subFList.Reverse())
     {
         var items = previous.ToList();
         items.Add(kvpair.Key);
         List <ItemSet> subFreqByKey = new List <ItemSet>();
         FPTree         subsubTree   = BuildSubTree(SubFreqKey, items[items.Count - 2], minSupport);
         MinePatterns(subsubTree.rootNode, kvpair.Key, minSupport, subFreqByKey);
         var _subFList = GenerateFList(subFreqByKey, kvpair.Key, minSupport); //create new FList for newly added pattern
         MineLonger(items, minSupport, _subFList, subFreqByKey);
     }
 }
Ejemplo n.º 24
0
        private void InitializeEncoder(string input)
        {
            frequencies = new Dictionary <char, decimal>(256);
            foreach (var c in input)
            {
                if (!frequencies.ContainsKey(c))
                {
                    frequencies.Add(c, 0);
                }

                frequencies[c]++;
            }
            frequencies = frequencies.Reverse().ToDictionary(pair => pair.Key, pair => pair.Value);
        }
    private static void DrawIcons_(Component[] components, Rect target_rect)
    {
        // DynamicBoneのm_Rootの対象となるGameObject
        if (dynamic_bone_roots_.Contains(components[0].transform))
        {
            DrawIcon_(icon_resources_["DynamicBoneRoot"], target_rect);
            return;
        }

        foreach (Component component in components)
        {
            foreach (var icon_info in icon_resources_.Reverse())
            {
                if (component != null && component.GetType().Name.Contains(icon_info.Key))
                {
                    var icon = icon_info.Value;
                    // DynamicBoneのm_Rootに対象となるTransformが設定されていない場合は専用のアイコンに切り替える
                    if (kDynamicBoneType != null && component.GetType() == kDynamicBoneType)
                    {
                        if (kDynamicBoneType.GetField("m_Root").GetValue(component) == null)
                        {
                            icon = icon_resources_["DynamicBonePartial"];
                        }
                    }

#if (VRC_SDK_VRCSDK3 && !UDON)
                    // PBがアタッチされていたら専用のアイコンに切り替える. rootTransformが設定されていない場合は警告用のアイコンを表示する
                    foreach (var pb in component.GetComponents <VRCPhysBone>().Where(obj => obj != null))
                    {
                        if (pb.rootTransform != null)
                        {
                            icon = icon_resources_["VRCPhysBoneRoot"];
                        }
                        else
                        {
                            icon = icon_resources_["VRCPhysBonePartial"];
                        }
                    }
#endif
                    DrawIcon_(icon, target_rect);

                    if (VRChierarchyHighlighterEdit.is_draw_vers.GetValue())
                    {
                        PreviewVers_(component, target_rect);
                    }
                    return;
                }
            }
        }
    }
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            graph        = new Dictionary <string, List <string> >();
            dependencies = new Dictionary <string, int>();
            graph        = ReadGraph();
            dependencies = DefineDependencies();
            dependencies = dependencies.Reverse().ToDictionary(x => x.Key, x => x.Value);
            var sorted = SearchGraph();

            if (sorted != null)
            {
                Console.WriteLine(string.Join(" ", sorted));
            }
        }
Ejemplo n.º 27
0
        private static void PrintFirstFiveRegisteredUsers()
        {
            var result = userCollection
                         .Reverse()
                         .OrderBy(user => user.Value)
                         .Take(5)
                         .OrderByDescending(user => user.Value)
                         .ToDictionary(x => x.Key, x => x.Value);

            foreach (var user in result)
            {
                Console.WriteLine(user.Key);
            }
        }
Ejemplo n.º 28
0
    public void DrawMeshOnEachBranch()
    {
        foreach (var branch in SplinePlus.SPData.DictBranches)
        {
            //update branches layers
            if (!DMBranches.ContainsKey(branch.Key))
            {
                var newBranchLayer = new DMBranch();
                newBranchLayer.MeshHolder = new GameObject("Mesh Holder");

                newBranchLayer.MeshHolder.AddComponent <MeshFilter>();
                newBranchLayer.MeshHolder.AddComponent <MeshRenderer>();
                newBranchLayer.MeshHolder.transform.parent = this.gameObject.transform;
                DMBranches.Add(branch.Key, newBranchLayer);
            }

            //Draw all branches meshesB
            if (branch.Value.Vertices.Count > 0 && DMBranches[branch.Key].PrefabMeshes.Count > 0)
            {
                var dMBranch = DMBranches[branch.Key];

                var branchFinalMesh = DrawMesh(branch.Value, dMBranch);
                branchFinalMesh.RecalculateBounds();

                if (dMBranch.SmoothNormals)
                {
                    NormalSolver.RecalculateNormals(branchFinalMesh, dMBranch.SmoothNormalsAngle);
                }
                else
                {
                    branchFinalMesh.RecalculateNormals();
                }
                dMBranch.MeshHolder.GetComponent <MeshFilter>().sharedMesh = branchFinalMesh;
            }
        }


        foreach (var dMBranch in DMBranches.Reverse())
        {
            if (!SplinePlus.SPData.DictBranches.ContainsKey(dMBranch.Key))
            {
                MonoBehaviour.DestroyImmediate(dMBranch.Value.MeshHolder);
                DMBranches.Remove(dMBranch.Key);
            }
        }
        if (IsUpdateBase)
        {
            IsUpdateBase = false;
        }
    }
Ejemplo n.º 29
0
 internal void AddTownToListReversed(int pathlenght, Centers towncenter, Dictionary <Centers, Centers> camefrom)
 {
     if (!TownAlreadyMeasured(towncenter) || pathlenght < distancetoalltowns[towncenter].Distance)
     {
         reversecamefrom.Clear();
         foreach (KeyValuePair <Centers, Centers> node in camefrom.Reverse())
         {
             reversecamefrom[node.Value] = node.Key;
         }
         distancetoalltowns[towncenter] = (new TownDistance {
             Distance = pathlenght, town = towncenter, pathway = reversecamefrom
         });
     }
 }
Ejemplo n.º 30
0
    /// <summary>
    /// Updates the UI listing, it creates the necessary items not yet listed, update existing items and remove unused entries
    /// </summary>
    public void UpdateUI()
    {
        List <int> processedIDs = new List <int>();

        // Update existing slots and add new ones
        foreach (PhotonPlayer player in PhotonNetwork.playerList)
        {
            // Update existing slot
            if (_slots.ContainsKey(player.ID))
            {
                // Found ID, refresh data
                _slots[player.ID].RefreshData(player);

                // Add ID to processed IDs list
                processedIDs.Add(player.ID);

                Debug.Log("Player " + player.NickName + " already has a playerslot, updating existing slot...");
            }
            // Create new slot
            else
            {
                // Instantiate prefab and set data
                GameObject slot = Instantiate(_playerSlotPrefab, _playerSlotHolder);
                slot.transform.localScale    = Vector3.one;
                slot.transform.localPosition = new Vector3(slot.transform.localPosition.x, slot.transform.localPosition.y, 0);

                PlayerSlot playerSlot = slot.GetComponent <PlayerSlot>();
                playerSlot.RefreshData(player);

                // Add to dictionary
                _slots.Add(player.ID, playerSlot);

                // Add ID to processed IDs list
                processedIDs.Add(player.ID);

                Debug.Log("Creating a new PlayerSlot for player: " + player.NickName);
            }
        }

        // Remove playerslots of players that are no longer connected to the room
        foreach (var slot in _slots.Reverse())
        {
            if (!processedIDs.Contains(slot.Key))
            {
                _slots.Remove(slot.Key);
                Destroy(slot.Value.gameObject);
            }
        }
    }
        /// <summary>
        /// Finds the supervisor.
        /// </summary>
        /// <param name="nPlant">The n plant.</param>
        /// <param name="nonBlocking">if set to <c>true</c> [non blocking].</param>
        private void FindSupervisor(int nPlant, bool nonBlocking)
        {
            _numberOfRunningThreads = 0;
            _statesStack            = new Stack <StatesTuple>();
            _removeBadStates        = new Stack <bool>();

            _validStates = new Dictionary <StatesTuple, bool>(StatesTupleComparator.GetInstance());

            MakeReverseTransitions();

            var initialIndex = new StatesTuple(new int[_statesList.Count], _bits, _tupleSize);

            _statesStack.Push(initialIndex);
            _removeBadStates.Push(false);

            var vThreads = new Task[NumberOfThreads - 1];

            for (var i = 0; i < NumberOfThreads - 1; ++i)
            {
                vThreads[i] = Task.Factory.StartNew(() => FindStates(nPlant));
            }

            FindStates(nPlant);

            for (var i = 0; i < NumberOfThreads - 1; ++i)
            {
                vThreads[i].Wait();
            }

            foreach (var s in _validStates.Reverse())
            {
                if (s.Value)
                {
                    _validStates.Remove(s.Key);
                }
            }

            bool vNewBadStates;

            do
            {
                vNewBadStates = DepthFirstSearch(false, true);
                GC.Collect();
                if (nonBlocking)
                {
                    vNewBadStates |= RemoveBlockingStates(true);
                }
            } while (vNewBadStates);
        }
		/// <summary>
		/// Merge given dictionaries
		/// </summary>
		/// <param name="dictionaries">dictionaries to merge</param>
		/// <param name="overrideDueplicateWithLatterDictionaryValue">
		/// If true and duplicate key exists, then dupe key's values are overriden by latter dictionary values
		/// </param>
		public Dictionary<string, string> MergeDictionaries(
			Dictionary<int, Dictionary<string, string>> dictionaries, 
			bool overrideDueplicateWithLatterDictionaryValue = true)
		{
			Dictionary<string, string> result = new Dictionary<string, string>(dictionaries.Count);
			var query = overrideDueplicateWithLatterDictionaryValue ? dictionaries.Reverse() : dictionaries;

			foreach (var index in query)
			{
				Dictionary<string, string> d2 = index.Value;
				result = result.Concat(d2.Where(x => !result.Keys.Contains(x.Key))).ToDictionary(o => o.Key, o => o.Value);
			}

			return result;
		}
Ejemplo n.º 33
0
        /// <summary>
        /// Merge given dictionaries
        /// </summary>
        /// <param name="dictionaries">dictionaries to merge</param>
        /// <param name="overrideDueplicateWithLatterDictionaryValue">
        /// If true and duplicate key exists, then dupe key's values are overriden by latter dictionary values
        /// </param>
        public Dictionary <string, string> MergeDictionaries(
            Dictionary <int, Dictionary <string, string> > dictionaries,
            bool overrideDueplicateWithLatterDictionaryValue = true)
        {
            Dictionary <string, string> result = new Dictionary <string, string>(dictionaries.Count);
            var query = overrideDueplicateWithLatterDictionaryValue ? dictionaries.Reverse() : dictionaries;

            foreach (var index in query)
            {
                Dictionary <string, string> d2 = index.Value;
                result = result.Concat(d2.Where(x => !result.Keys.Contains(x.Key))).ToDictionary(o => o.Key, o => o.Value);
            }

            return(result);
        }
Ejemplo n.º 34
0
        public void RemoveBillBoard(Point bPoint, int billBoardSize)
        {
            bool check = false;
            Dictionary <Point, bool> tempBillBoarPoint = new Dictionary <Point, bool>(t.billBoardPoint);

            foreach (KeyValuePair <Point, bool> item in tempBillBoarPoint.Reverse())
            {
                if (item.Key == bPoint || (check == true && billBoardSize > 0))
                {
                    t.billBoardPoint[item.Key] = false;
                    billBoardSize--;
                    check = true;
                }
            }
        }
Ejemplo n.º 35
0
 public void RenameFolders()
 {
     RenameQueue.Reverse().ToList().ForEach(pair =>
     {
         try
         {
             Debug.WriteLine(pair.Key + " >> " + pair.Value);
             Directory.Move(pair.Key, pair.Value);
         }
         catch (Exception ex)
         {
             options.Logger.FatalLog(ex.ToString());
         }
     });
 }
Ejemplo n.º 36
0
        public string Convert(int arabicNumber)
        {
            _arabicNumber = arabicNumber;
            _romanNumeralBuilder.Clear();

            _romanNumberStore
            .Reverse()
            .ToList()
            .ForEach
            (
                i => romanNumeralAppender(i)
            );

            return(_romanNumeralBuilder.ToString());
        }
Ejemplo n.º 37
0
        private static void ParseNodeInternal(XElement element, DataSchemaKey key)
        {
            foreach (XElement el in element.Elements())
            {
                string name = el.Attribute("name").Value;
                switch (el.Name.LocalName)
                {
                    case "value" :
                        string mappedColumn = el.Value;
                        DataSchemaValue v = new DataSchemaValue(name, mappedColumn);
                        ParseNodeInternal(el, v);
                        key.AddChild(v);
                    break;

                    case "container" :
                        DataSchemaKey c = new DataSchemaKey(DataSchemaKeyType.Container, name);
                        ParseNodeInternal(el, c);
                        key.AddChild(c);
                    break;

                    case "iterator" :
                        int max = Int32.Parse(el.Attribute("maxItemCount").Value);
                        DataSchemaIterator i = new DataSchemaIterator(name, max);
                        ParseNodeInternal(el, i);
                        key.AddChild(i);
                    break;

                    case "iteratorValue" :
                        Dictionary<DataSchemaIterator,int> iterators = new Dictionary<DataSchemaIterator,int>();
                        FindIterators(key, iterators);
                        iterators.Reverse();
                        List<DataSchemaIteratorValueMappedColumn> columns = new List<DataSchemaIteratorValueMappedColumn>();
                        string tmpl = el.Value;
                        GenCoulumns(tmpl, iterators, columns, 0);
                        DataSchemaIteratorValue iv = new DataSchemaIteratorValue(name, columns);
                        ParseNodeInternal(el, iv);
                        key.AddChild(iv);
                    break;
                }
            }
        }
Ejemplo n.º 38
0
        async private void CompareButton_OnClick(object sender, RoutedEventArgs e)
        {
            if (File.Exists(OldFilePathTextBox.Text) == false || File.Exists(NewFilePathTextBox.Text) == false) {
                return;
            }
            OldFile = new FileInfo(OldFilePathTextBox.Text).FullName;
            NewFile = new FileInfo(NewFilePathTextBox.Text).FullName;
            CompareButton.Content = new Run("Comparing...");
            Task<Dictionary<string, string>> fastDiffTask = Task.Run(() =>
            {
                Dictionary<string, string> diffTableDictionary = new Dictionary<string, string>();
                //diffTableDictionary.Add("-----", string.Empty);
                using (SQLiteConnection connection = new SQLiteConnection(DAL.ConnectionString)) {
                    connection.Open();
                    //连接两个库
                    string attachSql = "ATTACH '" + OldFile + "' AS old;ATTACH '" + NewFile + "' AS new;";
                    SQLiteCommand attachCommand = new SQLiteCommand(attachSql, connection);
                    attachCommand.ExecuteNonQuery();
                    //循环每个表
                    foreach (MASTERDB type in Enum.GetValues(typeof(MASTERDB))) {
                        if (type == MASTERDB.LEVEL_DATA_MASTER) {
                            //地图表没啥比对价值
                            continue;
                        }
                        //检查表存在性
                        SQLiteCommand existCommand = new SQLiteCommand(string.Format(ExistSql, type.ToString()), connection);
                        int existCount = Convert.ToInt32(existCommand.ExecuteScalar());
                        if (existCount == 1) {
                            //只有一边存在
                            diffTableDictionary.Add("[New]" + type.ToString(), type.ToString());
                        }
                        else if (existCount == 2) {
                            //检查数据是否存在差异
                            int oldHasNew = 0, newHasNew = 0;
                            string hasDiffMark = string.Empty;
                            try {
                                existCommand.CommandText = string.Format(ExistInNewSql, type.ToString());
                                if (existCommand.ExecuteScalar() != null) {
                                    newHasNew = 1;
                                }
                                existCommand.CommandText = string.Format(ExistInOldSql, type.ToString());
                                if (existCommand.ExecuteScalar() != null) {
                                    oldHasNew = 1;
                                }
                                switch ((oldHasNew << 1) | newHasNew) {
                                    case 3: { hasDiffMark = "←→"; break; }
                                    case 2: { hasDiffMark = "← "; break; }
                                    case 1: { hasDiffMark = " →"; break; }
                                    default: break;
                                }
                            }
                            catch (Exception) {
                                //表结构发生变化
                                //todo 不出异常的解决方案
                                hasDiffMark = "Cng";
                            }


                            if (string.IsNullOrEmpty(hasDiffMark) == false) {
                                diffTableDictionary.Add("[" + hasDiffMark + "]" + type.ToString(), type.ToString());
                            }
                        }
                    }
                }
                //trick to add to dict first
                var reverseDict = diffTableDictionary.Reverse().ToDictionary(pair => pair.Key, pair => pair.Value);
                reverseDict.Add("Results:" + diffTableDictionary.Count, "");
                return reverseDict.Reverse().ToDictionary(pair => pair.Key, pair => pair.Value);
            });

            TableSelectComboBox.ItemsSource = await fastDiffTask;
            TableSelectComboBox.SelectedIndex = 0;
            CompareButton.Content = new Run("Compare");
        }
        private static string GetSubjectNameItemString(Dictionary<string, string> dic)
        {
            var rev = dic.Reverse();

            var sb = new StringBuilder();
            foreach (var item in rev)
            {
                sb.Append(item.Key + "=" + item.Value + ",");
            }
            sb.Length--;
            return sb.ToString();
        }
Ejemplo n.º 40
0
        public Playlist [] GetPlaylists (uint index, uint max_count, string order, bool reverse_order)
        {
            var playlist_sources = ServiceManager.SourceManager.FindSources<AbstractPlaylistSource> ();

            switch (order) {
                case "Alphabetical":
                    playlist_sources = playlist_sources.OrderBy (p => p.Name);
                    break;
                case "UserDefined":
                    playlist_sources = playlist_sources.OrderBy (p => p.Order);
                    break;
            }
            if (reverse_order) {
                playlist_sources = playlist_sources.Reverse ();
            }

            var playlists = new List<Playlist> ();
            foreach (var pl in playlist_sources.Skip ((int)index).Take ((int)max_count)) {
                playlists.Add (BuildPlaylistFromSource (pl));
            }
            return playlists.ToArray ();
        }
Ejemplo n.º 41
0
        public void TestDetermineHierarchy05()
        {
            DetermineHierarchyTest test = new DetermineHierarchyTest();

            // hierarchy mappings:
            // A > B > C
            //   > D > E > F
            // G > H

            TemplateInSet templateA = test.CreateTemplateInSet("A");
            TemplateInSet templateB = test.CreateTemplateInSet("B");
            TemplateInSet templateC = test.CreateTemplateInSet("C");
            TemplateInSet templateD = test.CreateTemplateInSet("D");
            TemplateInSet templateE = test.CreateTemplateInSet("E");
            TemplateInSet templateF = test.CreateTemplateInSet("F");
            TemplateInSet templateG = test.CreateTemplateInSet("G");
            TemplateInSet templateH = test.CreateTemplateInSet("H");

            Dictionary<TemplateInSetBase, IEnumerable<TemplateInSetBase>> mappings = new Dictionary<TemplateInSetBase, IEnumerable<TemplateInSetBase>>()
                {
                    {templateA, null},
                    {templateB, new TemplateInSet[] { templateA }},
                    {templateC, new TemplateInSet[] { templateB }},
                    {templateD, new TemplateInSet[] { templateA }},
                    {templateE, new TemplateInSet[] { templateD }},
                    {templateF, new TemplateInSet[] { templateE }},
                    {templateG, null},
                    {templateH, new TemplateInSet[] { templateG }}
                };
            mappings.Reverse();
            test.Run(mappings);

            Assert.IsNull(templateA.BaseTemplateInSet);
            Assert.IsNull(templateG.BaseTemplateInSet);

            Assert.AreSame(templateA, templateB.BaseTemplateInSet);
            Assert.AreSame(templateB, templateC.BaseTemplateInSet);
            Assert.AreSame(templateA, templateD.BaseTemplateInSet);
            Assert.AreSame(templateD, templateE.BaseTemplateInSet);
            Assert.AreSame(templateE, templateF.BaseTemplateInSet);
            Assert.AreSame(templateG, templateH.BaseTemplateInSet);
        }
Ejemplo n.º 42
0
 private string getParentName(Dictionary<string, int> jointOrderCollection, int index)
 {
     foreach (var item in jointOrderCollection.Reverse())
     {
         if (item.Value.Equals(index))
         {
             return item.Key;
         }
     }
     return String.Empty;
 }
Ejemplo n.º 43
0
        private static Dictionary<Game, int> MergeMatches(Dictionary<Game, int> matchList1, Dictionary<Game, int> matchList2)
        {
            var merged = new Dictionary<Game, int>();
            int team1Index = 0;
            foreach (var match in matchList1)
            {
                int team2Index = 0;
                foreach (var otherMatch in matchList2.Reverse())
                {
                    if(team2Index>team1Index)
                    {
                        break;
                    }
                    if(team1Index==team2Index)
                    {
                        merged.Add(new Game(match.Key.HomeTeam, otherMatch.Key.GuestTeam), match.Value);
                    }
                    team2Index++;
                }
                team1Index++;
            }

            return merged;
        }
Ejemplo n.º 44
0
        private Dictionary<string, double> BenjaminiHochberg(Dictionary<string, double> pvalueDict)
        {
            Dictionary<string, double> tempretDict = new Dictionary<string, double>();
            Dictionary<string, double> retDict = new Dictionary<string, double>();
            Dictionary<string, double> sortedDict = pvalueDict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

            int count = 1;
            foreach (KeyValuePair<string, double> kvp in sortedDict)
            {
                double qValue = kvp.Value * sortedDict.Values.Count / (count);
                tempretDict.Add(kvp.Key, qValue);

                count++;
            }

            Dictionary<string, double> reverseSortedDict = tempretDict.Reverse().ToDictionary(x => x.Key, x => x.Value);

            int i = 0;
            foreach (KeyValuePair<string, double> kvp in reverseSortedDict)
            {
                if (i != 0)
                {
                    if (retDict.ElementAt(i - 1).Value < kvp.Value)
                    {
                        retDict.Add(kvp.Key, retDict.ElementAt(i - 1).Value);
                    }
                    else
                    {
                        retDict.Add(kvp.Key, kvp.Value);
                    }
                }
                else
                {
                    retDict.Add(kvp.Key, kvp.Value);
                }

                i++;
            }

            return retDict;
        }
Ejemplo n.º 45
0
        public void TestDetermineHierarchyForContributingTemplates01()
        {
            DetermineHierarchyTest test = new DetermineHierarchyTest();

            // hierarchy mappings:
            // A > B > C
            //   > D > E > F
            // G >
            //     H > J
            // I >

            ContributingTemplateInSet templateA = test.CreateContributingTemplateInSet("A");
            ContributingTemplateInSet templateB = test.CreateContributingTemplateInSet("B");
            ContributingTemplateInSet templateC = test.CreateContributingTemplateInSet("C");
            ContributingTemplateInSet templateD = test.CreateContributingTemplateInSet("D");
            ContributingTemplateInSet templateE = test.CreateContributingTemplateInSet("E");
            ContributingTemplateInSet templateF = test.CreateContributingTemplateInSet("F");
            ContributingTemplateInSet templateG = test.CreateContributingTemplateInSet("G");
            ContributingTemplateInSet templateH = test.CreateContributingTemplateInSet("H");
            ContributingTemplateInSet templateI = test.CreateContributingTemplateInSet("I");
            ContributingTemplateInSet templateJ = test.CreateContributingTemplateInSet("J");

            Dictionary<TemplateInSetBase, IEnumerable<TemplateInSetBase>> mappings = new Dictionary<TemplateInSetBase, IEnumerable<TemplateInSetBase>>()
                {
                    {templateA, null},
                    {templateB, new ContributingTemplateInSet[] { templateA }},
                    {templateC, new ContributingTemplateInSet[] { templateB }},
                    {templateD, new ContributingTemplateInSet[] { templateA }},
                    {templateE, new ContributingTemplateInSet[] { templateD }},
                    {templateF, new ContributingTemplateInSet[] { templateE }},
                    {templateG, null},
                    {templateH, new ContributingTemplateInSet[] { templateG, templateI }},
                    {templateI, null},
                    {templateJ, new ContributingTemplateInSet[] { templateH }}
                };
            mappings.Reverse();
            test.Run(mappings);

            Assert.IsNull(templateA.BaseContributingTemplatesInSet);
            Assert.IsNull(templateG.BaseContributingTemplatesInSet);
            Assert.IsNull(templateI.BaseContributingTemplatesInSet);

            Assert.AreSame(templateA, templateB.BaseContributingTemplatesInSet.First());
            Assert.AreSame(templateB, templateC.BaseContributingTemplatesInSet.First());
            Assert.AreSame(templateA, templateD.BaseContributingTemplatesInSet.First());
            Assert.AreSame(templateD, templateE.BaseContributingTemplatesInSet.First());
            Assert.AreSame(templateE, templateF.BaseContributingTemplatesInSet.First());
            Assert.AreSame(templateH, templateJ.BaseContributingTemplatesInSet.First());
            Assert.IsTrue(templateH.BaseContributingTemplatesInSet.Contains(templateG));
            Assert.IsTrue(templateH.BaseContributingTemplatesInSet.Contains(templateI));

            Assert.IsFalse(templateC.BaseContributingTemplatesInSet.Contains(templateA));
            Assert.IsFalse(templateF.BaseContributingTemplatesInSet.Contains(templateD));
            Assert.IsFalse(templateF.BaseContributingTemplatesInSet.Contains(templateA));
            Assert.IsFalse(templateE.BaseContributingTemplatesInSet.Contains(templateA));
            Assert.IsFalse(templateJ.BaseContributingTemplatesInSet.Contains(templateG));
            Assert.IsFalse(templateJ.BaseContributingTemplatesInSet.Contains(templateI));
        }
Ejemplo n.º 46
0
 private static void Build(string file)
 {
     var jumpTable = new Dictionary<string, ushort>();
     string directory = Path.GetDirectoryName(Path.GetFullPath(file));
     string[] lines = File.ReadAllLines(file);
     bool waitEndIf = false;
     foreach (var _line in lines)
     {
         string line = _line.Trim();
         if (line.StartsWith("#") || string.IsNullOrEmpty(line))
             continue;
         if (waitEndIf)
         {
             if (line == "endif")
                 waitEndIf = false;
             else
                 continue;
         }
         if (line.StartsWith("asm "))
         {
             string[] parts = line.Split(' ');
             if (verbose)
                 Console.WriteLine("Assemling " + parts[1]);
             Spasm(Path.Combine(directory, parts[1]), Path.Combine(directory, parts[2]), null, configuration);
         }
         else if (line.StartsWith("if "))
             waitEndIf = configuration != line.Substring(3);
         else if (line.StartsWith("link "))
         {
             string[] parts = line.Split(' ');
             byte[] data = new byte[int.Parse(parts[3], NumberStyles.HexNumber)];
             for (int i = 0; i < data.Length; i++)
                 data[i] = 0xFF;
             using (Stream stream = File.Open(Path.Combine(directory, parts[1]), FileMode.Open))
                 stream.Read(data, 0, (int)stream.Length);
             output.Seek(int.Parse(parts[2], NumberStyles.HexNumber), SeekOrigin.Begin);
             output.Write(data, 0, data.Length);
             output.Flush();
         }
         else if (line.StartsWith("echo "))
             Console.WriteLine(line.Substring(5));
         else if (line.StartsWith("load "))
             LoadLabels(Path.Combine(directory, line.Substring(5)));
         else if (line.StartsWith("jump finish "))
         {
             // C3 34 12
             string[] parts = line.Split(' ');
             int tableAddress = int.Parse(parts[2], NumberStyles.HexNumber);
             output.Seek(tableAddress - (jumpTable.Count * 3), SeekOrigin.Begin);
             string include = "";
             foreach (var jumpValue in jumpTable.Reverse())
             {
                 byte[] value = BitConverter.GetBytes(jumpValue.Value);
                 include = jumpValue.Key + " .equ $" + ((ushort)output.Position).ToString("X4") + Environment.NewLine + include;
                 output.Write(new byte[]
                     {
                         0xC3, // jp
                         value[0],
                         value[1]
                     }, 0, 3);
             }
             include = ";This file was generated by a tool" + Environment.NewLine + include;
             File.WriteAllText(Path.Combine(directory, parts[3]), include);
         }
         else if (line.StartsWith("jump include "))
             jumpTable.Add(line.Substring(13), (ushort)labels[line.Substring(13).ToLower()]);
         else if (line.StartsWith("rm "))
         {
             string[] parts = line.Substring(3).Split(' ');
             foreach (var part in parts)
             {
                 if (File.Exists(Path.Combine(directory, part)))
                     File.Delete(Path.Combine(directory, part));
                 if (Directory.Exists(Path.Combine(directory, part)))
                     Directory.Delete(Path.Combine(directory, part), true);
             }
         }
         else if (line.StartsWith("cp"))
         {
             string[] parts = line.Substring(3).Split(' ');
             File.Copy(Path.Combine(directory, parts[0]), Path.Combine(directory, parts[1]));
         }
         else if (line.StartsWith("mkdir "))
             Directory.CreateDirectory(Path.Combine(directory, line.Substring(6)));
         else if (line.StartsWith("fscreate "))
             CreateFilesystem(Path.Combine(directory, line.Substring(9)));
         else if (line.StartsWith("pages "))
         {
             var parts = line.Substring(6).Split(' ');
             foreach (var part in parts)
                 AddPage(byte.Parse(part, NumberStyles.HexNumber));
         }
         else if (line == "endif") { }
         else
         {
             Console.WriteLine("Unknown build directive: " + line);
             throw new InvalidOperationException("Unknown build directive");
         }
     }
 }