コード例 #1
0
ファイル: CodeFileProcessor.cs プロジェクト: jrjohn/Grace
        public IEnumerable<ClassEntry> GetClassEntries(string filePath, ClassType classType)
        {
            List<string> lines = new List<string>(File.ReadAllLines(filePath));

            RemoveUsingAndNamspace(lines);

            int classIndex = lines.FindLastIndex(x => x.Contains("public class "));

            while (classIndex >= 0)
            {
                yield return ProcessExampleClass(lines, classIndex, classType);

                classIndex = lines.FindLastIndex(x => x.Contains("public class "));
            }
        }
コード例 #2
0
        private static void TrimToClass(List<string> answerLines)
        {
            var classDeclarationIndex = answerLines.FindIndex(x => x.Contains("public class Answer"));
            answerLines.RemoveRange(0, classDeclarationIndex + 2);

            var namespaceEndBracketIndex = answerLines.FindLastIndex(x => x.Contains("}"));
            var classEndBracketIndex = answerLines.FindLastIndex(namespaceEndBracketIndex - 1, x => x.Contains("}"));
            answerLines.RemoveRange(classEndBracketIndex, answerLines.Count - classEndBracketIndex);

            for (var lineIndex = 0; lineIndex < answerLines.Count; lineIndex++)
            {
                if (answerLines[lineIndex].Length >= 8)
                    answerLines[lineIndex] = answerLines[lineIndex].Substring(8);

                answerLines[lineIndex] = answerLines[lineIndex].Replace("Answer1", "Answer").Replace("Answer2", "Answer").Replace("Answer3", "Answer");
            }
        }
コード例 #3
0
 private void RemoveTrailingZeros(List<int> list)
 {
     for (int i = list.FindLastIndex(j => j != 0) + 1; i < list.Count; i++)
     {
         list.RemoveAt(i);
         i--;
     }
 }
コード例 #4
0
        public ScrollSubtitles GetScrolledSub(List<Subtitles> subs, int sec, int min, int hour)
        {
            VideoTime videotime = new VideoTime();
            var time = Convert.ToDateTime(videotime.PrintTime(sec, min, hour));

            int? sub = subs.FindLastIndex((x) => Convert.ToDateTime(x.Timebegin) < time && Convert.ToDateTime(x.Timeend) > time);

            if (sub != -1)
            {
                return new ScrollSubtitles(subs.ElementAt((int)sub).Text, subs.ElementAt((int)sub).Timeend, (int)sub);
            }
            else
            {
                return new ScrollSubtitles(string.Empty, string.Empty,
                subs.FindLastIndex((x) => Convert.ToDateTime(x.Timebegin) < time) + 1);
            }
        }
コード例 #5
0
        private List<IMigration> FilterOutLaterMigrations(string toVersion, List<IMigration> filteredMigrations)
        {
            var toIndex = filteredMigrations.FindLastIndex(migration => migration.Version == toVersion);
            if (toIndex != -1)
                filteredMigrations = filteredMigrations.Take(toIndex).ToList();

            return filteredMigrations;
        }
コード例 #6
0
        private void RemoveGymList(string namePerson, TypeWorkout arg)
        {
            var gymItem = GymList?.FindLastIndex((x => x.Name.Equals(namePerson)));

            if (gymItem == null)
            {
                return;
            }
            GymList.RemoveAt((int)gymItem);
        }
コード例 #7
0
 private string FindSummary(List<string> lines)
 {
     int index = lines.FindLastIndex(s => s.Contains(SummaryText));
     string results = "";
     if(index > -1)
     {
         results = lines[index];
     }
     return results;
 }
コード例 #8
0
ファイル: Program.cs プロジェクト: autozimu/gVimClient
        static void Main(string[] args)
        {
            string gvimbin = LocategVimBin();

            if (gvimbin == null)
            {
                Debug.WriteLine("gVimClient: no vim binary found.");
                return;
            }

            if (args.Length == 0)
            {
                Debug.WriteLine($"gVimClient: {gvimbin}");
                Process.Start(gvimbin);
            }
            else
            {
                // Insert --remote-tab-silent argument.
                List<string> argsList = new List<string>(args);
                int modifierIdx = 0;
                if (argsList.Exists(a => a.StartsWith("-")))
                {
                    modifierIdx = argsList.FindLastIndex(a => a.StartsWith("-"));
                }
                argsList.Insert(modifierIdx, "--remote-tab-silent");

                StringBuilder optsBuilder = new StringBuilder();
                foreach (string arg in args)
                {
                    if (arg.StartsWith("-"))
                    {
                        optsBuilder.Append($"{arg} ");
                    }
                    else
                    {
                        optsBuilder.Append($"\"{arg}\" ");
                    }
                }

                string opts = optsBuilder.ToString();
                Debug.WriteLine($"gVimClient: {gvimbin} {opts}");

                Process proc = Process.Start(gvimbin, opts);
                if (argsList.Contains("-f"))
                {
                    proc.WaitForExit();
                }
            }
        }
コード例 #9
0
        private void CheckSchedule(List<Job> schedule)
        {
            Scheduled = true;

            // Check if all deadlines are met
            foreach (var job in _jobs)
            {
                // If the job is not runned at all
                if (!schedule.Exists(t => t != null && t.Id == job.Id))
                {
                    Scheduled = false;
                    break;
                }
                else// Check if the job meets deadline
                {
                    if (job.Type == JobType.Aperiodic)
                    {
                        // Index indicates runtime of job in schedule list, 
                        // Example: if index of job is 0 then the job is runned from 0 to 1.
                        var lastRun = schedule.FindLastIndex(x => x != null && x.Id == job.Id) + 1;
                        if (lastRun > job.Deadline)
                        {
                            Scheduled = false;
                            break;
                        }
                    }
                    else
                    {// Periodic
                        var i = job.ArrivalTime;
                        while (i < schedule.Count)
                        {
                            // Calculate runtime between period
                            var periodOrRunTime = i + job.Period < schedule.Count ? job.Period : schedule.Count - i;
                            var runTime = schedule.GetRange(i, periodOrRunTime).Count(x => x != null && x.Id == job.Id);
                            // If the job didnt run for comp. time then it missed deadline.
                            if (runTime != job.ComputationTime)
                            {
                                Scheduled = false;
                                break;
                            }
                            // Next arrival time
                            i += job.Period;
                        }
                    }
                }
            }
        }
コード例 #10
0
        /// <summary>
        /// 定義されているオブジェクト・メソッド・クラスの中から検索し、参照を取得・設定します。
        /// </summary>
        /// <param name="name">キー</param>
        /// <returns>なければ<see cref="KecaknoahNil.Reference"/></returns>
        public KecaknoahReference GetReference(string name)
        {
            int idx = 0;

            if (GlobalObjects.ContainsKey(name))
            {
                return(GlobalObjects[name]);
            }
            if ((idx = topMethods.FindLastIndex(p => p.Name == name)) >= 0)
            {
                return(methodReferences[idx]);
            }
            if ((idx = classes.FindLastIndex(p => p.Name == name)) >= 0)
            {
                return(classReferences[idx]);
            }
            return(KecaknoahNil.Reference);
        }
コード例 #11
0
        private List <string> finalizeline(List <string> words)
        {
            List <string> result = new List <string>();

            // copy words
            words.ForEach(w => result.Add(w));
            // remove whitespace
            while (result.FindIndex(r => Regex.Match(r, "\\s").Success) == 0)
            {
                result.RemoveAt(0);
            }
            while (result.Count > 0 && result.FindLastIndex(r => Regex.Match(r, "\\s").Success) == result.Count - 1)
            {
                result.RemoveAt(result.Count - 1);
            }

            return(result);
        }
コード例 #12
0
        public SlotInput SetInputInSlot(int slotNumber, string input)
        {
            List <string> inputList        = GetInputList(input);
            int           wakeupFrameIndex = inputList.FindLastIndex(x => x.StartsWith(WakeUpFrameDelimiter.ToString()));

            if (wakeupFrameIndex < 0)
            {
                throw new Exception("No ! frame specified.  See the readme for more information.");
            }

            IEnumerable <short> inputShorts = GetInputShorts(inputList);

            var enumerable = inputShorts as short[] ?? inputShorts.ToArray();

            OverwriteSlot(slotNumber, enumerable);

            return(new SlotInput(input, enumerable, wakeupFrameIndex));
        }
コード例 #13
0
        // history filter, combat panel.  List should be in entry order.
        static public List <HistoryEntry> LatestFirstToLastDock(List <HistoryEntry> list)
        {
            int lastdock = list.FindLastIndex(x => !x.MultiPlayer && x.EntryType == JournalTypeEnum.Docked);

            if (lastdock >= 0)
            {
                List <HistoryEntry> tolastdock = new List <HistoryEntry>();
                for (int i = list.Count - 1; i >= lastdock; i--)     // go backwards so in lastest first order
                {
                    tolastdock.Add(list[i]);
                }
                return(tolastdock);
            }
            else
            {
                return(new List <HistoryEntry>());
            }
        }
コード例 #14
0
        static int GetActiveRuntimeIndex(List <RuntimeDetector> runtimes)
        {
            var runtimeJson = Environment.GetEnvironmentVariable("XR_RUNTIME_JSON");

            if (string.IsNullOrEmpty(runtimeJson))
            {
                return(0);
            }

            var index = runtimes.FindLastIndex(s => s.jsonPath.Equals(runtimeJson, StringComparison.CurrentCultureIgnoreCase));

            if (index == -1)
            {
                return(runtimes.Count - 1);
            }

            return(index);
        }
コード例 #15
0
        /// <summary>Updates the last target command used by the flight computer.</summary>
        private void UpdateLastTarget()
        {
            int lastTargetIndex = _commandQueue.FindLastIndex(c => (c is TargetCommand));

            if (lastTargetIndex >= 0)
            {
                LastTarget = _commandQueue[lastTargetIndex] as TargetCommand;
            }
            else if (_activeCommands.ContainsKey(LastTarget.Priority) &&
                     _activeCommands[LastTarget.Priority] is TargetCommand)
            {
                LastTarget = _activeCommands[LastTarget.Priority] as TargetCommand;
            }
            else
            {
                LastTarget = TargetCommand.WithTarget(null);
            }
        }
コード例 #16
0
        //Broken right now, smh

        /*public override int ChoosePrefix(Item item, UnifiedRandom rand)
         * {
         *  if ((item.modItem is KiItem && item.damage > 0) && item.maxStack == 1 && rand.NextBool(10))
         *  {
         *      return mod.PrefixType("CondensedPrefix");
         *  }
         *  if ((item.modItem is KiItem && item.damage > 0) && item.maxStack == 1 && rand.NextBool(60))
         *  {
         *      return mod.PrefixType("MystifyingPrefix");
         *  }
         *  if ((item.modItem is KiItem && item.damage > 0) && item.maxStack == 1 && rand.NextBool(30))
         *  {
         *      return mod.PrefixType("UnstablePrefix");
         *  }
         *  if ((item.modItem is KiItem && item.damage > 0) && item.maxStack == 1 && rand.NextBool(10))
         *  {
         *      return mod.PrefixType("BalancedPrefix");
         *  }
         *  if ((item.modItem is KiItem && item.damage > 0) && item.maxStack == 1 && rand.NextBool(5))
         *  {
         *      return mod.PrefixType("MasteredPrefix");
         *  }
         *  return -1;
         * }*/
        public override void ModifyTooltips(Item item, List <TooltipLine> tooltips)
        {
            if (!item.social && item.prefix > 0)
            {
                // try to find the end of the prefix indexes. If one can't be found, just slap it at the end?
                int index = tooltips.FindLastIndex(t => (t.mod == "Terraria" || t.mod == mod.Name) && (t.isModifier || t.Name.StartsWith("Tooltip")));
                if (index == -1)
                {
                    index = tooltips.Count - 1;
                }
                if (kiChangeBonus > 0)
                {
                    TooltipLine line = new TooltipLine(mod, "PrefixKiChange", "+" + kiChangeBonus + "% More Ki Usage");
                    line.isModifier    = true;
                    line.isModifierBad = true;
                    tooltips.Insert(index, line);
                }
                if (kiChangeBonus < 0)
                {
                    TooltipLine line = new TooltipLine(mod, "PrefixKiChange", kiChangeBonus + "% Less Ki Usage");
                    line.isModifier = true;
                    tooltips.Insert(index, line);
                }
                if (speedChangeBonus > 0)
                {
                    TooltipLine line = new TooltipLine(mod, "PrefixSpeedChange", "+" + speedChangeBonus + "% More cast speed");
                    line.isModifier = true;
                    tooltips.Insert(index, line);
                }
                if (speedChangeBonus < 0)
                {
                    TooltipLine line = new TooltipLine(mod, "PrefixSpeedChange", speedChangeBonus + "% Less cast speed");
                    line.isModifier    = true;
                    line.isModifierBad = true;
                    tooltips.Insert(index, line);
                }
                if (maxChargeBonus > 0)
                {
                    TooltipLine line = new TooltipLine(mod, "PrefixKiChange", "+" + maxChargeBonus + " Maximum charges");
                    line.isModifier = true;
                    tooltips.Insert(index, line);
                }
            }
        }
コード例 #17
0
        public void Teste()
        {
            list.Add("Maria");
            list.Add("Alex");
            list.Add("Bob");
            list.Add("Anna");
            list.Insert(2, "Marco");
            foreach (string obj in list)
            {
                Console.WriteLine(obj);
            }
            Console.WriteLine("List count: " + list.Count);
            string s1 = list.Find(x => x[0] == 'A');

            Console.WriteLine("First 'A': " + s1);
            string s2 = list.FindLast(x => x[0] == 'A');

            Console.WriteLine("Last 'A': " + s2);
            int pos1 = list.FindIndex(x => x[0] == 'A');

            Console.WriteLine("First position 'A': " + pos1);
            int pos2 = list.FindLastIndex(x => x[0] == 'A');

            Console.WriteLine("Last position 'A': " + pos2);
            List <string> list2 = list.FindAll(x => x.Length == 5);

            Console.WriteLine("---------------------");
            foreach (string obj in list2)
            {
                Console.WriteLine(obj);
            }
            list.Remove("Alex");
            Console.WriteLine("---------------------");
            foreach (string obj in list)
            {
                Console.WriteLine(obj);
            }
            list.RemoveAll(x => x[0] == 'M');
            Console.WriteLine("---------------------");
            foreach (string obj in list)
            {
                Console.WriteLine(obj);
            }
        }
コード例 #18
0
 /// <summary>
 /// Reports the zero-based index position of the last occurrence of a specified string within this instance.
 /// </summary>
 /// <param name="symbol">The string to seek.</param>
 /// <returns>The zero-based starting index position of value if that string is found, or -1 if it is not. If value is System.String.Empty, the return value is the last index position in this instance.</returns>
 /// <exception cref="ArgumentNullException">symbol should not be null.</exception>
 public int LastIndexOf(string symbol)
 {
     if (symbol == null)
     {
         throw new ArgumentNullException(nameof(symbol), "symbol was null");
     }
     symbol = symbol.Trim();
     if (symbol.Length < 1)
     {
         throw new ArgumentException("symbol was empty", nameof(symbol));
     }
     return(list.FindLastIndex(ele => symbol.Equals(ele.Element?.Symbol, StringComparison.OrdinalIgnoreCase)));
 }
コード例 #19
0
        static void Main(string[] args)
        {
            Console.WriteLine("************Using a generic collection list similar to arraylist************");
            List <int> li = new List <int>();

            li.Add(51);
            li.Add(7);
            li.Add(87);
            li.Add(78);
            li.Add(89);
            li.Add(75);
            li.Add(78);
            Console.WriteLine("**********FIND METHOD***********");
            int findRes = li.Find(x => x.Equals(12));

            Console.WriteLine("Finding 12 in the list :{0}", findRes);
            foreach (int i in li)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine("********findAll Method*******");
            List <int> findAllRes = li.FindAll(x => x.Equals(78));

            Console.WriteLine("Finding all elements as 78 :");
            foreach (var item in findAllRes)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("***********FindIndex Method*************");
            int findIndex = li.FindIndex(x => x.Equals(78));

            Console.WriteLine("Finding indexes of 78 :");
            Console.WriteLine(findIndex);
            Console.WriteLine("***********FindLast Method************");

            int findLast = li.FindLast(x => x.Equals(78));

            Console.WriteLine("Last element quals to 78 is :{0}", findLast);
            Console.WriteLine("********FindLastIndex Method*********");
            int findlastindex = li.FindLastIndex(x => x.Equals(78));

            Console.WriteLine(findlastindex);
            Console.Read();
        }
コード例 #20
0
 public int FindLastIndex(Predicate <T> match)
 {
     if (ThreadSafe)
     {
         lock ((this as ICollection).SyncRoot) {
             return(list.FindLastIndex(match));
         }
     }
     else
     {
         return(list.FindLastIndex(match));
     }
 }
コード例 #21
0
        public new void Add(T item)
        {
            List <T> list = this.ToList();

            int index = list.FindLastIndex(x => x.SectionHeader == item.SectionHeader);

            if (index < 0)
            {
                /*
                 *  item is the first of its kind, show
                 *  Todo We may also want to sort sections, for now we dont
                 */

                item.IsSectionHeader = true;
            }

            // Put the new item as the last in its section
            this.Insert(index + 1, item);
        }
コード例 #22
0
ファイル: RpcQueueTest.cs プロジェクト: Xenoage/RpcLib
        public async Task Enqueue_RemoveObsolete()
        {
            int    callsCount         = 100;
            string targetPeerID       = "TestClient";
            var    retryLatestMethods = new HashSet <string> {
                "Method5", "Method8"
            };
            var backlog = new JsonFileRpcBacklog(new DirectoryInfo(backlogDir));
            var queue   = await RpcQueue.Create(targetPeerID, backlog);

            var allCalls = new List <RpcCall>();

            // Enqueue
            for (int iCall = 0; iCall < callsCount; iCall++)
            {
                string methodName = "Method" + random.Next(10);
                var    retry      = retryLatestMethods.Contains(methodName)
                    ? RpcRetryStrategy.RetryLatest : RpcRetryStrategy.Retry;
                var call = CreateCall(methodName, targetPeerID, retry);
                allCalls.Add(call);
                await queue.Enqueue(call);

                await Task.Delay(50);
            }
            // Test backlog: Only last call of the RetryLatest methods must be there
            var backlogCalls = await backlog.ReadAll(targetPeerID);

            var callsWithoutObsolete = allCalls.Where((call, index) => {
                if (call.RetryStrategy == RpcRetryStrategy.RetryLatest)
                {
                    return(allCalls.FindLastIndex(it => it.Method.Name == call.Method.Name) == index);
                }
                return(true);
            }).ToList();

            CollectionAssert.AreEqual(callsWithoutObsolete, backlogCalls);
            // Test queue: All methods must still be there
            Assert.AreEqual(allCalls.Count, queue.Count);
            for (int i = 0; i < allCalls.Count; i++)
            {
                Assert.AreEqual(allCalls[i], await queue.Dequeue());
            }
        }
コード例 #23
0
        public HistoryEntry PreviousFrom(HistoryEntry e, bool fsdjumps)
        {
            if (e != null)
            {
                int curindex = historylist.IndexOf(e);

                if (curindex > 0)       // no point with index=0, there is no last.
                {
                    int lastindex = historylist.FindLastIndex(curindex - 1, x => (fsdjumps) ? x.IsFSDJump : true);

                    if (lastindex >= 0)
                    {
                        return(historylist[lastindex]);
                    }
                }
            }

            return(null);
        }
コード例 #24
0
ファイル: Reader.cs プロジェクト: PetX1996/ScriptOptimalizer
        private void ReadXMLArg(string line)
        {
            if (ReaderHelper.GetNextBlackChar(line, 0) != '<')
            {
                return;
            }

            if (line.IndexOf("/>") == -1) // start arg
            {
                int    argStartIndex = line.IndexOf('<') + 1;
                int    argEndIndex   = line.IndexOf(' ', argStartIndex);
                string argName       = line.Substring(argStartIndex, argEndIndex - argStartIndex);

                List <XMLAttribute> atts = new List <XMLAttribute>();
                int attEquals            = 0;
                while (true)
                {
                    attEquals = line.IndexOf('=', attEquals + 1);
                    if (attEquals == -1)
                    {
                        break;
                    }

                    int    attNameStart = line.LastIndexOf(' ', attEquals) + 1;
                    string attName      = line.Substring(attNameStart, attEquals - attNameStart);

                    int    attValueEnd = line.IndexOf('"', attEquals + 2);
                    string attValue    = line.Substring(attEquals + 2, attValueEnd - (attEquals + 2));
                    atts.Add(new XMLAttribute(attName, attValue));
                }

                LIST_XMLArgs.Add(new XMLArg(argName, atts));
            }
            else
            {
                int    argStartIndex = line.IndexOf('<') + 1;
                int    argEndIndex   = line.IndexOf("/>", argStartIndex);
                string argName       = line.Substring(argStartIndex, argEndIndex - argStartIndex);

                int argIndex = LIST_XMLArgs.FindLastIndex(a => a.Name == argName);
                LIST_XMLArgs.RemoveAt(argIndex);
            }
        }
コード例 #25
0
        private static IEnumerable <CodeInstruction> Transpiler(IEnumerable <CodeInstruction> instructions, ILGenerator generator)
        {
            List <CodeInstruction> newInstructions = ListPool <CodeInstruction> .Shared.Rent(instructions);

            int          offset      = 1;
            int          index       = newInstructions.FindIndex(instruction => instruction.opcode == OpCodes.Brtrue_S) + offset;
            Label        returnLabel = generator.DefineLabel();
            Label        valueLabel  = generator.DefineLabel();
            LocalBuilder ev          = generator.DeclareLocal(typeof(DeactivatingWorkstationEventArgs));

            newInstructions.InsertRange(index, new[]
            {
                new CodeInstruction(OpCodes.Ldarg_1),
                new CodeInstruction(OpCodes.Ldc_I4_2),
                new CodeInstruction(OpCodes.Bne_Un_S, valueLabel),
                new CodeInstruction(OpCodes.Ldarg_0),
                new CodeInstruction(OpCodes.Ldc_I4_1),
                new CodeInstruction(OpCodes.Newobj, GetDeclaredConstructors(typeof(DeactivatingWorkstationEventArgs))[0]),
                new CodeInstruction(OpCodes.Dup),
                new CodeInstruction(OpCodes.Dup),
                new CodeInstruction(OpCodes.Stloc_S, ev.LocalIndex),
                new CodeInstruction(OpCodes.Call, Method(typeof(Handlers.Player), nameof(Handlers.Player.OnDeactivatingWorkstation))),
                new CodeInstruction(OpCodes.Callvirt, PropertyGetter(typeof(DeactivatingWorkstationEventArgs), nameof(DeactivatingWorkstationEventArgs.IsAllowed))),
                new CodeInstruction(OpCodes.Brfalse_S, returnLabel),
                new CodeInstruction(OpCodes.Ldloc_S, ev.LocalIndex),
                new CodeInstruction(OpCodes.Callvirt, PropertyGetter(typeof(DeactivatingWorkstationEventArgs), nameof(DeactivatingWorkstationEventArgs.NewStatus))),
                new CodeInstruction(OpCodes.Starg_S, 1),
            });

            offset = -1;
            index  = newInstructions.FindLastIndex(instruction => instruction.opcode == OpCodes.Ldfld) + offset;

            newInstructions[index].WithLabels(valueLabel);

            newInstructions[newInstructions.Count - 1].WithLabels(returnLabel);

            for (int z = 0; z < newInstructions.Count; z++)
            {
                yield return(newInstructions[z]);
            }

            ListPool <CodeInstruction> .Shared.Return(newInstructions);
        }
コード例 #26
0
ファイル: Board.cs プロジェクト: rfrfrf/connect4neuralnetwork
        // column should be an integer in [0-6]
        public Checker RemoveChecker(int column)
        {
            for (int row = 0; row < Rows; row++)
            {
                Checker checker = Cells[row, column];
                if (checker != Checker.Empty)
                {
                    Cells[row, column] = Checker.Empty;
                    int lastindex = MoveHistory.FindLastIndex(e => e == column);
                    if (lastindex != -1)
                    {
                        MoveHistory.RemoveAt(lastindex);
                    }

                    return(checker);
                }
            }
            return(0);
        }
コード例 #27
0
        public (SectionedIndex index, bool needsNewSection) InsertItem(TItem item)
        {
            var sectionIndex = sections.GroupIndexOf(item, groupingKey);

            if (sectionIndex == -1)
            {
                var          insertionIndex = sections.FindLastIndex(g => areInOrder(g.First(), item, groupingKey));
                List <TItem> list           = new List <TItem> {
                    item
                };
                sections.Insert(insertionIndex + 1, list); // when there are no sections the insertionIndex will be -1
                return(new SectionedIndex(insertionIndex + 1, 0), true);
            }

            var rowIndex = sections[sectionIndex].FindLastIndex(i => areInOrder(i, item, orderingKey));

            sections[sectionIndex].Insert(rowIndex + 1, item); // when the section is empty, the rowIndex will be -1
            return(new SectionedIndex(sectionIndex, rowIndex + 1), false);
        }
コード例 #28
0
        private string GenerateTicks(List <Tuple <DateTime, int> > values)
        {
            string ticks = string.Empty;

            int first = (values.FindIndex(x => x.Item2 != 0));
            int last  = (values.FindLastIndex(x => x.Item2 != 0));

            for (int i = first; i <= last; i = i + 2)
            {
                ticks += "'" + values[i].Item1.ToString(Settings.FORMAT_TIME) + "',";
            }

            if (!ticks.Equals(string.Empty))
            {
                ticks = ticks.Substring(0, ticks.Length - 1);
            }

            return(ticks);
        }
コード例 #29
0
        public List <SemanticAnswer> Evaluate(List <Token> token)
        {
            List <SemanticAnswer> result = new List <SemanticAnswer>();
            int equalIndex     = token.FindLastIndex(token => token.IsSymbol(Context.symbol_equal));
            var idToken        = token[equalIndex - 1];
            var assignationSet = Context.Instance.Assignations;

            if (assignationSet.Contains(idToken.Lexeme))
            {
                result.Add(new SemanticAnswer(AnswerType.Warning, string.Format("\"{0}\": Reassignation", idToken.Lexeme)));
                return(result);
            }
            else
            {
                assignationSet.Add(idToken.Lexeme);
                result.Add(new SemanticAnswer(AnswerType.Valid, string.Format("\"{0}\": Assignation", idToken.Lexeme)));
                return(result);
            }
        }
コード例 #30
0
        public static void Executar()
        {
            List <string> list = new List <string>(); //Instanciando a Lista

            list.Add("Maria");                        //Adicionando em ordem normal
            list.Add("Jose");
            list.Add("Mateus");
            list.Add("Anna");
            list.Add("Stefanie");
            list.Insert(2, "Darn");       //Usando Insert, tu pode determina a posição q vai entra o item
            foreach (string nome in list)
            {
                Console.WriteLine(nome);                         //Lendo os itens da Lista
            }
            Console.WriteLine("Nomes na lista : " + list.Count); //Count pra ver tamanho
            string first = list.Find(x => x[0] == 'M');          // encontra primeiro predicado satisfeito

            Console.WriteLine("primeiro com letra M " + first);

            string last = list.FindLast(x => x[0] == 'M'); //encontra o ultimo predicado satisfeito

            Console.WriteLine("ultimo com letra M " + last);

            int pos1 = list.FindIndex(x => x[0] == 'M'); //Encontra a posição do predicado definido

            Console.WriteLine("Primeira posição com letra M " + pos1);

            int pos2 = list.FindLastIndex(x => x[0] == 'M');//ultima posição do predicado definido

            Console.WriteLine("Ultima posição com letra M " + pos2);

            List <string> list2 = list.FindAll(x => x.Length == 4); // Listando aqueles q atendem o predicado

            foreach (string nome in list2)
            {
                Console.WriteLine(nome);
            }

            //list.Remove(); Serve pra remover normal
            //list.RemoveAt(2) remove na posição declarada
            //list.RemoveRange(2 , 2) passa apartir de quando remover, depois quantos remover
            //list.RemoveAll( x => x[0] == 'M' Remove todos com algum predicado desde q o mesmo seja satisfeito
        }
コード例 #31
0
        public void FindLastIndexTest2()
        {
            DynamicArray <int> array = new DynamicArray <int>();
            List <int>         list  = new List <int>();

            FillCollections(array, list);

            ActionTest(array, list, testableAction);

            void testableAction(int randomElement)
            {
                int index = RandomTestsUtils.Random.Next(array.Count);

                if (array.FindLastIndex(index, a => a <= randomElement) != list.FindLastIndex(index, a => a <= randomElement))
                {
                    Assert.Fail();
                }
            }
        }
コード例 #32
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //最後のクリック削除
            StrokeCodeList.RemoveRange(StrokeCodeList.Count - 2, 2);
            // 最後のクリックまでの移動削除
            int ix = StrokeCodeList.FindLastIndex(x => x.IndexOf("stroke.MouseModeTo") == -1);

            StrokeCodeList.RemoveRange(ix + 1, StrokeCodeList.Count - (ix + 1));
            StrokeCodeList.Add(
                "    stroke.Send();\n" +
                "}");

            StrokeCode = string.Join("", StrokeCodeList);

            MouseHook.Stop();
            KeyboardHook.Stop();
            DialogResult = true;
            Close();
        }
コード例 #33
0
 private int FindLastTrackIndexFromPlaylist(int currentIndex, List <Track> sourcePlaylist, List <Track> playbackPlaylist)
 {
     if (currentIndex >= 0)
     {
         var lastPlaybackIndex = playbackPlaylist.FindLastIndex(currentIndex, x => sourcePlaylist.Any(t => t.Id == x.Id));
         if (lastPlaybackIndex < 0)
         {
             return(lastPlaybackIndex);
         }
         else
         {
             return(sourcePlaylist.FindIndex(x => x.Id == playbackPlaylist[lastPlaybackIndex].Id));
         }
     }
     else
     {
         return(currentIndex);
     }
 }
コード例 #34
0
	//Loads a view/screen, scrolls the view to the bottom if scrollTo is set to 0.0f, scrolls to a given position otherwise, default value scrolls to 1.0f (top)
	public void LoadApp(string appName, bool openOnTop = true)
	{
		//Always compare lowercase names
		appName = appName.ToLower();

		AbstractApp app = existingApps[appName];

		//If the app is not on top of the stack
		if (GetCurrentAppName() != appName) {
			//Find if it's somewhere else in the stack
			int index = stack.FindLastIndex(a => a.name == app.name);
			if (index != -1) {
				//If yes: remove it so it can be added on top of the stack
				stack.RemoveAt(index);
			}

			//Add the app to the stack
			stack.Add(app);
		} else {
			//The app is already on top of the stack: make sure we're not putting it on the top layer again by accident :o
			openOnTop = false;
		}

		//Move the app on the top layer if needed
		if (openOnTop) {
			app.transform.SetAsLastSibling();
		}

		//If there is an app on the stack already, we'll need to remember it so we can hide it when the new app opens
		AbstractApp previousApp = null;
		if (stack.Count > 1) {
			previousApp = stack[stack.Count - 2];
		}

		//Resume the app (and animate it, if it's being moved to the top layer, meaning it wasn't already visible)
		app.ResumeApp();

		//Hide the previous app (if it exists) once the new one has finished its animation
		if (previousApp != null)
		{
			previousApp.PauseApp();
		}
	}
コード例 #35
0
        /// <summary>
        ///     данные о имени  пвп должны быть назначенны зарание
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="candidat"></param>
        /// <param name="setCcToData"></param>
        /// <returns></returns>
        public List <CandidatOut> RegisterCandidate(IDbConnection connection, CandidatOut candidat,
                                                    Action <int> setCcToData)
        {
            candidat.ValidateRegistrate();
            var ccModel = _storeService.BalanceCalcResultCc(connection, candidat.UserId, REGISTER_CANDIDATE_CC_PRICE);
            List <CandidatOut> candidates = null;
            var hasError = false;

            candidates =
                _officerCandidatRepository.GetRegistredOfficerCandidatesByTopPvp(connection, MAX_CANDIDATES_COUNT);

            var minPvp = candidates.Min(i => i.PvpPoint);

            if (candidates.Count == 0 || candidates.Min(i => i.PvpPoint) < candidat.PvpPoint)
            {
                if (_isExistCandidate(connection, candidat.UserId))
                {
                    throw new Exception(Error.CantRegisterCandidatAlreadyExist);
                }

                _createAndSaveNewCandidate(connection, candidat, false);
                if (candidates.Count == MAX_CANDIDATES_COUNT)
                {
                    var idx = candidates.FindLastIndex(i => i.PvpPoint == minPvp);
                    candidates.RemoveAt(idx);
                }
                candidates.Add(candidat);
            }
            else
            {
                hasError = true;
            }

            if (hasError)
            {
                throw new Exception(Error.CantRegisterCandidatNotEnoughPvP);
            }
            // todo переместить в один коннекшен
            var newBalance = _storeService.AddOrUpdateBalance(connection, ccModel);

            setCcToData(newBalance.Quantity);
            return(candidates.OrderByDescending(i => i.PvpPoint).ToList());
        }
コード例 #36
0
        public List <SemanticAnswer> Evaluate(List <Token> token)
        {
            List <SemanticAnswer> result = new List <SemanticAnswer>();
            int index   = token.FindLastIndex(x => x.IsSymbol(Context.symbol_openParenthesis)) - 1;
            var tokenID = token[index];

            var functions = Context.Instance.Functions;

            if (functions.Contains(tokenID.Lexeme))
            {
                result.Add(new SemanticAnswer(AnswerType.Valid, string.Format("Function call \"{0}\" OK", tokenID.Lexeme)));
                return(result);
            }
            else
            {
                result.Add(new SemanticAnswer(AnswerType.Warning, string.Format("Function call \"{0}\" recursive, extern or not defined", tokenID.Lexeme)));
                return(result);
            }
        }
コード例 #37
0
        private static IEnumerable <CodeInstruction> Transpiler(IEnumerable <CodeInstruction> instructions, ILGenerator generator)
        {
            List <CodeInstruction> newInstructions = ListPool <CodeInstruction> .Shared.Rent(instructions);

            const int offset = 0;

            // Search for the last "ldarg.0".
            int index = newInstructions.FindLastIndex(instruction => instruction.opcode == OpCodes.Ldarg_0) + offset;

            // Get the count to find the previous index
            int oldCount = newInstructions.Count;

            // Get the return label from the last instruction.
            object returnLabel = newInstructions[index - 1].operand;

            // var ev = new StartingEventArgs(Server.Host, true);
            //
            // Handlers.Warhead.OnStarting(ev);
            //
            // if (!ev.IsAllowed)
            //   return;
            newInstructions.InsertRange(index, new[]
            {
                new CodeInstruction(OpCodes.Call, PropertyGetter(typeof(Server), nameof(Server.Host))),
                new CodeInstruction(OpCodes.Ldc_I4_1),
                new CodeInstruction(OpCodes.Newobj, GetDeclaredConstructors(typeof(StartingEventArgs))[0]),
                new CodeInstruction(OpCodes.Dup),
                new CodeInstruction(OpCodes.Call, Method(typeof(Handlers.Warhead), nameof(Handlers.Warhead.OnStarting))),
                new CodeInstruction(OpCodes.Call, PropertyGetter(typeof(StartingEventArgs), nameof(StartingEventArgs.IsAllowed))),
                new CodeInstruction(OpCodes.Brfalse_S, returnLabel),
            });

            // Add the starting labels to the first injected instruction.
            // Calculate the difference and get the valid index - is better and easy than using a list
            newInstructions[index].MoveLabelsFrom(newInstructions[newInstructions.Count - oldCount + index]);

            for (int z = 0; z < newInstructions.Count; z++)
            {
                yield return(newInstructions[z]);
            }

            ListPool <CodeInstruction> .Shared.Return(newInstructions);
        }
コード例 #38
0
        private void SplitPaths(List <SubPath> paths, List <ConversionPath> curPath, List <ConversionPath[]> outp)
        {
            for (int i = 0; i < paths.Count; i++)
            {
                curPath.Add(paths[i].Path);

                if (paths[i].Sub == null)
                {
                    outp.Add(curPath.ToArray());
                }
                else
                {
                    SplitPaths(paths[i].Sub, curPath, outp);
                }

                int idx = curPath.FindLastIndex(t => t == paths[i].Path);
                curPath.RemoveAt(idx);
            }
        }
コード例 #39
0
ファイル: Program.cs プロジェクト: rokn/HackBulgaria
        static List<int> BirthdayRanges(List<int> birthdays, List<KeyValuePair<int, int>> ranges)
        {
            List<int> result = new List<int>();
            List<int> sortedBirthdays = new List<int>(birthdays);
            sortedBirthdays.Sort();

            foreach (var kvp in ranges)
            {
                int start = sortedBirthdays.FindIndex(day => day >= kvp.Key && day <= kvp.Value);
                int end = sortedBirthdays.FindLastIndex(day => day >= kvp.Key && day <= kvp.Value);

                if(start < 0)
                {
                    result.Add(0);
                    continue;
                }

                result.Add((end - start) + 1);
            }

            return result;
        }
コード例 #40
0
ファイル: ComplexMatcher.cs プロジェクト: KinTT/BeatCare
   public List<Peak> MatchQST(List<double> Complex, int RPeakIdx, int ComplexDelay, int GlobalTic)
   {
       if (Complex.Count <= 1)
           return new List<Peak>(0);
       int num1 = Complex.Count - RPeakIdx;
       int num2 = RPeakIdx + Convert.ToInt32(Math.Round((double)num1 * this.ExpectedTPeak / this.ExpectedRRInterval)) + 1;
       List<double> range1 = Complex.GetRange(RPeakIdx, num2 - RPeakIdx + 1);
       int val2 = Array.IndexOf<double>(range1.ToArray(), Enumerable.Min((IEnumerable<double>)range1)) + RPeakIdx;
       int index1 = Math.Max(num2 - this.Window, val2);
       int num3 = Math.Min(num2 + this.Window, Complex.Count - 1);
       List<double> range2 = Complex.GetRange(index1, num3 - index1 + 1);
       int index2 = Array.IndexOf<double>(range2.ToArray(), Enumerable.Max((IEnumerable<double>)range2)) + index1;
       List<double> list1 = new List<double>();
       for (int index3 = 1; index3 < Complex.Count; ++index3)
           list1.Add(Complex[index3] - Complex[index3 - 1]);
       List<double> range3 = Complex.GetRange(RPeakIdx, index2 - RPeakIdx + 1);
       int index4 = Array.IndexOf<double>(range3.ToArray(), Enumerable.Min((IEnumerable<double>)range3)) + RPeakIdx;
       int index5 = list1.FindLastIndex(RPeakIdx - 1, RPeakIdx - 1, (Predicate<double>)(X => X < 0.0)) + 1;
       int index6 = Math.Max(Complex.Count - (int)this.ExpectedPPeak, 0);
       int count1 = Math.Min((int)this.ExpectedPPeak, Complex.Count - 1);
       List<double> range4 = Complex.GetRange(index6, count1);
       int num4 = Complex.Count + ComplexDelay;
       List<Peak> list2 = new List<Peak>()
 {
   new Peak(PeakType.QPeak, index5 - num4, GlobalTic - num4 + index5, Complex[index5]),
   new Peak(PeakType.SPeak, index4 - num4, GlobalTic - num4 + index4, Complex[index4]),
   new Peak(PeakType.TPeak, index2 - num4, GlobalTic - num4 + index2, Complex[index2])
 };
       if (range4.Count > 0)
       {
           int count2 = index6 + Array.IndexOf<double>(range4.ToArray(), Enumerable.Min((IEnumerable<double>)range4)) - index6 + 1;
           List<double> range5 = Complex.GetRange(index6, count2);
           int index3 = index6 + Array.IndexOf<double>(range5.ToArray(), Enumerable.Max((IEnumerable<double>)range5));
           list2.Add(new Peak(PeakType.PPeak, index3 - num4, GlobalTic - num4 + index3, Complex[index3]));
       }
       return list2;
   }
コード例 #41
0
        // centresysname is a default one
        public static string FindNextVisitedSystem(List<VisitedSystemsClass> _visitedSystems, string sysname, int dir, string centresysname)
        {
            int index = _visitedSystems.FindIndex(x => x.Name.Equals(sysname));

            if (index != -1)
            {
                if (dir == -1)
                {
                    if (index < 1)                                  //0, we go to the end and work from back..
                        index = _visitedSystems.Count;

                    int indexn = _visitedSystems.FindLastIndex(index - 1, x => x.HasTravelCoordinates || (x.curSystem != null && x.curSystem.HasCoordinate));

                    if (indexn == -1)                             // from where we were, did not find one, try from back..
                        indexn = _visitedSystems.FindLastIndex(x => x.HasTravelCoordinates || (x.curSystem != null && x.curSystem.HasCoordinate));

                    return (indexn != -1) ? _visitedSystems[indexn].Name : centresysname;
                }
                else
                {
                    index++;

                    if (index == _visitedSystems.Count)             // if at end, go to beginning
                        index = 0;

                    int indexn = _visitedSystems.FindIndex(index, x => x.HasTravelCoordinates || (x.curSystem != null && x.curSystem.HasCoordinate));

                    if (indexn == -1)                             // if not found, go to beginning
                        indexn = _visitedSystems.FindIndex(x => x.HasTravelCoordinates || (x.curSystem != null && x.curSystem.HasCoordinate));

                    return (indexn != -1) ? _visitedSystems[indexn].Name : centresysname;
                }
            }
            else
            {
                index = _visitedSystems.FindLastIndex(x => x.HasTravelCoordinates || (x.curSystem != null && x.curSystem.HasCoordinate));
                return (index != -1) ? _visitedSystems[index].Name : centresysname;
            }
        }
コード例 #42
0
ファイル: MojangService.cs プロジェクト: AMerkuri/MCNotifier
 private DateTime GetLastTimeUsernameChangedTime(List<MojangProfileHistory> profileHistory, string username)
 {
     var index = profileHistory.FindLastIndex(x => string.Equals(x.Name, username, StringComparison.OrdinalIgnoreCase));
     return ((long) profileHistory[index + 1].ChangedToAt).GetDateTimeFromUnixDate();
 }
コード例 #43
0
		private static IEnumerable<Token> CreatePostfixTokenList(List<Token> tokens, Dictionary<string, Expression> variableMap)
		{
			tokens = InsertImpliedMultiplication(tokens);

			// https://en.wikipedia.org/wiki/Shunting-yard_algorithm

			var outputQueue = new List<Token>();
			var stack = new Stack<Token>();

			for (var index = 0; index < tokens.Count; index++)
			{
				var currentToken = tokens[index];

				// If the token is a number, then add it to the output queue.
				if (currentToken.Type.IsOperand())
				{
					outputQueue.Add(currentToken);
				}

				// If the token is a function token, then push it onto the stack.
				else if (currentToken.Type == TokenType.Function)
				{
					if (FunctionRepository.Get(currentToken.Value).FixType == FixType.PreFix)
					{
						outputQueue.Add(currentToken);
					}
					else
					{
						stack.Push(currentToken);
					}
				}

				// If the token is a function argument separator (e.g., a comma):
				else if (currentToken.Type == TokenType.Comma)
				{
					// Until the token at the top of the stack is a left parenthesis,
					// pop operators off the stack onto the output queue.
					while (stack.Peek().Type != TokenType.OpenParenthesis)
					{
						outputQueue.Add(stack.Pop());
					}

					// If no left parentheses are encountered, either the separator
					// was misplaced or parentheses were mismatched.
				}

				// If the token is an operator, o1, then:
				else if (currentToken.Type.IsOperator())
				{
					// while there is an operator token o2, or a function token fun,
					// at the top of the operator stack:
					while (stack.Any() && (stack.Peek().Type.IsOperator() || stack.Peek().Type == TokenType.Function))
					{
						var somethingChanged = false;

						// if it is a function token then pop fun off the operator 
						// stack, onto the output queue;
						if (stack.Peek().Type == TokenType.Function)
						{
							outputQueue.Add(stack.Pop());
							somethingChanged = true;
						}

						// if on the other hand it is an operator token, and either
						//    o1 is left-associative and its precedence is less than or equal to that of o2, or
						//    o1 is right associative, and has precedence less than that of o2,
						// then pop o2 off the operator stack, onto the output queue;
						else
						{
							var topType = stack.Peek().Type;
							if (topType.IsOperator())
							{
								var o1Associativity = currentToken.Type.Associativity();
								var o1Precedence = currentToken.Type.Precedence();
								var o2Precedence = topType.Precedence();

								if ((o1Associativity == OperatorAssociativity.Left && o1Precedence <= o2Precedence) ||
								    (o1Associativity == OperatorAssociativity.Right && o1Precedence < o2Precedence))
								{
									outputQueue.Add(stack.Pop());
									somethingChanged = true;
								}
							}
						}

						if (!somethingChanged) break;
					}

					// at the end of iteration push o1 onto the operator stack.
					stack.Push(currentToken);
				}

				// If the token is a left parenthesis (i.e. "("), then push it onto the stack.
				else if (currentToken.Type == TokenType.OpenParenthesis)
				{
					stack.Push(currentToken);
				}

				// If the token is a right parenthesis (i.e. ")"):
				else if (currentToken.Type == TokenType.CloseParenthesis)
				{
					// Until the token at the top of the stack is a left parenthesis,
					// pop operators off the stack onto the output queue.
					while (stack.Any() && stack.Peek().Type != TokenType.OpenParenthesis)
					{
						outputQueue.Add(stack.Pop());
					}

					// Pop the left parenthesis from the stack, but not onto the output queue.
					stack.Pop();

					// If the token at the top of the stack is a function token, pop it onto the output queue.
					if (stack.Any() && stack.Peek().Type == TokenType.Function)
					{
						outputQueue.Add(stack.Pop());
					}

					// If the stack runs out without finding a left parenthesis,
					// then there are mismatched parentheses.
				}

				else if (currentToken.Type == TokenType.OpenBrace)
				{
					var indexOfCloseBrace = tokens.FindLastIndex(t => t.Type == TokenType.CloseBrace);
					var tokenSubstring = tokens.Skip(index + 1).Take(indexOfCloseBrace - index - 1).ToList();

					if (tokenSubstring.Count > 0)
					{
						var operands = ParseCommaSeparatedList(tokenSubstring, variableMap).ToList();
						var list = new ExpressionListToken(new ExpressionList(operands));
						outputQueue.Add(list);
					}
					else
					{	// Special case for empty lists
						outputQueue.Add(new ExpressionListToken(new ExpressionList(new List<Expression>())));
					}

					index = indexOfCloseBrace;
				}

				else if (currentToken.Type == TokenType.CloseBrace)
				{
					throw new SyntaxErrorException("Mismatched braces");
				}

				else
				{
					throw new SyntaxErrorException("Unexpected token", currentToken.Value);
				}
			}

			// When there are no more tokens to read:
			// While there are still operator tokens in the stack:
			while (stack.Any())
			{
				// If the operator token on the top of the stack is a parenthesis,
				// then there are mismatched parentheses.
				if (stack.Peek().Type == TokenType.OpenParenthesis || stack.Peek().Type == TokenType.CloseParenthesis)
				{
					throw new SyntaxErrorException("Mismatched parentheses");
				}

				// Pop the operator onto the output queue.
				outputQueue.Add(stack.Pop());
			}

			return outputQueue;
		}
コード例 #44
0
ファイル: DFATuring.cs プロジェクト: ptr92zet/Math-Lingustics
        public void InitializeTape(List<string> initList)
        {
            this.tape = new List<string>(maxTapeLength);
            foreach (string symbol in initList)
            {
                this.tape.Add(symbol);
            }
            IsTapeInitialized = true;
            int lastIndex = tape.FindLastIndex(FindLastSymbol);
            for (int i=lastIndex+1; i<maxTapeLength; i++)
            {
                this.tape.Add("#");
            }
            Console.WriteLine(lastIndex);
            Console.WriteLine(Tape);

        }
コード例 #45
0
        private string creatpointinfo(string[] instcoodrow,int pp,List<string> abc)
        {
            string instcood = instcoodrow[0].Trim() + "," + instcoodrow[1].Replace(")", "").Replace("_", ",").Trim();
            //get the geoset
            int geosetindex = abc.FindLastIndex(pp - 1, findgeoset);
            string geosetstr = abc.ElementAt(geosetindex).Split(':')[1];
            geosetstr = geosetstr.Remove(geosetstr.Length - 1);
            geosetstr = geosetstr.Trim();

            //get the operation
            int opindex = abc.FindLastIndex(pp - 1, findop);
            string opstr = abc.ElementAt(opindex).Split(':')[1];
            opstr = opstr.Remove(opstr.Length - 1);
            opstr = opstr.Trim();

            return  instcood + "," + opstr + "," + geosetstr + "," + pp.ToString();
        
        }
コード例 #46
0
		void InsertGroup (BuildProviderGroup group, List <BuildProviderGroup> groups)
		{
			if (group.Application) {
				groups.Insert (groups.Count - 1, group);
				return;
			}

			int index;
			if (group.Standalone)
				index = groups.FindLastIndex (SkipApplicationGroup);
			else
				index = groups.FindLastIndex (SkipStandaloneGroups);

			if (index == -1)
				groups.Add (group);
			else
				groups.Insert (index == 0 ? 0 : index - 1, group);
		}
コード例 #47
0
        public List<AttendanceLogRecord> GetAttendanceLogRecordList(int iCompany, int iDepartment, DateTime beginDate, DateTime endDate, int columnIndex, bool isOrderByAcs)
        {
            List<AttendanceReport> attendanceReports = GetAttendanceReport(iCompany, iDepartment, beginDate, endDate, columnIndex, isOrderByAcs);
            if (attendanceReports.Count == 0)
                return null;

            List<string> lEmplNumbers = GetEmployeeNumberList(iCompany, iDepartment);
            if (lEmplNumbers == null || lEmplNumbers.Count == 0)
                return null;
            string sEmplNumbers = string.Join(",", lEmplNumbers.ToArray());

            OleDbCommand odCom = BuildSelectCmd("Employee", "EmployeeNumber, FirstName, LastName", "EmployeeNumber IN(" + sEmplNumbers + ") AND Active=TRUE");

            OleDbDataReader odRdr = odCom.ExecuteReader();

            List<Employee> employeeList = new List<Employee>();
            Employee empl;
            while (odRdr.Read())
            {
                empl = new Employee();
                empl.EmployeeNumber = (int)odRdr["EmployeeNumber"];
                empl.LastName = odRdr["LastName"].ToString();
                empl.FirstName = odRdr["FirstName"].ToString();
                employeeList.Add(empl);
            }
            odRdr.Close();

            List<AttendanceLogRecord> attLogList = new List<AttendanceLogRecord>();
            AttendanceLogRecord attLog = null;

            List<AttendanceRecord> attRecordList = new List<AttendanceRecord>();
            AttendanceRecord attRecord = null;

            foreach (AttendanceReport attReport in attendanceReports)
            {
                string sAttendanceRecordIDs = attReport.AttendanceRecordIDList;
                sAttendanceRecordIDs = sAttendanceRecordIDs.Replace("{", "").Replace("}", ",").Trim(',');

                odCom = BuildSelectCmd("AttendanceRecord", "*", "ID IN(" + sAttendanceRecordIDs + ")");
                odRdr = odCom.ExecuteReader();

                attRecordList.Clear();
                while (odRdr.Read())
                {
                    attRecord = new AttendanceRecord();
                    attRecord.ID = (int)odRdr["ID"];
                    attRecord.EmployeeNumber = (int)odRdr["EmployeeNumber"];
                    attRecord.Note = odRdr["Note"].ToString();
                    attRecord.Time = (DateTime)odRdr["Time"];
                    attRecordList.Add(attRecord);
                }
                odRdr.Close();

                attRecordList.Sort(delegate(AttendanceRecord e1, AttendanceRecord e2) { return e1.Time.CompareTo(e2.Time); });
                int roundValue = GetConfig().RecordRoundingValue;
                foreach (AttendanceRecord att in attRecordList)
                {
                    att.Time = Util.RoundDateTime(att.Time, roundValue);
                }

                bool isCheckIn = true;
                bool isFirst = true;

                DateTime dDateLog = attRecordList[0].Time.Date;
                foreach (AttendanceRecord att in attRecordList)
                {
                    attLog = new AttendanceLogRecord();
                    if (isFirst)
                    {
                        attLog.EmployeeNumber = attReport.EmployeeNumber;
                        attLog.DateLog = attReport.WorkFrom.Date;

                        //TODO wrong number, total hours here is based on the in/out, not report
                        attLog.TotalHours = Math.Round(CalculateTotalHours(attRecordList), 2);

                        Employee employee = employeeList.Find(delegate(Employee e) { return e.EmployeeNumber == attReport.EmployeeNumber; });

                        attLog.EmployeeName = employee.LastName + ", " + employee.FirstName;
                        isFirst = false;
                    }

                    attLog.ID = att.ID;
                    attLog.TimeLog = (isCheckIn ? "In " : "Out ") + att.Time.ToString("HH:mm");
                    if (att.Time.Date.CompareTo(attReport.WorkFrom.Date) > 0)
                        attLog.TimeLog += " [" + att.Time.Date.ToShortDateString() + "]";
                    attLog.Note = att.Note;

                    attLogList.Add(attLog);

                    isCheckIn = !isCheckIn;
                }

                if (isCheckIn == false && dDateLog.Equals(DateTime.Now.Date) == false)
                {
                    attLog = new AttendanceLogRecord();
                    //attLog.DateLog = attReport.WorkFrom.Date;
                    //attLog.EmployeeNumber = attReport.EmployeeNumber;
                    attLog.TimeLog = "OutMistakes";
                    attLogList.Add(attLog);
                }
            }

            List<RoostedDayOff> roostedDayOffList = GetRoostedDayOffList();
            Hashtable hasEmplName = new Hashtable();
            if (roostedDayOffList.Count > 0)
            {
                AttendanceLogRecord attRc = null;
                foreach (RoostedDayOff roostedDayOff in roostedDayOffList)
                {
                    string employeeName = null;
                    if (hasEmplName.ContainsKey(roostedDayOff.EmployeeNumber))
                    {
                        employeeName = (string)hasEmplName[roostedDayOff.EmployeeNumber];
                    }
                    else
                    {
                        Employee employee = GetEmployeeByEmployeeNumber(roostedDayOff.EmployeeNumber);
                        if (employee == null)
                            continue;

                        employeeName = employee.LastName + ", " + employee.FirstName;

                        hasEmplName.Add(roostedDayOff.EmployeeNumber, employeeName );
                    }

                    attRc = new AttendanceLogRecord();
                    attRc.EmployeeNumber = roostedDayOff.EmployeeNumber;
                    attRc.EmployeeName = employeeName;
                    attRc.DateLog = roostedDayOff.Date;
                    attRc.TotalHours= roostedDayOff.TotalHours;
                    attRc.TimeLog = "Roosted day off";
                    attRc.Note = roostedDayOff.Note;

                    int indexRp = attLogList.FindIndex(0, delegate(AttendanceLogRecord e) { return e.EmployeeNumber == attRc.EmployeeNumber && e.DateLog.Date.CompareTo(attRc.DateLog.Date) == 1; });
                    if (indexRp < 0)
                    {
                        indexRp = attLogList.FindLastIndex(delegate(AttendanceLogRecord e) { return e.EmployeeNumber == attRc.EmployeeNumber; });

                        if (indexRp < 0)
                        {
                            indexRp = attLogList.FindIndex(delegate(AttendanceLogRecord e) { return e.EmployeeNumber > attRc.EmployeeNumber; });

                            if (indexRp < 0)
                            {
                                indexRp = attLogList.Count;
                            }
                        }
                        else
                            indexRp++;
                    }

                    int indexRp_1 = 0;
                    while (true)
                    {
                        if (indexRp > attLogList.Count - 1)
                            break;
                        indexRp_1 = attLogList.FindIndex(indexRp, 1, delegate(AttendanceLogRecord e) { return e.DateLog.Equals(DateTime.MinValue); });
                        if (indexRp_1 < 1)
                            break;
                        indexRp++;
                    }

                    attLogList.Insert(indexRp, attRc);
                }
                hasEmplName.Clear();
                roostedDayOffList.Clear();
            }
            return attLogList;
        }
コード例 #48
0
ファイル: Euler18.cs プロジェクト: gorauskas/Euler.Net
        /// <summary>
        /// The key strategy of the algorithm is to treat the data from the bottom up.
        /// Here are the steps:
        ///  1. Get the last row of the triangle
        ///  2. Get the next to the last row of the triangle
        ///  3. Loop through the items from step 2 above
        ///  4. Find the 2 adjacent items for the item in step 3 above
        ///  5. Select the largest of the 2 items from step 4 above
        ///  6. Replace the item in step 3 above with the sum of item in step 5 
        ///     and the original item from step 3
        ///  7. Remove the last row from the triangle
        /// This is a form of reduction because the next to the last row will contain
        /// the accumulation of the items values after each iteration of the loop in 
        /// FindMaxSum.
        /// </summary>
        /// <param name="triangle">
        /// The triangle data is passed by ref because I need to change
        /// the thing itself.
        /// </param>
        private void ReduceTriangle(ref List<List<int>> triangle) {
            var lastRow = triangle.Last();

            foreach (var index in Enumerable.Range(0, triangle.Count - 1)) {
                triangle[triangle.FindLastIndex(x => true) - 1][index] +=
                    Math.Max(lastRow.GetRange(index, 2)[0], lastRow.GetRange(index, 2)[1]);
            }

            triangle.Remove(lastRow);
        }
コード例 #49
0
        public List<AttendanceSummaryViewReport> GetAttendanceSummaryReport(int iCompany, int iDepartment, DateTime beginDate, DateTime endDate)
        {
            List<AttendanceSummaryReport> attSummarys = new List<AttendanceSummaryReport>();

            List<AttendanceLogReport> attReports = GetAttendanceLogReportList(iCompany, iDepartment, beginDate, endDate);

            if (attReports == null || attReports.Count == 0)
                return null;

            AttendanceSummaryReport attSummary = null;

            foreach (AttendanceLogReport attRp in attReports)
            {
                //attRp.EmployeeNumber
                attSummary = new AttendanceSummaryReport();
                attSummary.EmployeeNumber = attRp.EmployeeNumber;
                attSummary.FullName = attRp.FullName;
                attSummary.TotalHour = attRp.TotalHour;
                attSummary.DateLog = attRp.WorkFrom;
                attSummary.WorkingHour = "Regular Hour : " + attRp.WorkingHour;
                attSummary.ChartData = new double[] { attRp.RegularHour, attRp.WorkingHour, attRp.OvertimeHour1 + attRp.OvertimeHour2 + attRp.OvertimeHour3 + attRp.OvertimeHour4 };
                attSummarys.Add(attSummary);

                if (attRp.OvertimeHour1 > 0)
                {
                    attSummary = new AttendanceSummaryReport();
                    attSummary.EmployeeNumber = attRp.EmployeeNumber;
                    attSummary.DateLog = attRp.WorkFrom;
                    attSummary.WorkingHour = "Overtime Hour 1 : " + attRp.OvertimeHour1;
                    attSummarys.Add(attSummary);

                    if (attRp.OvertimeHour2 > 0)
                    {
                        attSummary = new AttendanceSummaryReport();
                        attSummary.EmployeeNumber = attRp.EmployeeNumber;
                        attSummary.DateLog = attRp.WorkFrom;
                        attSummary.WorkingHour = "Overtime Hour 2 : " + attRp.OvertimeHour2;
                        attSummarys.Add(attSummary);

                        if (attRp.OvertimeHour3 > 0)
                        {
                            attSummary = new AttendanceSummaryReport();
                            attSummary.EmployeeNumber = attRp.EmployeeNumber;
                            attSummary.DateLog = attRp.WorkFrom;
                            attSummary.WorkingHour = "Overtime Hour 3 : " + attRp.OvertimeHour3;
                            attSummarys.Add(attSummary);

                            if (attRp.OvertimeHour4 > 0)
                            {
                                attSummary = new AttendanceSummaryReport();
                                attSummary.EmployeeNumber = attRp.EmployeeNumber;
                                attSummary.DateLog = attRp.WorkFrom;
                                attSummary.WorkingHour = "Overtime Hour 4 : " + attRp.OvertimeHour4;
                                attSummarys.Add(attSummary);
                            }
                        }
                    }
                }
            }

            if (attSummarys.Count == 0)
                return null;

            int employeeNumber = 0, flexiHours = 0;//, wcalRegHour = 8;
            bool applyFlexiHours = false, isFirst = true;
            WorkingCalendar wCal = null;
            PaymentRate paymentRate = null;
            List<Shift> shiftList = new List<Shift>();
            DayOfWeek weekStartsOn = DayOfWeek.Monday;
            DateTime beginFlexiDate, endFlexiDate;
            List<AttendanceSummaryViewReport> attSummarysRs = new List<AttendanceSummaryViewReport>();
            DateTime duplicatedate = DateTime.MinValue;
            while (attSummarys.Count > 0)
            {
                AttendanceSummaryReport attSumRp = attSummarys[0];
                if (employeeNumber == attSumRp.EmployeeNumber)
                {
                    if (applyFlexiHours)
                    {

                        beginFlexiDate = attSumRp.DateLog;
                        endFlexiDate = beginFlexiDate;

                        if (weekStartsOn.Equals(attSumRp.DateLog.DayOfWeek))
                        {
                            endFlexiDate = beginFlexiDate.AddDays(6);//Week
                        }
                        else
                        {
                            while (true)
                            {
                                if (weekStartsOn.Equals(endFlexiDate.DayOfWeek))
                                    break;
                                endFlexiDate = endFlexiDate.AddDays(1);
                            }
                            endFlexiDate = endFlexiDate.AddDays(-1);
                        }

                        List<AttendanceSummaryReport> attSummarysSub = attSummarys.FindAll(delegate(AttendanceSummaryReport e) { return e.EmployeeNumber == employeeNumber && e.DateLog.CompareTo(beginFlexiDate) != -1 && e.DateLog.CompareTo(endFlexiDate) != 1; });
                        if (attSummarysSub == null || attSummarysSub.Count == 0)
                            continue;

                        List<AttendanceSummaryReport> attSummarys_1 = new List<AttendanceSummaryReport>();

                        foreach (AttendanceSummaryReport attRp in attSummarysSub)
                        {
                            if (attRp.DateLog.Equals(duplicatedate))
                            {
                                attSummarys_1[attSummarys_1.Count - 1].WorkingHour = "Regular Hour : " + attSummarys_1[attSummarys_1.Count - 1].TotalHour;
                            }
                            else
                                attSummarys_1.Add(attRp);

                            duplicatedate = attRp.DateLog;
                        }

                        isFirst = true;
                        double dFlexiHours = Convert.ToDouble(flexiHours);
                        AttendanceSummaryViewReport attRp_1;

                        double totalOvertimeHour = 0;
                        int rateNumber = 1;
                        List<string> overtimeHours = null;
                        foreach (AttendanceSummaryReport attRp in attSummarys_1)
                        {
                            attRp_1 = new AttendanceSummaryViewReport();
                            attRp_1.ChartData = attRp.ChartData;
                            attRp_1.DateLog = attRp.DateLog.ToString("d MMM yyyy");
                            attRp_1.DateLogTime = attRp.DateLog;
                            attRp_1.WorkingHour = attRp.WorkingHour;
                            attRp_1.TotalHour = attRp.TotalHour;
                            attRp_1.EmployeeNumber = 0;
                            attRp_1.FullName = null;

                            if (isFirst)
                            {
                                dFlexiHours -= attRp.TotalHour;
                                attRp_1.EmployeeNumber = attRp.EmployeeNumber;
                                attRp_1.FullName = attRp.FullName;
                                double[] chartData = attRp.ChartData;
                                chartData[1] = attRp.TotalHour;
                                chartData[2] = 0;
                                attRp_1.ChartData = chartData;
                                attSummarysRs.Add(attRp_1);
                                isFirst = false;
                            }
                            else
                            {

                                if (dFlexiHours > 0)
                                {
                                    if (dFlexiHours < attRp.TotalHour)
                                    {
                                        attRp_1.WorkingHour = "Regular Hour : " + dFlexiHours;
                                        double[] chartData = attRp.ChartData;
                                        chartData[1] = dFlexiHours;
                                        chartData[2] = attRp.TotalHour - dFlexiHours;
                                        attRp_1.ChartData = chartData;
                                        attSummarysRs.Add(attRp_1);

                                        overtimeHours = new List<string>();
                                        totalOvertimeHour += attRp.TotalHour - dFlexiHours;
                                        GetOverTimeHour(ref overtimeHours, ref rateNumber, ref totalOvertimeHour, paymentRate);
                                        foreach (string strOvertime in overtimeHours)
                                        {
                                            attRp_1 = new AttendanceSummaryViewReport();
                                            attRp_1.ChartData = null;
                                            attRp_1.DateLog = null;
                                            attRp_1.DateLogTime = attRp.DateLog;
                                            attRp_1.TotalHour = -1;
                                            attRp_1.EmployeeNumber = 0;
                                            attRp_1.FullName = null;
                                            attRp_1.WorkingHour = strOvertime;
                                            attSummarysRs.Add(attRp_1);
                                        }
                                    }
                                    else
                                    {
                                        double[] chartData = attRp.ChartData;
                                        chartData[1] = attRp.TotalHour;
                                        chartData[2] = 0;
                                        attRp_1.ChartData = chartData;
                                        attSummarysRs.Add(attRp_1);
                                    }
                                    dFlexiHours -= attRp.TotalHour;
                                }
                                else
                                {
                                    overtimeHours = new List<string>();
                                    totalOvertimeHour += attRp.TotalHour;
                                    GetOverTimeHour(ref overtimeHours, ref rateNumber, ref totalOvertimeHour, paymentRate);
                                    for (int i = 0; i < overtimeHours.Count; i++)
                                    {
                                        attRp_1 = new AttendanceSummaryViewReport();
                                        attRp_1.WorkingHour = overtimeHours[i];
                                        if (i == 0)
                                        {
                                            attRp_1.DateLog = attRp.DateLog.ToString("d MMM yyyy");
                                            attRp_1.DateLogTime = attRp.DateLog;
                                            attRp_1.TotalHour = attRp.TotalHour;
                                            attRp_1.EmployeeNumber = 0;
                                            attRp_1.FullName = null;
                                            double[] chartData = attRp.ChartData;
                                            chartData[1] = 0;
                                            chartData[2] = attRp.TotalHour;
                                            attRp_1.ChartData = chartData;
                                        }

                                        attSummarysRs.Add(attRp_1);
                                    }
                                }
                            }
                        }

                        attSummarys.RemoveAll(delegate(AttendanceSummaryReport e) { return e.EmployeeNumber == employeeNumber && e.DateLog.CompareTo(beginFlexiDate) != -1 && e.DateLog.CompareTo(endFlexiDate) != 1; });

                    }
                    else
                    {
                        if (shiftList.Count > 1)
                        {
                            AttendanceSummaryViewReport attRp_1 = new AttendanceSummaryViewReport();
                            attRp_1.ChartData = attSumRp.ChartData;
                            attRp_1.DateLogTime = attSumRp.DateLog;
                            attRp_1.WorkingHour = attSumRp.WorkingHour;

                            if (duplicatedate.Equals(attSumRp.DateLog))
                            {
                                attRp_1.TotalHour = -1;
                                attRp_1.EmployeeNumber = 0;
                            }
                            else
                            {
                                attRp_1.DateLog = attSumRp.DateLog.ToString("d MMM yyyy");
                                attRp_1.TotalHour = attSumRp.TotalHour;
                                attRp_1.EmployeeNumber = attSumRp.EmployeeNumber;
                                attRp_1.FullName = attSumRp.FullName;
                            }

                            int shiftNumber = -1;
                            if (!attSumRp.DateLog.Equals(DateTime.MinValue))
                            {
                                shiftNumber = GetShiftNumber(attSumRp.DateLog, wCal, shiftList, false);
                                if (attRp_1.DateLog != null)
                                    attRp_1.DateLog += " [Shift " + shiftNumber + "]";
                            }
                            duplicatedate = attSumRp.DateLog;

                            attSummarysRs.Add(attRp_1);
                            attSummarys.Remove(attSumRp);
                        }
                        else
                        {
                            AttendanceSummaryViewReport attRp_1 = new AttendanceSummaryViewReport();
                            attRp_1.ChartData = attSumRp.ChartData;
                            attRp_1.DateLogTime = attSumRp.DateLog;
                            attRp_1.WorkingHour = attSumRp.WorkingHour;

                            if (duplicatedate.Equals(attSumRp.DateLog))
                            {
                                attRp_1.TotalHour = -1;
                                attRp_1.EmployeeNumber = 0;
                            }
                            else
                            {
                                attRp_1.DateLog = attSumRp.DateLog.ToString("d MMM yyyy");
                                attRp_1.TotalHour = attSumRp.TotalHour;
                                attRp_1.EmployeeNumber = attSumRp.EmployeeNumber;
                                attRp_1.FullName = attSumRp.FullName;
                            }

                            duplicatedate = attSumRp.DateLog;

                            attSummarysRs.Add(attRp_1);
                            attSummarys.Remove(attSumRp);
                        }
                    }
                }
                else
                {
                    employeeNumber = attSumRp.EmployeeNumber;
                    wCal = GetWorkingCalendarByEmployee(employeeNumber);
                    shiftList = GetShiftListByWorkingCalendar(wCal.ID);
                    paymentRate = GetWorkingDayPaymentRateByWorkingCalendar(wCal.ID);
                    applyFlexiHours = wCal.ApplyFlexiHours;
                    flexiHours = wCal.FlexiHours;
                    weekStartsOn = GetDayOfWeek(wCal.WeekStartsOn);
                }
            }

            List<RoostedDayOff> roostedDayOffList = GetRoostedDayOffList();
            Hashtable hasEmplName = new Hashtable();
            if (roostedDayOffList.Count > 0)
            {
                AttendanceSummaryViewReport attReport = null;
                foreach (RoostedDayOff roostedDayOff in roostedDayOffList)
                {
                    double regularHour = 0;
                    string employeeName = null;
                    if (hasEmplName.ContainsKey(roostedDayOff.EmployeeNumber))
                    {
                        object[] objData= (object[])hasEmplName[roostedDayOff.EmployeeNumber];
                        employeeName = (string)objData[0];
                        regularHour =  (double)objData[1];
                    }
                    else
                    {
                        Employee employee = GetEmployeeByEmployeeNumber(roostedDayOff.EmployeeNumber);
                        if (employee == null)
                            continue;

                        employeeName = employee.LastName + ", " + employee.FirstName;

                        AttendanceSummaryViewReport attViewRp = attSummarysRs.Find(delegate(AttendanceSummaryViewReport e) { return e.EmployeeNumber == roostedDayOff.EmployeeNumber; });
                        if (attViewRp != null)
                            regularHour = attViewRp.ChartData[0];
                        else
                        {
                            wCal = GetWorkingCalendarByEmployee(roostedDayOff.EmployeeNumber);
                            paymentRate = GetWorkingDayPaymentRateByWorkingCalendar(wCal.ID);
                            regularHour = paymentRate.NumberOfRegularHours;
                        }
                        hasEmplName.Add(roostedDayOff.EmployeeNumber, new object[] { employeeName, regularHour });
                    }

                    attReport = new AttendanceSummaryViewReport();
                    attReport.EmployeeNumber = roostedDayOff.EmployeeNumber;
                    attReport.FullName = employeeName;
                    attReport.DateLog = roostedDayOff.Date.ToString("d MMM yyyy");
                    attReport.DateLogTime = roostedDayOff.Date;
                    attReport.ChartData = new double[] { regularHour, roostedDayOff.TotalHours, 0 };
                    attReport.TotalHour = roostedDayOff.TotalHours;
                    attReport.WorkingHour = "Roosted day off";

                    int indexRp = attSummarysRs.FindIndex(0, delegate(AttendanceSummaryViewReport e) { return e.EmployeeNumber == attReport.EmployeeNumber && e.DateLogTime.Date.CompareTo(attReport.DateLogTime.Date) == 1; });
                    if (indexRp < 0)
                    {
                        indexRp = attSummarysRs.FindLastIndex(delegate(AttendanceSummaryViewReport e) { return e.EmployeeNumber == attReport.EmployeeNumber; });

                        if (indexRp < 0)
                        {
                            indexRp = attSummarysRs.FindIndex(delegate(AttendanceSummaryViewReport e) { return e.EmployeeNumber > attReport.EmployeeNumber; });

                            if (indexRp < 0)
                            {
                                indexRp = attSummarysRs.Count;
                            }
                        }
                        else
                            indexRp++;
                    }

                    int indexRp_1 = 0;
                    while (true)
                    {
                        if (indexRp > attSummarysRs.Count - 1)
                            break;
                        indexRp_1 = attSummarysRs.FindIndex(indexRp, 1, delegate(AttendanceSummaryViewReport e) { return e.DateLog == null; });
                        if (indexRp_1 < 1)
                            break;
                        indexRp++;
                    }

                    attSummarysRs.Insert(indexRp, attReport);
                }
                hasEmplName.Clear();
                roostedDayOffList.Clear();
            }
            return attSummarysRs;
        }
コード例 #50
0
ファイル: AbsFluxSpectra.cs プロジェクト: hpavlov/tangra3
        private static void RescaleData(
			int fromWavelength, int toWavelength, int step, bool useBlurring, double fwhmCoeff, double nonLinearityCoeff,
			List<double> wavelengths, List<double> fluxes, List<double> rescaledFluxes, List<double> resolvedWavelengths)
        {
            bool useFwhmNormalisation = !double.IsNaN(fwhmCoeff);
            bool useNonLinearityNormalisation = !double.IsNaN(nonLinearityCoeff);

            // Blurring:
            // 1) Find the number of original datapoints in resolution/blur interval
            // 2) Use this number as a kernel for Gaussian blur of all participating data points
            // 3) Perform a blur using twice the resolution interval
            // 4) Get the average of the participating blurred data points
            // 5) This is the value to be used for the bin

            int totalPoints = (toWavelength - fromWavelength) / step;

            int totalSourceDataPoints = wavelengths.Count;
            double firstDataWaveLength = wavelengths[0];
            double lastDataWaveLength = wavelengths[totalSourceDataPoints - 1];

            double totalSourceDataPointsRange = lastDataWaveLength - firstDataWaveLength;
            int binSize = (int)Math.Ceiling(step / (totalSourceDataPointsRange / totalSourceDataPoints));
            var kernel = new float[2 * binSize + 1];
            for (int i = 0; i < binSize; i++)
            {
                kernel[binSize + i] = kernel[binSize - i] = GetGaussianValue(binSize, i);
            }

            var partFluxes = new List<double>();

            rescaledFluxes.Clear();
            rescaledFluxes.AddRange(new double[totalPoints]);

            if (resolvedWavelengths != null)
            {
                resolvedWavelengths.Clear();
                resolvedWavelengths.AddRange(new double[totalPoints]);
            }

            for (int i = 0; i < totalPoints; i++)
            {
                float midWvL = fromWavelength + (i + 0.5f) * step;
                int binFromWvL = fromWavelength + i * step;
                int binToWvL = fromWavelength + (i + 1) * step;

                if (resolvedWavelengths != null) resolvedWavelengths[i] = midWvL;

                if (binFromWvL < firstDataWaveLength || binFromWvL > lastDataWaveLength)
                {
                    rescaledFluxes[i] = double.NaN;
                    continue;
                }

                // double blurredValue = Sum(all_blurred_point_values) / num_points;

                int idxFrom = wavelengths.FindLastIndex(x => x < binFromWvL);
                int idxTo = wavelengths.FindIndex(x => x > binToWvL);

                partFluxes.Clear();

                for (int j = idxFrom + 1; j < idxTo; j++)
                {
                    double sum = 0;
                    double weight = 0;

                    if (useBlurring)
                    {
                        for (int k = j - binSize; k <= j + binSize; k++)
                        {
                            if (k > 0 && k < wavelengths.Count - 1)
                            {
                                weight += kernel[k - j + binSize];
                                sum += kernel[k - j + binSize] * fluxes[k];
                            }
                        }

                        double blurredFlux = 0;

                        if (weight > 0)
                            blurredFlux = sum / weight;
                        else
                            blurredFlux = fluxes[j];

                        partFluxes.Add(blurredFlux);
                    }
                    else
                    {
                        partFluxes.Add(fluxes[j]);
                    }
                }

                double rescaledValue = partFluxes.Any() ? partFluxes.Average() : double.NaN;

                if (useFwhmNormalisation)
                    rescaledValue = rescaledValue * fwhmCoeff;
                if (useNonLinearityNormalisation)
                    rescaledValue = Math.Pow(rescaledValue, nonLinearityCoeff);

                rescaledFluxes[i] = rescaledValue;
            }
        }
コード例 #51
0
        //Summary:
        //Parses the xbee rx packet
        //generates exceptions on error


        public List<Byte> parseRxPacket(List<Byte> packet)
        {
            #region TRACE_CODE
            String traceString = DateTime.Now.ToString();
            foreach (Byte b in packet)
            {
                traceString += "0x" + b.ToString("x2") + " ";
            }
            traceString += Environment.NewLine;

            _xbeeTrace.TraceInformation(traceString);
            foreach (TraceListener l in _xbeeTrace.Listeners)
            {
                l.Flush();
            }

            #endregion

            List<Byte> parsedPacket = null;


            if (communicationMode == COMMUNICATION_MODE.RAW)
            {
                return packet;
            }

            if (packet.Contains((Byte)ESCAPE_CHARS.STX))
            {
                int lastIndex = 0;
                lastIndex = packet.FindLastIndex(findSTX);
                if (packet.Count >= lastIndex + 3)
                {
                    Byte[] packetLengthArray = { packet[lastIndex + 2], packet[lastIndex + 1] };                //msb and lsb of length
                    short packetLength = BitConverter.ToInt16(packetLengthArray, 0);    //convert to short
                    if (packet.Count < packetLength + lastIndex + 3)
                        return null;
                    else parsedPacket = new List<byte>();
                }

            }
            List<List<Byte>> packetList = new List<List<byte>>();
            while (packet.Contains((Byte)ESCAPE_CHARS.STX))
            {
                int lastIndex = 0;
                lastIndex = packet.FindLastIndex(findSTX);

                packetList.Insert(0, packet.GetRange(lastIndex, packet.Count-lastIndex ));
                packet.RemoveRange(lastIndex, packet.Count - lastIndex);
            }



            foreach (List<Byte> l in packetList)
            {
                List<Byte> parsedL = null;
                if (communicationMode == COMMUNICATION_MODE.API_ESC)
                {
                    parsedL = removeEscapeChars(l);
                }
                Byte[] packetLengthArray = { parsedL[2], parsedL[1] };                //msb and lsb of length
                short packetLength = BitConverter.ToInt16(packetLengthArray, 0);    //convert to short


                parsedL.RemoveAt(0); //remove the start delimiter   

                parsedL.RemoveRange(0, 2); //remove the length fields

                Byte checksum = parsedL[parsedL.Count - 1];       //get the received checksum

                parsedL.RemoveAt(parsedL.Count - 1);              //remove the checksum from the packet

                if (computeCheckSum(parsedL) != checksum)        //validate checksum
                {
                    throw new Xbee_Exception("Checksum Error");
                }

                if (packetLength != parsedL.Count)               //verify received byte count
                {
                    throw new Xbee_Exception("Recevied Length mismatch ");
                }
                if (parsedL[0] != (Byte)API_ID.Rx_16)            //verify api id
                {
                    throw new Xbee_Exception(" API identifier mismatch");
                }
                else
                {
                    parsedL.RemoveAt(0);                         //remove the api id
                }

                parsedL.RemoveRange(0, 4);       //remove the address , rssi , option bytes
                parsedPacket.AddRange(parsedL.GetRange(0, parsedL.Count));

            }

            return parsedPacket;
        }
コード例 #52
0
 private void CountTable()
 {
     if (IsComplete())
     {
         List<int> scores = new List<int>();
         for (int i = 0; i < table.RowCount; ++i)
         {
             scores.Add((int)table.Rows[i].Cells["colPoints"].Tag);
         }
         List<int> sortedScores = new List<int>(scores);
         sortedScores.Sort();
         for (int i = 0; i < table.RowCount; ++i)
         {
             int ps = scores.Count - sortedScores.FindIndex(delegate(int x) { return x == scores[i]; });
             int pe = scores.Count - sortedScores.FindLastIndex(delegate(int x) { return x == scores[i]; });
             table[colPlace.Index, i].Value = ((ps == pe) ? ps.ToString() : pe.ToString() + "-" + ps.ToString());
         }
     }
     else
     {
         for (int i = 0; i < table.RowCount; ++i)
         {
             table[colPlace.Index, i].Value = "";
         }
     }
 }
コード例 #53
0
ファイル: Program.cs プロジェクト: Rivolvan/rainmeter
        static int Main(string[] args)
        {
            if (args.Length < 4)
            {
                Console.WriteLine("DllExporter error: Invalid arguments");
                return 1;
            }

            string configurationName = args[0];
            string platformTarget = args[1];
            string targetDirectory = args[2];
            string targetDllName = targetDirectory + args[3];
            string targetIlName = targetDllName + ".il";
            string targetResName = targetDllName + ".res";

            bool is64 = platformTarget.ToLower().Equals("x64");
            bool isDebug = configurationName.ToLower().Equals("debug");

            string ilasmPath = FindIlasmPath(is64);
            if (ilasmPath == null)
            {
                Console.WriteLine("DllExporter error: ilasm.exe not found");
                return 1;
            }

            string ildasmPath = FindIldasmPath();
            if (ildasmPath == null)
            {
                Console.WriteLine("DllExporter error: ildasm.exe not found");
                return 1;
            }

            Directory.SetCurrentDirectory(targetDirectory);

            // Disassemble
            Process ildasmProc = new Process();
            string ildasmArgs = string.Format(
                "/nobar {0} /output=\"{1}\" \"{2}\"",
                isDebug ? "/linenum" : "",
                targetIlName,
                targetDllName);

            ildasmProc.StartInfo = new ProcessStartInfo(ildasmPath, ildasmArgs);
            ildasmProc.StartInfo.UseShellExecute = false;
            ildasmProc.StartInfo.CreateNoWindow = false;
            ildasmProc.StartInfo.RedirectStandardOutput = true;
            ildasmProc.Start();
            ildasmProc.WaitForExit();

            if (ildasmProc.ExitCode != 0)
            {
                Console.WriteLine("DllExporter error: Unable to disassemble!");
                Console.WriteLine(ildasmProc.StandardOutput.ReadToEnd());
                return ildasmProc.ExitCode;
            }

            bool hasResource = File.Exists(targetResName);

            // Read disassembly and find methods marked with DllExport attribute
            List<string> lines = new List<string>(File.ReadAllLines(targetIlName));
            int attributeIndex = 0;
            int exportCount = 0;
            while (true)
            {
                attributeIndex = lines.FindIndex(attributeIndex, new Predicate<string>(x => x.Contains(".custom instance void") && x.Contains("DllExport::.ctor()")));
                if (attributeIndex < 8) break;

                int methodIndex = lines.FindLastIndex(attributeIndex, attributeIndex, new Predicate<string>(x => x.Contains(".method")));
                if (methodIndex == -1)
                {
                    Console.WriteLine("DllExporter error: Unable to parse disassembly (.method not found)!");
                    return 1;
                }

                int functionIndex = lines.FindIndex(methodIndex, new Predicate<string>(x => x.Contains("(")));
                if (functionIndex == -1)
                {
                    Console.WriteLine("DllExporter error: Unable to parse disassembly (bracket not found)!");
                    return 1;
                }

                int bracketPos = lines[functionIndex].IndexOf('(');
                int functionNamePos = lines[functionIndex].LastIndexOf(' ', bracketPos);
                string functionName = lines[functionIndex].Substring(functionNamePos, bracketPos - functionNamePos);

                // Change calling convention to cdecl
                lines[functionIndex] = string.Format("{0} modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) {1}", lines[functionIndex].Substring(0, functionNamePos - 1), lines[functionIndex].Substring(functionNamePos));

                int attributeBeginPos = lines[attributeIndex].IndexOf('.');
                string spaces = new string(' ', attributeBeginPos);

                // Replace attribute with export
                ++exportCount;
                lines[attributeIndex] = string.Format("{0}.export [{1}] as {2}", spaces, exportCount, functionName);

                ++attributeIndex;
            }

            if (exportCount == 0)
            {
                Console.WriteLine("DllExporter warning: Nothing found to export.");
            }

            // Remove the DllExport class
            int classIndex = lines.FindIndex(new Predicate<string>(x => x.Contains(".class ") && x.EndsWith(".DllExport")));
            if (classIndex == -1)
            {
                Console.WriteLine("DllExporter error: Unable to parse disassembly (DllExport class not found)!");
                return 1;
            }
            else
            {
                int classEndIndex = lines.FindIndex(classIndex, new Predicate<string>(x => x.Contains("} // end of class") && x.EndsWith(".DllExport")));
                if (classEndIndex == -1)
                {
                    Console.WriteLine("DllExporter error: Unable to parse disassembly (DllExport class end not found)!");
                    return 1;
                }

                lines.RemoveRange(classIndex, classEndIndex - classIndex + 2);
            }

            // Write everything back
            File.WriteAllLines(targetIlName, lines.ToArray());

            // Reassemble
            Process ilasmProc = new Process();
            string resource = hasResource ? string.Format("/resource=\"{0}\"", targetResName) : "";
            string ilasmArgs = string.Format("/nologo /quiet /dll {0} {1} /output=\"{2}\" {3} \"{4}\"", isDebug ? "/debug /pdb" : "/optimize", is64 ? "/x64 /PE64" : "", targetDllName, resource, targetIlName);
            ilasmProc.StartInfo = new ProcessStartInfo(ilasmPath, ilasmArgs);
            ilasmProc.StartInfo.UseShellExecute = false;
            ilasmProc.StartInfo.CreateNoWindow = false;
            ilasmProc.StartInfo.RedirectStandardOutput = true;
            ilasmProc.Start();
            ilasmProc.WaitForExit();

            if (ilasmProc.ExitCode != 0)
            {
                Console.WriteLine("DllExporter error: Unable to assemble!");
                Console.WriteLine(ilasmProc.StandardOutput.ReadToEnd());
                return ilasmProc.ExitCode;
            }

            // Cleanup
            File.Delete(targetIlName);
            File.Delete(targetResName);

            Console.WriteLine("DllExporter: Processed {0}", args[3]);

            return 0;
        }
コード例 #54
0
        private void VerificationScenario(uint testKey)
        {
            // setup
            List<SiloAddress> silos = new List<SiloAddress>();

            foreach (var siloHandle in this.HostedCluster.GetActiveSilos())
            {
                long hash = siloHandle.SiloAddress.GetConsistentHashCode();
                int index = silos.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1;
                silos.Insert(index, siloHandle.SiloAddress);
            }

            // verify parameter key
            VerifyKey(testKey, silos);
            // verify some other keys as well, apart from the parameter key            
            // some random keys
            for (int i = 0; i < 3; i++)
            {
                VerifyKey((uint)random.Next(), silos);
            }
            // lowest key
            uint lowest = (uint)(silos.First().GetConsistentHashCode() - 1);
            VerifyKey(lowest, silos);
            // highest key
            uint highest = (uint)(silos.Last().GetConsistentHashCode() + 1);
            VerifyKey(lowest, silos);
        }
コード例 #55
0
ファイル: Program.cs プロジェクト: al-main/Asp-Dot-Net-CSharp
        /*
         * Functions in List.
         * 1. Contains() function: Checks if an item exists in the list.
         *      This method returns true if item exists, else false.
         *
         * 2. Exists() function: Checks if an item exists in the list based on a condition.
         *      This method returns true if item exists else false.
         *
         * 3. Find() function: Searches for an element that matches the conditions defined by the specified lambda expression
         *      and returns the first matching item from the list.
         *
         * 4. FindLast() function: Searches for an element that matches the conditions defined by the specified lambda expression
         *      and returns the Last matching item from the list.
         *
         * 5. FindAll() function: Returns all the items from the list matches the conditions specified by the lambda expression.
         *
         * 6. FindIndex() function: Returns the index of the item, that matches the condition specfied by the lambda expression.
         *      There are 2 other overloads of this method which allows us to specify the range of the elements to search, with in the list.
         *
         * 7. FindLastIndex() function: Returns the index of the items, that matches the condition specified by the lambda expression.
         *      There are 2 other overloads of this method which allows us to specify the range of the elements to search, with in the list.
         *
         * 8. ToList() function: Convert an array to a List.
         *
         * 9. ToArray function: Convert a List to an Array.
         *
         * 10. ToDictionary() function: Convert a List  to a Dictionary.
         */
        static void Main(string[] args)
        {
            Customer customer1 = new Customer() { ID = 101, Name = "Anand Dev", Salary = 4000 };
            Customer customer2 = new Customer() { ID = 102, Name = "Praveen", Salary = 5000 };
            Customer customer3 = new Customer() { ID = 103, Name = "Uttam", Salary = 8000 };

            List<Customer> listCustomers = new List<Customer>(2);
            listCustomers.Add(customer1);
            listCustomers.Add(customer2);
            listCustomers.Add(customer3);

            Console.WriteLine("Values in the list are:");
            foreach (Customer c in listCustomers)
            {
                Console.WriteLine("ID = {0}, Name = {1}, Salry = {2}", c.ID, c.Name, c.Salary);
            }
            Console.WriteLine();

            #region 1. Contains() method.
            if (listCustomers.Contains(customer3))
            {
                Console.WriteLine("List Contains() Customer 3 object.\n");
            }
            else
            {
                Console.WriteLine("List does NOT Contains() Customer 3 object.\n");
            }
            #endregion

            #region 2. Exists() method.
            if (listCustomers.Exists(cust => cust.Name.StartsWith("A")))
            {
                Console.WriteLine("Item Exists(), having Name starting with \"A\".\n");
            }
            else
            {
                Console.WriteLine("Item NOT Exists(), having Name starting with \"A\".\n");
            }
            #endregion

            #region 3. Find() method.
            Customer findCustomer = listCustomers.Find(cust => cust.Salary > 4000);
            Console.WriteLine("Find() method give us first object matching condition from list:\nID = {0}, Name = {1}, Salry = {2}", findCustomer.ID, findCustomer.Name, findCustomer.Salary);

            #endregion

            #region 4. FindLast() method.
            Customer findLastCustomer = listCustomers.FindLast(cust => cust.Salary > 4000);
            Console.WriteLine("\nFindLast() method give us last object matching condition from list:\nID = {0}, Name = {1}, Salry = {2}", findLastCustomer.ID, findLastCustomer.Name, findLastCustomer.Salary);
            #endregion

            #region 5. FindAll() method.
            Console.WriteLine("\nFindAll() method returns all the items from the list matches the conditions specified by the lambda expression.");
            List<Customer> listFindAllCustomers = listCustomers.FindAll(cust => cust.Salary > 4000);
            foreach (Customer c in listFindAllCustomers)
            {
                Console.WriteLine("ID = {0}, Name = {1}, Salry = {2}", c.ID, c.Name, c.Salary);
            }
            #endregion

            #region 6. FindIndex() method.
            int index = listCustomers.FindIndex(cust => cust.Salary > 4000);
            Console.WriteLine("\nFindIndex() method, Index = {0}", index);
            #endregion

            #region 7. FindLastIndex() method.
            int lastIndex = listCustomers.FindLastIndex(cust => cust.Salary > 4000);
            Console.WriteLine("\nFindLastIndex() method, Last Index = {0}",lastIndex);
            #endregion

            #region 8. Array to List conversion.
            Console.WriteLine("\nArray to List conversion:");
            Customer[] arrayCustomers = new Customer[3];
            arrayCustomers[0] = customer1;
            arrayCustomers[1] = customer2;
            arrayCustomers[2] = customer3;

            List<Customer> arrayToListCustomers = arrayCustomers.ToList();
            foreach (Customer c in arrayToListCustomers)
            {
                Console.WriteLine("ID = {0}, Name = {1}, Salry = {2}", c.ID, c.Name, c.Salary);
            }
            #endregion

            #region 9. List to Array conversion
            Console.WriteLine("\nList to Array conversion:");
            Customer[] listToArray = listCustomers.ToArray();
            foreach (Customer c in listToArray)
            {
                Console.WriteLine("ID = {0}, Name = {1}, Salry = {2}", c.ID, c.Name, c.Salary);
            }
            #endregion

            #region 10. List to Dictionary conversion.
            Console.WriteLine("\nList to Dictionary conversion:");
            Dictionary <int,Customer> listToDictonary = listCustomers.ToDictionary(cus => cus.ID);
            foreach (KeyValuePair<int, Customer> kvp in listToDictonary)
            {
                Customer c = kvp.Value;
                Console.WriteLine("ID = {0}, Name = {1}, Salry = {2}", c.ID, c.Name, c.Salary);
            }
            #endregion

            Console.ReadKey();
        }
コード例 #56
0
        private static StringBuilder RestoreTags(Dictionary<int, string> tags, StringBuilder builder)
        {
            List<MinifyHtmlTag> незакрытыеТеги = new List<MinifyHtmlTag>();
            int[] позицииТегов = tags.Keys.ToArray();

            for (int i = позицииТегов.Length - 1; i >= 0; i--)
            {
                int позиция = позицииТегов[i];
                if (позицииТегов[i] < builder.Length)
                {
                    builder = builder.Insert(позицииТегов[i], tags[позиция]);

                    // Изменяем список незакрытых тегов
                    MinifyHtmlTag новыйТег = new MinifyHtmlTag(tags[позиция]);
                    if (!string.IsNullOrEmpty(новыйТег.Name))
                    {
                        if (новыйТег.MinifyTagType == MinifyTagType.Opening)
                        {
                            незакрытыеТеги.Add(новыйТег);
                        }
                        else if (новыйТег.MinifyTagType == MinifyTagType.Closing)
                        {
                            int индексОткрытогоТега = незакрытыеТеги.FindLastIndex(p => p.Name == новыйТег.Name);
                            if (индексОткрытогоТега != -1)
                                незакрытыеТеги.RemoveAt(индексОткрытогоТега);
                        }
                    }
                }
                else
                {
                    break;
                }
            }

            for (int i = незакрытыеТеги.Count - 1; i >= 0; i--)
            {
                builder.Append(незакрытыеТеги[i].CreateClosingTag());
            }

            return builder;
        }
コード例 #57
0
        private void HandleUnreferencedTimelinekeys(SpriterDataEntityAnimation animation, SpriterDataEntityAnimationMainline mainline, List<KeyFrame> keyFrameList, IDictionary<int, ScaledSprite> persistentScaledSprites, SpriterObject SpriterObject, IDictionary<string, Texture2D> textures, IDictionary<KeyFrameValues, int> keyFrameValuesParentDictionary, IDictionary<int, SpriterBone> persistentBones, IDictionary<int, ScaledPositionedObject> boneRefDic, IDictionary<string, ObjectInfo> boxes, IDictionary<int, ScaledPolygon> persistentScaledPolygons, IDictionary<int, SpriterPoint> persistentPoints, SpriterDataEntity entity)
        {
            foreach (var timeline in animation.Timeline)
            {
                foreach (var timelineKey in timeline.Key)
                {
                    // if timeline key has an object, and no mainline keys for objects reference this key
                    if (timelineKey.Object != null &&
                        !mainline.Keys.Where(k => k.ObjectRef != null)
                                 .Any(k => k.ObjectRef.Any(r => r.Key == timelineKey.Id && r.Timeline == timeline.Id)) ||
                        timelineKey.Bone != null &&
                        !mainline.Keys.Where(k => k.BoneRef != null)
                                 .Any(k => k.BoneRef.Any(r => r.Key == timelineKey.Id && r.Timeline == timeline.Id)))
                    {
                        int index = keyFrameList.FindLastIndex(kf => Math.Abs(kf.Time - (timelineKey.Time/1000.0f)) < .0001f);
                        if (index > 0)
                        {
                            var keyFrame = new KeyFrame {Time = timelineKey.Time/1000.0f};
                            var mainlineKey = mainline.Keys.Single(k => k.Time == timelineKey.Time);
                            if (mainlineKey.ObjectRef != null && timelineKey.Object != null)
                            {
                                CreateRuntimeObjectsForSpriterObjectRef(mainlineKey, persistentScaledSprites,
                                                                        SpriterObject, animation, textures, keyFrame,
                                                                        keyFrameValuesParentDictionary, boxes, persistentScaledPolygons, persistentPoints, timelineKeyOverride: timelineKey);
                            }

                            if (mainlineKey.BoneRef != null && timelineKey.Bone != null)
                            {
                                CreateRuntimeObjectsForSpriterBoneRef(mainlineKey, persistentBones, SpriterObject,
                                                                      animation, keyFrame, boneRefDic,
                                                                      keyFrameValuesParentDictionary, entity, timelineKey);
                            }
                            keyFrameList.Insert(index, keyFrame);
                        }
                    }
                }
            }
        }
コード例 #58
0
    static void DrawSubUserSettings_BundleId(TestFlightMobileProvision[] availableProvisions, string[] availableIdentities)
    {
        var bundleIdOptions = new List<string>();

        bundleIdOptions.Add("com.*");

        foreach(var p in availableProvisions)
        {
            int start = p.AppIdentifier.IndexOf(".");

            if(start == -1)
                continue;

            var id = p.AppIdentifier.Substring(start+1);
            if(id == "*")
                id = "com.*";
            else if(p.Certificates != null && !System.Array.Exists(availableIdentities, m => p.Certificates.Contains(m)))
                continue;

            if(bundleIdOptions.Contains(id))
                continue;

            bundleIdOptions.Add(id);
        }

        bundleIdOptions.Sort((m,n) => m.Length.CompareTo(n.Length) );

        int prevBundle = 0;
        prevBundle = Mathf.Max(0,bundleIdOptions.FindLastIndex(m => PlayerSettings.bundleIdentifier.StartsWith(m.Replace("*",""))));

        var newChosenBundle = Popup(new GUIContent("Bundle Id*", "Select/edit your bundle Id from the list of bundle ids that match your provisioning profiles.\n\nYou are only able to select from provisioning profiles that match this bundle id."), prevBundle, bundleIdOptions.ToArray(), 0);

        if(bundleIdOptions.Count == 0)
            return;

        var newBundleId = bundleIdOptions[newChosenBundle];

        if(bundleIdOptions[newChosenBundle].EndsWith("*"))
        {
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(FieldWidth+4);
            EditorGUILayout.BeginHorizontal("box");

            var appsuffix = PlayerSettings.productName;
            if(PlayerSettings.bundleIdentifier.StartsWith(bundleIdOptions[prevBundle].Replace("*","")))
                appsuffix = PlayerSettings.bundleIdentifier.Remove(0, bundleIdOptions[prevBundle].Replace("*","").Length);

            newBundleId = bundleIdOptions[newChosenBundle].Replace("*","");
            GUILayout.Label(newBundleId, GUILayout.ExpandWidth(false));

            newBundleId += GUILayout.TextField(appsuffix, GUILayout.ExpandWidth(false), GUILayout.MinWidth(100));

            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndHorizontal();
        }

        PlayerSettings.bundleIdentifier = newBundleId;
    }
コード例 #59
0
		int InsertLines (int offset, int start, int end, out int newStart, out int newEnd)
		{
			StringBuilder sb = new StringBuilder ();
			StackFrame ff = DebuggingService.CurrentFrame;
			List<AssemblyLine> lines = new List<AssemblyLine> (ff.Disassemble (start, end - start + 1));
			
			int i = lines.FindIndex (al => !al.IsOutOfRange);
			if (i == -1) {
				newStart = int.MinValue;
				newEnd = int.MinValue;
				return 0;
			}
			
			newStart = i == 0 ? start : int.MinValue;
			lines.RemoveRange (0, i);
			
			int j = lines.FindLastIndex (al => !al.IsOutOfRange);
			newEnd = j == lines.Count - 1 ? end : int.MinValue;
			lines.RemoveRange (j + 1, lines.Count - j - 1);
			
			int lineCount = 0;
			int editorLine = editor.GetTextEditorData ().OffsetToLineNumber (offset);
			foreach (AssemblyLine li in lines) {
				if (li.IsOutOfRange)
					continue;
				InsertAssemblerLine (sb, editorLine++, li);
				lineCount++;
			}
			editor.Insert (offset, sb.ToString ());
			editor.Document.CommitUpdateAll ();
			if (offset == 0)
				this.cachedLines.InsertRange (0, lines);
			else
				this.cachedLines.AddRange (lines);
			return lineCount;
		}
コード例 #60
0
        /// <summary>
        /// Given a polygon defined by an outer ring with one or more inner rings (holes), return a single list of points representing
        /// a polygon with a hole added to it. The added hole is removed from <paramref name="innerRings"/>.
        /// </summary>
        /// <param name="outerRing">A list of Cartographic points defining the outer polygon.</param>
        /// <param name="innerRings">A list of lists of Cartographic points, each list defining a "hole" in the outer polygon.</param>
        /// <returns>A single list of Cartographic points defining the polygon, including the eliminated inner ring.</returns>
        public static List<Cartographic> EliminateHole(List<Cartographic> outerRing, List<List<Cartographic>> innerRings)
        {
            // Convert from LLA -> XYZ and project points onto a tangent plane to find the mutually visible vertex.
            List<Cartesian> cartesianOuterRing = new List<Cartesian>();
            foreach (Cartographic point in outerRing)
            {
                cartesianOuterRing.Add(Ellipsoid.Wgs84.ToCartesian(point));
            }
            var windingOrder = GetWindingOrder(cartesianOuterRing);
            List<List<Cartesian>> cartesianInnerRings = new List<List<Cartesian>>();
            for(int i = 0; i < innerRings.Count; ++i)
            {
                var ring = innerRings[i];
                List<Cartesian> cartesianInnerRing = new List<Cartesian>();
                foreach (Cartographic point in ring)
                {
                    cartesianInnerRing.Add(Ellipsoid.Wgs84.ToCartesian(point));
                }
                var innerWindingOrder = GetWindingOrder(cartesianInnerRing);
                if (innerWindingOrder == windingOrder)
                {
                    ring.Reverse();
                    cartesianInnerRing.Reverse();
                }
                cartesianInnerRings.Add(cartesianInnerRing);
            }

            EllipsoidTangentPlane tangentPlane = new EllipsoidTangentPlane(Ellipsoid.Wgs84, cartesianOuterRing);
            cartesianOuterRing = (List<Cartesian>)(tangentPlane.ComputePositionsOnPlane(cartesianOuterRing));
            for (int i = 0; i < cartesianInnerRings.Count; i++)
            {
                cartesianInnerRings[i] = (List<Cartesian>)(tangentPlane.ComputePositionsOnPlane(cartesianInnerRings[i]));
            }

            int visibleVertexIndex = GetMutuallyVisibleVertexIndex(cartesianOuterRing, cartesianInnerRings);
            int innerRingIndex = GetRightmostRingIndex(cartesianInnerRings);
            int innerRingVertexIndex = GetRightmostVertexIndex(cartesianInnerRings[innerRingIndex]);

            List<Cartographic> innerRing = innerRings[innerRingIndex];
            List<Cartographic> newPolygonVertices = new List<Cartographic>();

            for (int i = 0; i < outerRing.Count; i++)
            {
                newPolygonVertices.Add(outerRing[i]);
            }

            List<Cartographic> holeVerticesToAdd = new List<Cartographic>();

            // If the rightmost inner vertex is not the starting and ending point of the ring,
            // then some other point is duplicated in the inner ring and should be skipped once.
            if (innerRingVertexIndex != 0)
            {
                for (int j = 0; j <= innerRing.Count; j++)
                {
                    int index = (j + innerRingVertexIndex) % innerRing.Count;
                    if (index != 0)
                    {
                        holeVerticesToAdd.Add(innerRing[index]);
                    }
                }
            }
            else
            {
                for (int j = 0; j < innerRing.Count; j++)
                {
                    holeVerticesToAdd.Add(innerRing[(j + innerRingVertexIndex) % innerRing.Count]);
                }
            }

            int lastVisibleVertexIndex = newPolygonVertices.FindLastIndex(delegate(Cartographic point)
            {
                return point.Equals(outerRing[visibleVertexIndex]);
            });

            holeVerticesToAdd.Add(outerRing[lastVisibleVertexIndex]);
            newPolygonVertices.InsertRange(lastVisibleVertexIndex + 1, holeVerticesToAdd);
            innerRings.RemoveAt(innerRingIndex);

            return newPolygonVertices;
        }