Example #1
0
        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 "));
            }
        }
 private void RemoveTrailingZeros(List<int> list)
 {
     for (int i = list.FindLastIndex(j => j != 0) + 1; i < list.Count; i++)
     {
         list.RemoveAt(i);
         i--;
     }
 }
        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;
        }
        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);
            }
        }
        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");
            }
        }
 private string FindSummary(List<string> lines)
 {
     int index = lines.FindLastIndex(s => s.Contains(SummaryText));
     string results = "";
     if(index > -1)
     {
         results = lines[index];
     }
     return results;
 }
Example #7
0
        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();
                }
            }
        }
        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;
                        }
                    }
                }
            }
        }
Example #9
0
        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;
        }
Example #10
0
   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;
   }
Example #11
0
 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();
 }
Example #12
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();
        
        }
    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;
    }
Example #14
0
        /*
         * 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();
        }
		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);
		}
        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;
        }
        //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;
        }
        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;
        }
Example #19
0
        /// <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);
        }
		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;
		}
        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);
        }
Example #22
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 = "";
         }
     }
 }
        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);
                        }
                    }
                }
            }
        }
Example #24
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;
        }
        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;
        }
Example #26
0
        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);

        }
Example #27
0
        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;
        }
Example #28
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;
            }
        }
		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;
		}
Example #30
0
        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;
            }
        }