Example #1
0
        static void Main()
        {
            int number = 10;
            Random rand = new Random();
            List<int> myList = new List<int>();
            List<int> resultList = new List<int>();
            for (int i = 0; i < number; i++)
            {
                myList.Add(rand.Next(1, number));
            }

            foreach (var item in myList)
            {
                Console.WriteLine(item);
            }

            myList.Sort();

            Console.WriteLine("Sorted List");
            foreach (var item in myList)
            {
                Console.WriteLine(item);
            }

            int index = 0;
            int curr = myList[index];
            int counter = 0;
            Console.WriteLine(myList.LastIndexOf(curr) + "{0}", 1 / 2);

            while (index < myList.Count)
            {
                curr = myList[index];
                counter = (myList.LastIndexOf(curr) - index) + 1;
                
                if (((counter % 2) == 0) && (counter != 1))
                {
                    Console.WriteLine("in");
                    for (int i = 1; i <= counter; i++)
                    {
                        resultList.Add(curr);

                    }
                }
                index = myList.LastIndexOf(curr) + 1;


            }

            foreach (var item in resultList)
            {
                Console.WriteLine(item);
            }

        }
        private List<String> ParseParentheses(List<String> tokens)
        {
            int openingParenthesesIndex = tokens.LastIndexOf(Operators.OPEN_PARENTHESES);

            while (openingParenthesesIndex >= 0)
            {
                int closingParenthesesIndex = tokens.IndexOf(Operators.CLOSE_PARENTHESES);

                tokens = Unwind(tokens, openingParenthesesIndex, closingParenthesesIndex);

                openingParenthesesIndex = tokens.LastIndexOf(Operators.OPEN_PARENTHESES);
            }

            return tokens;
        }
Example #3
0
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is int");

        try
        {
            int[] iArray = new int[1000];
            for (int i = 0; i < 1000; i++)
            {
                iArray[i] = i;
            }
            List<int> listObject = new List<int>(iArray);
            int ob = this.GetInt32(0, 1000);
            int result = listObject.LastIndexOf(ob);
            if (result != ob)
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,result is: " + result);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
Example #4
0
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is type of string");

        try
        {
            string[] strArray = { "apple", "banana", "dog", "chocolate", "dog", "food" };
            List<string> listObject = new List<string>(strArray);
            int result = listObject.LastIndexOf("dog");
            if (result != 4)
            {
                TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,result is: " + result);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
Example #5
0
 /// <summary>
 /// Beginning at the end, of the set, return all elements until the element after the element which satifies the condition [stopAt]
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="orderedSet"></param>
 /// <param name="stopAt"></param>
 /// <returns></returns>
 static IEnumerable<TestBuilder> Filter(List<TestBuilder> orderedSet, Func<TestBuilder, bool> stopAt)
 {
     var first = orderedSet.LastOrDefault(stopAt);
     return first == null ?
         orderedSet :
         orderedSet.Skip(orderedSet.LastIndexOf(first));
 }
Example #6
0
        static void Main(string[] args)
        {
            List<String> nomes = new List<String>() { "epaminondas", "eva", "chico", "tião", "eva" };

            List<String> outrosNomes = new List<String>() { "adão", "eva", "agnaldo" };

            Console.WriteLine("quantidade de elementos: {0}", nomes.Count);
            Console.WriteLine("posição da 1a. \"eva\" dentro da lista: {0}", nomes.IndexOf("eva"));
            Console.WriteLine("posição da última \"eva\" dentro da lista: {0}", nomes.LastIndexOf("eva"));

            Console.WriteLine();

            nomes.Remove("chico");

            nomes.RemoveAll(x => x.Contains('e'));

            nomes.AddRange(outrosNomes);

            foreach (var item in nomes)
            {
                Console.WriteLine(item);
            }

            nomes.Sort();

            nomes.ForEach(new Action<string>(Imprimir));

            Console.ReadKey();
        }
Example #7
0
        static void Main(string[] args)
        {
            //creating a list
            var numbers = new List<int>() { 1, 2, 3, 4 };
            numbers.Add(1);
            numbers.AddRange(new int[3] { 5, 6, 7 });

            foreach (var number in numbers)
                Console.WriteLine(number);

            Console.WriteLine();
            Console.WriteLine("Index of 1: " + numbers.IndexOf(1));
            Console.WriteLine("Last Index of 1: " + numbers.LastIndexOf(1));

            Console.WriteLine("Count: " + numbers.Count);

            for (int i = 0; i < numbers.Count; i++)
            {
                if (numbers[i] == 1)
                    numbers.Remove(numbers[i]);
            }

            foreach (var number in numbers)
                Console.WriteLine(number);

            numbers.Clear();
            Console.WriteLine("Count: " + numbers.Count);
        }
        public static int SpanNumber(List<int> inputNumbers)
        {
            List<int> spanNumbers = new List<int>();
            for (int i = 0; i < inputNumbers.Count; i++)
            {
                if (inputNumbers.LastIndexOf(inputNumbers[i]) >= 0)
                {
                    int span = (inputNumbers.LastIndexOf(inputNumbers[i]) - i) + 1;
                    spanNumbers.Add(span);
                }
            }

            spanNumbers.Sort((a, b) => -1 * a.CompareTo(b));

            return spanNumbers[0];
        }
        public string Eval()
        {
            decimal result = 0;
            int position;
            string resultString = "";

            foreach (string line in File.ReadLines("C:\\users\\skornish\\Desktop\\prefix.txt"))
            {
                List<string> list = new List<string>(line.Split(' '));
                while (list.Contains("+") ||
                       list.Contains("-") ||
                       list.Contains("/") ||
                       list.Contains("*"))
                {
                    position = 0;
                    foreach (string element in list)
                    {
                        if (element.Equals("+") ||
                            element.Equals("-") ||
                            element.Equals("/") ||
                            element.Equals("*"))
                        {
                            position = Math.Max(position, list.LastIndexOf(element));
                        }
                    }

                    if (list.ElementAt(position).Equals("+"))
                    {
                        result = decimal.Parse(list.ElementAt(position + 1)) +
                                 decimal.Parse(list.ElementAt(position + 2));
                    }
                    else if (list.ElementAt(position).Equals("-"))
                    {
                        result = decimal.Parse(list.ElementAt(position + 1)) -
                                 decimal.Parse(list.ElementAt(position + 2));
                    }
                    else if (list.ElementAt(position).Equals("/"))
                    {
                        result = decimal.Parse(list.ElementAt(position + 1)) /
                                 decimal.Parse(list.ElementAt(position + 2));
                    }
                    else if (list.ElementAt(position).Equals("*"))
                    {
                        result = decimal.Parse(list.ElementAt(position + 1)) *
                                 decimal.Parse(list.ElementAt(position + 2));
                    }
                    list.Insert(position, result.ToString());
                    list.RemoveAt(position + 3);
                    list.RemoveAt(position + 2);
                    list.RemoveAt(position + 1);
                }
                resultString = resultString + "," + result.ToString();
            }

            MessageBox.Show(resultString);
            return resultString;
        }
Example #10
0
        static void Main(string[] args)
        {
            List<int> MyList = new List<int>();

            string l = Console.ReadLine();

            while (l != string.Empty)
            {

                MyList.Add(int.Parse(l));

                l = Console.ReadLine();
            }

            MyList.Sort();

            int index = 0;

            int curr = 0;

            bool isMajorant = false;

            while (index < MyList.Count)
            {
                curr = MyList[index];

                int counter = MyList.LastIndexOf(curr) - index + 1;

                if (counter > (MyList.Count / 2))
                {
                    Console.WriteLine("The majorant is: {0} -> {1} times", curr, counter);

                    isMajorant = true;
                }

                index = MyList.LastIndexOf(curr) + 1;

            }

            if (!isMajorant)
            {
                Console.WriteLine("The majorant does't exist");
            }
        }
Example #11
0
        static void Main()
        {
            int number = 1000;

            Random rand = new Random();
            List<int> myList = new List<int>();
            int[] countingArr = new int[number];

            for (int i = 0; i < 30; i++)
            {
                myList.Add(rand.Next(0, 30));
            }

            myList.Sort();

            int index = 0;
            int curr = myList[index];

            while (index < myList.Count)
            {
                curr = myList[index];
                int counter = myList.LastIndexOf(curr) - index + 1;
                countingArr[index] = counter;

                index = myList.LastIndexOf(curr) + 1;

            }

            for (int i = 0; i < countingArr.Length; i++)
            {
                if (countingArr[i] > 0)
                {
                    Console.WriteLine("Number {0} -> {1}", i, countingArr[i]);
                }
            }

            //foreach (var item in countingArr)
            //{
            //    if (item > 0)
            //    {
            //        Console.WriteLine("Number {0} -> {1}", Array.IndexOf(countingArr, item), item);
            //    }
            //}
        }
Example #12
0
        public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 2);
            var number = ArgToDecimal(arguments, 0);
            var refer = arguments.ElementAt(1);
            bool asc = false;
            if (arguments.Count() > 2)
            {
                asc = base.ArgToBool(arguments, 2);
            }
            var l = new List<double>();

            foreach (var c in refer.ValueAsRangeInfo)
            {
                var v = Utils.ConvertUtil.GetValueDouble(c.Value, false, true);
                if (!double.IsNaN(v))
                {
                    l.Add(v);
                }
            }
            l.Sort();
            double ix;
            if (asc)
            {
                ix = l.IndexOf(number)+1;
                if(_isAvg)
                {
                    int st = Convert.ToInt32(ix);
                    while (l.Count > st && l[st] == number) st++;
                    if (st > ix) ix = ix + ((st - ix) / 2D);
                }
            }
            else
            {
                ix = l.LastIndexOf(number);
                if (_isAvg)
                {
                    int st = Convert.ToInt32(ix)-1;
                    while (0 <= st && l[st] == number) st--;
                    if (st+1 < ix) ix = ix - ((ix - st - 1) / 2D);
                }
                ix = l.Count - ix;
            }
            if (ix <= 0 || ix>l.Count)
            {
                return new CompileResult(ExcelErrorValue.Create(eErrorType.NA), DataType.ExcelError);
            }
            else
            {
                return CreateResult(ix, DataType.Decimal);
            }
        }
Example #13
0
        static void Main()
        {
            int number = 10;

            Random rand = new Random();
            List<int> myList = new List<int>();
            List<int> resultList = new List<int>();
            for (int i = 0; i < number; i++)
            {
                myList.Add(rand.Next(1, number));
            }

            foreach (var item in myList)
            {
                Console.WriteLine(item);
            }

            myList.Sort();

            Console.WriteLine("Sorted List");
            foreach (var item in myList)
            {
                Console.WriteLine(item);
            }
            int index = 0;
            int curr = myList[index];

            while (index < myList.Count)
            {
                curr = myList[index];
                var newL = myList.FindAll(i => i.Equals(curr));
                if ((newL.Count % 2) == 0)
                {
                    foreach (var item1 in newL)
                    {
                        resultList.Add(item1);
                    }
                }

                newL.Clear();
                index = myList.LastIndexOf(curr) + 1;
            } 

            Console.WriteLine("Result list");
            foreach (var a in resultList)
            {
                Console.WriteLine(a);
            }


        }
Example #14
0
        static void Main()
        {
            List<int> myList = new List<int>();
            string line = Console.ReadLine();

            while (line != string.Empty)
            {

                myList.Add(int.Parse(line));
                line = Console.ReadLine();
            }

            myList.Sort();
            int index = 0;
            int curr = 0;
            bool isMajorant = false;

            while (index < myList.Count)
            {
                curr = myList[index];
                int counter = myList.LastIndexOf(curr) - index + 1;
                if (counter > (myList.Count /2))
                {
                    Console.WriteLine("The majorant is: {0} -> {1} times", curr, counter);
                    isMajorant = true;
                }
                

                index = myList.LastIndexOf(curr) + 1;

            }

            if (!isMajorant)
            {
                Console.WriteLine("The majorant does not exists!");
            }

        }
Example #15
0
        static void Main(string[] args)
        {
            int n = 1000;

            Random rand = new Random();
            List<int> List = new List<int>();
            int[] countingArr = new int[n];

            for (int i = 0; i < 30; i++)
            {
                List.Add(rand.Next(0, 30));
            }

            List.Sort();

            int index = 0;
            int curr = List[index];

            while (index < List.Count)
            {
                curr = List[index];
                int counter = List.LastIndexOf(curr) - index + 1;
                countingArr[index] = counter;

                index = List.LastIndexOf(curr) + 1;

            }

            for (int i = 0; i < countingArr.Length; i++)
            {
                if (countingArr[i] > 0)
                {
                    Console.WriteLine("Number {0} -> {1}", i, countingArr[i]);
                }
            }
        }
        /// <summary>
        /// Finds the biggest span between a leftmost and rightmost appearance of some value.
        /// </summary>
        /// <param name="numbers">List input.</param>
        /// <returns>Biggest span.</returns>
        public static int MaxSpan(List<int> numbers)
        {
            List<int> spanCounters = new List<int>();
            for (int i = 0; i < numbers.Count; i++)
            {
                int lastindexof = numbers.LastIndexOf(numbers[i]);
                if (lastindexof != -1)
                {
                    var spanCounter = (lastindexof - i) + 1;
                    spanCounters.Add(spanCounter);
                }
            }

            spanCounters.Sort((a, b) => -1 * a.CompareTo(b));
            return spanCounters[0];
        }
Example #17
0
    public static List<int> addJump(List<int> path, int n)
    {
        var position = path.LastIndexOf((int)Way.step);

        if (position < 0)
        {
            return null;
        }

        path[position] = (int)Way.jump;

        if (position > 0)
        {
            path.RemoveAt(position - 1);
        }

        return path.Sum() == n ? path : null;
    }
Example #18
0
        static List<string> Reorder(string[] words)
        {
            List<string> listOfWords = new List<string>(words);

            for (int i = 0; i < listOfWords.Count; i++)
            {
                string currentWord = listOfWords[i];
                int position = (currentWord.Length % (words.Length + 1));
                listOfWords.Insert(position, currentWord);
                if (position > i)
                {
                    listOfWords.RemoveAt(listOfWords.IndexOf(currentWord));
                }
                else
                {
                    listOfWords.RemoveAt(listOfWords.LastIndexOf(currentWord));
                }
            }
            return listOfWords;
        }
Example #19
0
 // this solution borrows heavily from solutions proposed by others
 public string Run()
 {
     int max = 0;
     int maxCycleLen = 0;
     List<int> remainders;
     for (int i = 983; i < 1000; i++)
     {
         int r = 10, count;
         remainders = new List<int>();
         for (count = 0; !remainders.Contains(r); count++)
         {
             remainders.Add(r);
             r = 10 * (r % i);
         }
         int cycleLen = count - remainders.LastIndexOf(r);
         if (cycleLen > maxCycleLen)
         {
             maxCycleLen = cycleLen;
             max = i;
         }
     }
     return max.ToString();
 }
Example #20
0
        private void tsmiCViewInCrawlResultView_Click(object sender, EventArgs e)
        {
            List<int> rowIndices = new List<int>();
            foreach (DataGridViewCell cell in this.dgvContent.SelectedCells) {
                int rowIndex = cell.RowIndex;
                if(rowIndices.LastIndexOf(rowIndex) < 0){
                    rowIndices.Add(rowIndex);
                }
            }
            rowIndices.Sort();

            List<GContentClass> conts = new List<GContentClass>();
            foreach (int idx in rowIndices) {
                DataGridViewRow dgvRow = this.dgvContent.Rows[idx];
                DataRowView drv = dgvRow.DataBoundItem as DataRowView;
                if(drv == null) continue;
                GDataSet.GContentRow row = drv.Row as GDataSet.GContentRow;
                GContentClass cont;
                if (Program.CacheController.TryFindContent(row.ContentKey, out cont)) {
                    conts.Add(cont);
                }
            }
            Program.AddVirtualGenre(new SimpleContentsVirtualGenre(conts, "キャッシュビューア", "キャッシュビューアからの書き出し" + Environment.NewLine + DateTime.Now.ToString()));
        }
Example #21
0
 public static int lastIndexOf <T>(this List <T> it, T item) => it.LastIndexOf(item);
Example #22
0
        //Берем две подряд идущие строки
        //Разделяем строки на колонки, пропуская колонки с датой, временем, объемом, максимумом и минимумом
        //Проверяем оставшиеся колонки на соответствие шаблонам чисел
        //Остается две колонки в каждой строке
        //Добавляем их индексы в массив voc в порядке возрастания
        //Проверяем, есть ли две такие колонки в обеих подстроках с разными индексами, чьи значения равны
        //Если да, то
        //Делаем предположение, что в первой подстроке - это закрытие, а во второй - открытие
        //Прибавляем значение соответствующей переменной, отвечающей за порядок (oc - OpenClose, co - CloseOpen)
        //Если одна из переменных больше, чем 80% длины массива doc, то возвращаем словарь с ключами "Open" и "Close" и их индексами
        //Если условие не выполнено, то предполагаем, что индекс колонки открытия меньше индекса колонки закрытия и возвращаем соответствующий словарь
        public Dictionary <string, int> GetOpenCloseColumns(string[] doc)
        {
            Dictionary <string, int> openclose = new Dictionary <string, int>();
            int date   = GetDateColumn(doc);
            int time   = GetTimeColumn(doc);
            int volume = GetVolumeColumn(doc);
            int max    = GetHighColumn(doc);
            int min    = GetLowColumn(doc);
            int oc     = 0;
            int co     = 0;

            int[]         voc = new int[2];
            List <string> str = new List <string>();

            for (int i = GetSkipRowsCount(doc); i < doc.Length - 1; i++)
            {
                string[] row = doc[i].Split(GetColumnSeparator(doc));
                if (row.Distinct().Count() == row.Length)
                {
                    for (int j = 0; j < row.Length; j++)
                    {
                        if (j == date || j == time || row[j] == string.Empty || j == volume || j == max || j == min)
                        {
                            continue;
                        }
                        foreach (KeyValuePair <string, string> pair in Patterns.Decimal)
                        {
                            if (Regex.IsMatch(row[j], pair.Value))
                            {
                                str.Add(row[j]);
                            }
                        }
                        ;
                    }
                    voc[0] = row.ToList().IndexOf(str[1]);
                    voc[1] = row.ToList().IndexOf(str[0]);
                    Array.Sort(voc);
#if DEBUG
                    Console.WriteLine(voc[0] + " " + voc[1]);
#endif

                    break;
                }
            }

            for (int i = GetSkipRowsCount(doc); i < doc.Length - 1; i++)
            {
                List <string> row1   = new List <string>();
                string[]      first  = doc[i].Split(GetColumnSeparator(doc));
                List <string> row2   = new List <string>();
                string[]      second = doc[i + 1].Split(GetColumnSeparator(doc));


                for (int j = 0; j < first.Length; j++)
                {
                    if (j == date || j == time || first[j] == string.Empty || j == volume || j == max || j == min)
                    {
                        continue;
                    }

                    foreach (KeyValuePair <string, string> pair in Patterns.Decimal)
                    {
                        if (Regex.IsMatch(first[j], pair.Value))
                        {
                            row1.Add(first[j]);
                        }
                    }

                    foreach (KeyValuePair <string, string> pair in Patterns.Decimal)
                    {
                        if (Regex.IsMatch(second[j], pair.Value))
                        {
                            row2.Add(second[j]);
                        }
                    }
                }

                foreach (string sub1 in row1)
                {
                    foreach (string sub2 in row2)
                    {
                        if (row1.IndexOf(sub1) == row2.LastIndexOf(sub2) || row1.LastIndexOf(sub1) == row2.IndexOf(sub2))
                        {
                            continue;
                        }
                        if (sub1 == sub2)
                        {
                            int open  = 0;
                            int close = 0;

                            for (int j = 0; j < first.Length; j++)
                            {
                                if (j == date || j == time || first[j] == string.Empty || j == volume || j == max || j == min)
                                {
                                    continue;
                                }
                                if (first[j] == sub1)
                                {
                                    close = j;
                                }
                            }

                            for (int j = 0; j < second.Length; j++)
                            {
                                if (j == date || j == time || second[j] == string.Empty || j == volume || j == max || j == min)
                                {
                                    continue;
                                }
                                if (second[j] == sub2)
                                {
                                    open = j;
                                }
                            }

                            if (open > close)
                            {
                                co++;
                            }
                            else if (close > open)
                            {
                                oc++;
                            }
                        }
                    }
                }
            }

            if (oc >= (int)(((double)doc.Length) * 0.8))
            {
#if DEBUG
                Console.WriteLine("OpenClose");
#endif
                openclose.Add("Open", voc[0]);
                openclose.Add("Close", voc[1]);
                return(openclose);
            }

            if (co >= (int)(((double)doc.Length) * 0.8))
            {
#if DEBUG
                Console.WriteLine("CloseOpen");
#endif
                openclose.Add("Open", voc[1]);
                openclose.Add("Close", voc[0]);
                return(openclose);
            }
#if DEBUG
            Console.WriteLine("OpenClose <80%");
#endif
            openclose.Add("Open", voc[0]);
            openclose.Add("Close", voc[1]);
            return(openclose);
        }
Example #23
0
        static void Main(string[] args)
        {
            int status = 0;

            string[] argument = args;
            string   data     = "";

            List <string> dataParts   = new List <string>();
            List <string> expressions = new List <string>();
            List <string> result      = new List <string>();


            try{
                StreamReader sr = new StreamReader(argument[0]);
                while (!sr.EndOfStream)
                {
                    data = sr.ReadLine();
                    expressions.Add(data);
                    expressions.Add(@"\\n");
                }

                int index = expressions.LastIndexOf(@"\\n");
                expressions.RemoveAt(index);
            }
            catch {
                foreach (string arg in argument)
                {
                    if (arg != null)
                    {
                        expressions.Add(arg);
                    }
                }
            }

            foreach (string expression in expressions)
            {
                string[] elements = expression.Split(' ');
                foreach (string elem in elements)
                {
                    dataParts.Insert(dataParts.Count, elem);
                }
            }



            foreach (string part in dataParts)
            {
                if ((Int32.Parse(part[0].ToString()) >= 97 && Int32.Parse(part[0].ToString()) <= 122) && status == 0)
                {
                    String identificador = "";
                    for (int i = 0; i < part.Length; i++)
                    {
                        if ((Int32.Parse(part[i].ToString()) >= 97 && Int32.Parse(part[i].ToString()) <= 122) && status == 0)
                        {
                            identificador = identificador + part[i];
                            status        = 1;
                        }
                        if ((Int32.Parse(part[i].ToString()) >= 65 && Int32.Parse(part[i].ToString()) <= 90) && status == 1)
                        {
                            identificador = identificador + part[i];
                        }
                        if (Int32.Parse(part[i].ToString()) >= 97 && Int32.Parse(part[i].ToString()) <= 122 && status == 1)
                        {
                            identificador = identificador + part[i];
                        }
                        if (Int32.Parse(part[i].ToString()) == 95 && status == 1)
                        {
                            identificador = identificador + part[i];
                        }
                    }
                    result.Add("<identificador, " + identificador + ">");
                    continue;
                }
                if (Int32.Parse(part) == 52 && status == 1)
                {
                    result.Add("<multiplicacao,>");
                    status = 0;
                    continue;
                }
                if (Int32.Parse(part) == 53 && status == 1)
                {
                    result.Add("<adição,>");
                    status = 0;
                    continue;
                }
                if (Int32.Parse(part) == 55 && status == 1)
                {
                    result.Add("<subtração,>");
                    status = 0;
                    continue;
                }
                if (Int32.Parse(part) == 57 && status == 1)
                {
                    result.Add("<divisão,>");
                    status = 0;
                    continue;
                }
                else
                {
                    Console.WriteLine(part);
                    Console.WriteLine(status);
                    foreach (string expr in expressions)
                    {
                        Console.Write(expr);
                        Console.Write(" ");
                    }
                    Console.WriteLine("Expressão não reconhecida");
                    return;
                }
            }


            foreach (string res in result)
            {
                if (status == 0)
                {
                    foreach (string expr in expressions)
                    {
                        Console.Write(expr);
                        Console.Write(" ");
                    }
                    Console.WriteLine("Expressão não reconhecida");
                    return;
                }
                Console.WriteLine(res);
            }

            return;
        }
Example #24
0
 public int LastIndexOf(T item, int index, int count)
 {
     return(list.LastIndexOf(item, index, count));
 }
 public int IndexOf(string item)
 {
     return(_extensions.LastIndexOf(convert(item)));
 }
Example #26
0
 public int LastIndexOf(T item)
 {
     return(list.LastIndexOf(item));
 }
Example #27
0
        public static void ListSort()
        {
            shipsList.Sort();
            string name = InputName();
            bool   ok   = false;

            foreach (Ship ship in shipsList)
            {
                if (ship.Name == name)
                {
                    Console.WriteLine($"Элемент с именем {name} находится на позиции {shipsList.LastIndexOf(ship)}");
                    ok = true;
                }
            }
            if (!ok)
            {
                Console.WriteLine("Такого элемента нет");
            }
        }
Example #28
0
		/*
		 * Matches a method against its arguments in the Lua stack. Returns
		 * if the match was successful. It it was also returns the information
		 * necessary to invoke the method.
		 */
		internal bool MatchParameters (LuaState luaState, MethodBase method, ref MethodCache methodCache)
		{
			ExtractValue extractValue;
			bool isMethod = true;
			var paramInfo = method.GetParameters ();
			int currentLuaParam = 1;
			int nLuaParams = LuaLib.LuaGetTop (luaState);
			var paramList = new List<object> ();
			var outList = new List<int> ();
			var argTypes = new List<MethodArgs> ();

			foreach (var currentNetParam in paramInfo) {
#if !SILVERLIGHT
				if (!currentNetParam.IsIn && currentNetParam.IsOut)  // Skips out params 
#else
				if (currentNetParam.IsOut)  // Skips out params
#endif
				{					
					paramList.Add (null);
					outList.Add (paramList.LastIndexOf (null));
				}  else if (IsTypeCorrect (luaState, currentLuaParam, currentNetParam, out extractValue)) {  // Type checking
					var value = extractValue (luaState, currentLuaParam);
					paramList.Add (value);
					int index = paramList.LastIndexOf (value);
					var methodArg = new MethodArgs ();
					methodArg.index = index;
					methodArg.extractValue = extractValue;
					argTypes.Add (methodArg);

					if (currentNetParam.ParameterType.IsByRef)
						outList.Add (index);

					currentLuaParam++;
				}  // Type does not match, ignore if the parameter is optional
				else if (IsParamsArray (luaState, currentLuaParam, currentNetParam, out extractValue)) {

					var paramArrayType = currentNetParam.ParameterType.GetElementType ();

					Func<int, object> extractDelegate = (currentParam) => {
						currentLuaParam ++;
						return extractValue (luaState, currentParam);
					};
					int count = (nLuaParams - currentLuaParam) + 1;
					Array paramArray = TableToArray (extractDelegate, paramArrayType, currentLuaParam, count);

					paramList.Add (paramArray);
					int index = paramList.LastIndexOf (paramArray);
					var methodArg = new MethodArgs ();
					methodArg.index = index;
					methodArg.extractValue = extractValue;
					methodArg.isParamsArray = true;
					methodArg.paramsArrayType = paramArrayType;
					argTypes.Add (methodArg);

				} else if (currentLuaParam > nLuaParams) { // Adds optional parameters
					if (currentNetParam.IsOptional)
						paramList.Add (currentNetParam.DefaultValue);
					else {
						isMethod = false;
						break;
					}
				} else if (currentNetParam.IsOptional)
					paramList.Add (currentNetParam.DefaultValue);
				else {  // No match
					isMethod = false;
					break;
				}
			}

			if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match
				isMethod = false;
			if (isMethod) {
				methodCache.args = paramList.ToArray ();
				methodCache.cachedMethod = method;
				methodCache.outList = outList.ToArray ();
				methodCache.argTypes = argTypes.ToArray ();
			}
			return isMethod;
		}
Example #29
0
 public static void CleanMusicList(ref CListView D)
 {
     List<String> Tracks = new List<string>();
     List<ListViewItem> itemsToRemove = new List<ListViewItem>();
     foreach(ListViewItem X in D.Items)
     {
         Song _Song = MainForm.ItemToSong(X);
         if(Tracks.LastIndexOf(_Song.Title.ToLower()+" - "+_Song.Artist.ToLower())>-1)
         {
             itemsToRemove.Add(X);
         }
         else
         {
             Tracks.Add(_Song.Title.ToLower() + " - "+_Song.Artist.ToLower());
         }
     }
     foreach(ListViewItem R in itemsToRemove)
     {
         D.Items.Remove(R);
     }
 }
Example #30
0
 public void setSectOrderedList(string section, string[] tab)
 {
     List<string> sections = new List<string>();
     foreach (INILine line in iniContent) sections.Add(line.section);
     string iSection = section.ToLower(Statics.Culture);
     int firstIndex = sections.IndexOf(iSection);
     int lastIndex = sections.LastIndexOf(iSection);
     if (firstIndex == -1) {
         if (iniContent.Count > 0) {
             INILine line = iniContent[iniContent.Count - 1];
             if (line.entry != "" || line.comment != "") {
                 INILine.setSection = line.section;
                 iniContent.Add(new INILine(""));
                 firstIndex++;
             }
         }
         INILine.setSection = section;
         firstIndex = lastIndex = iniContent.Count;
         iniContent.Add(new INILine("[" + section + "]"));
     }
     int tabIndex = 0;
     int tabCount = tab.Length - 1;
     while (++firstIndex <= lastIndex && tabIndex <= tabCount) {
         INILine line = iniContent[firstIndex];
         if (line.entry != "" && line.comment != "") {
             line.entry = INIComment + line.entry;
         }
         else if (line.comment != "") continue;
         else {
             line.entry = tab[tabIndex++];
         }
     }
     while (firstIndex <= lastIndex) iniContent.RemoveAt(lastIndex--);
     iniContent.Insert(firstIndex, new INILine(""));
     INILine.setSection = section;
     while (tabCount >= tabIndex) {
         iniContent.Insert(firstIndex, new INILine(tab[tabCount--]));
     }
     modified = true;
 }
Example #31
0
 public bool LastCastHit(Spell spell)
 {
     return(SeriesHits[Series.LastIndexOf(spell)]);
 }
Example #32
0
 public int LastIndexOf(Tryte @char)
 {
     return(_Chars.LastIndexOf(@char));
 }
Example #33
0
        public override void Go()
        {
            Start : Console.Clear();
            Console.WriteLine("Task5");
            Console.WriteLine("Дан двумерный массив размерностью 5х5,\n" +
                              "заполненный случайными числами из диапазона от -100 до 100 ***.\n" +
                              "Определить сумму элементов массива, расположенных между минимальным и максимальным элементами***.\n" +
                              "(МАКСИМАЛЬНО УДАЛЕННЫМИ друг от друга)\n");
            int[,] array = new int[5, 5];
            List <int> arr = new List <int>();

            fillRandom(array);
            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    arr.Add(array[i, j]);
                }
            }
            Console.WriteLine();
            Console.Write("| index |");
            for (int i = 0; i < 25; i++)
            {
                Console.Write("  " + i + "\t|");
            }
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.Write("| value |");
            foreach (int el in arr)
            {
                Console.Write("  " + el + "\t|");
            }
            Console.ResetColor();
            Console.WriteLine();
            int minElement    = arr.Min();
            int maxElement    = arr.Max();
            int LeftIndexMIN  = arr.IndexOf(minElement);
            int RightIndexMIN = arr.LastIndexOf(minElement);
            int LeftIndexMAX  = arr.IndexOf(maxElement);
            int RightIndexMAX = arr.LastIndexOf(maxElement);

            Console.WriteLine();
            Console.WriteLine("minElement = " + minElement +
                              "\nIndex left - right: " + LeftIndexMIN + " - " + RightIndexMIN);
            Console.WriteLine("maxElelement = " + maxElement +
                              "\nIndex left - right: " + LeftIndexMAX + " - " + RightIndexMAX);
            Console.WriteLine();
            List <int> result = new List <int>();
            int        maxDistance;
            int        maxDistanceTemp;

            Console.ForegroundColor = ConsoleColor.Magenta;
            if (LeftIndexMIN < LeftIndexMAX)
            {
                maxDistance = RightIndexMAX - LeftIndexMIN;
                result.Add(sum(arr, LeftIndexMIN, RightIndexMAX));
                if (RightIndexMAX < RightIndexMIN)
                {
                    maxDistanceTemp = RightIndexMIN - LeftIndexMAX;
                    if (maxDistanceTemp > maxDistance)
                    {
                        result[0] = sum(arr, LeftIndexMAX, RightIndexMIN);
                    }
                    else if (maxDistanceTemp == maxDistance)
                    {
                        result.Add(sum(arr, LeftIndexMAX, RightIndexMIN));
                        Console.Write("  ПОЛУЧАЕМ ДВЕ");
                    }
                }
            }
            else //(maxLeftIndex < minLeftIndex)
            {
                maxDistance = RightIndexMIN - LeftIndexMAX;
                result.Add(sum(arr, LeftIndexMAX, RightIndexMIN));
                if (RightIndexMIN < RightIndexMAX)
                {
                    maxDistanceTemp = RightIndexMAX - LeftIndexMIN;
                    if (maxDistanceTemp > maxDistance)
                    {
                        result[0] = sum(arr, LeftIndexMIN, RightIndexMAX);
                    }
                    else if (maxDistanceTemp == maxDistance)
                    {
                        result.Add(sum(arr, LeftIndexMIN, RightIndexMAX));
                        Console.Write("  ПОЛУЧАЕМ ДВЕ");
                    }
                }
            }
            Console.WriteLine("  Cумма(-Ы) элементов массива," +
                              " расположенных между минимальным и максимальным элементами\n" +
                              " (МАКСИМАЛЬНО УДАЛЕННЫМИ друг от друга):");
            Console.WriteLine();
            foreach (int sum in result)
            {
                Console.WriteLine("\tСУММА = " + sum);
            }
            Console.ResetColor();
            Console.WriteLine("\nВЫХОД  - ESK -\n");
            if (Console.ReadKey().Key != ConsoleKey.Escape)
            {
                goto Start;
            }
        }
Example #34
0
        static void Main(string[] args)
        {
            Customer c1 = new Customer()
            {
                ID     = 101,
                Name   = "Aatank",
                Salary = 4000,  // $/per hour :P
                Type   = " Regular"
            };
            Customer c2 = new Customer()
            {
                ID     = 102,
                Name   = "Agent 48",
                Salary = 5000, // $/per hour :P
                Type   = " Regular"
            };
            Customer c3 = new Customer()
            {
                ID     = 103,
                Name   = "popa",
                Salary = 4500, // $/per hour :P
                Type   = " Regular"
            };
            Customer c4 = new Customer()
            {
                ID     = 104,
                Name   = "Chedi",
                Salary = 35000, // $/per hour :P
                Type   = " Non regular"
            };
            Customer c5 = new Customer()
            {
                ID     = 105,
                Name   = "Hurt Locker",
                Salary = 5500, // $/per hour :P
                Type   = " Non regular"
            };
            List <Customer> list = new List <Customer>();

            //list.Add(c1);
            //list.Add(c2);
            //list.Add(c3);

            list.AddRange(new List <Customer>()
            {
                c1, c2, c3
            });
            List <Customer> ListNonRegular = new List <Customer>();

            ListNonRegular.Add(c4);
            ListNonRegular.Add(c5);

            //foreach (Customer i in list)
            //{
            //    Console.WriteLine("Id ={0}, Name={1}, Salary={2}", i.ID, i.Name, i.Salary);
            //}
            list.AddRange(ListNonRegular);
            Customer c6;
            int      c4LastIndex;

            //list.Insert(0, c4);
            // list.InsertRange(0, ListNonRegular);
            Console.WriteLine("list contains C2 ={0}", list.Contains(c2));
            Console.WriteLine("list.Exists(cust => cust.Salary > 4000)= {0}", list.Exists(cust => cust.Salary > 4000));
            c4LastIndex = list.LastIndexOf(c4);
            Console.WriteLine("last index od c4 is" + c4LastIndex);

            foreach (Customer i in list)
            {
                Console.WriteLine("Id ={0}, Name={1}, Salary={2}", i.ID, i.Name, i.Salary);
            }
            Console.Read();
        }
Example #35
0
        static void Main(string[] args)
        {
            //1. Create a one - dimensional Array of strings.
            //Ask the user to input some text.
            //Create a loop that goes through each string in the Array, adding the user’s text to the string.
            //Then create a loop that prints off each string in the Array on a separate line.
            string[] badPasswords = { "123456",   "password", "123456789", "12345678", "12345",    "111111",
                                      "1234567",  "sunshine", "qwerty",    "iloveyou", "princess", "admin",   "Admin",
                                      "Password", "welcome",  "4444",      "abc123",   "123123",   "!@#$%^&*","donald" };
            Console.WriteLine("Please add to my bad password list. Please input a bad password: "******"Curtis");
            names.Add("Dave");
            names.Add("Misty");
            names.Add("Adolfo");
            names.Add("Kevin");
            names.Add("Corey");
            names.Add("Guillermo");
            names.Add("Steven");
            names.Add("Eva");

            Console.WriteLine("Please type a name from the provided list: ");
            string input7 = Console.ReadLine();

            int index = names.FindIndex(s => s == input7);

            for (int i = 0; i < names.Count; i++)
            {
                if (input7.Contains(names[i]))
                {
                    Console.WriteLine(names[i] + index + " is in my list of names. ");
                }
            }
            Console.ReadLine();

            //7. Add code to that above loop that tells a user if they put in text that isn’t in the List.
            List <string> names1 = new List <string>();

            names1.Add("Curtis");
            names1.Add("Dave");
            names1.Add("Misty");
            names1.Add("Adolfo");
            names1.Add("Kevin");
            names1.Add("Corey");
            names1.Add("Guillermo");
            names1.Add("Steven");
            names1.Add("Eva");

            Console.WriteLine("Please search for the name Kevin: ");
            string input1 = Console.ReadLine();

            for (int j = 0; j < names1.Count; j++)
            {
                if (input1 != names1[j])
                {
                    Console.WriteLine(input1 + " does not exist.");
                    break;
                }
                else if (input1.Contains(names1[j]))
                {
                    Console.WriteLine("The name " + input1 + " is on my list.");
                    break;
                }
            }
            Console.ReadLine();

            //8. Add code to that above loop that stops it from executing once a match has been found.
            List <string> names2 = new List <string>();

            names2.Add("Curtis");
            names2.Add("Dave");
            names2.Add("Misty");
            names2.Add("Adolfo");
            names2.Add("Kevin");
            names2.Add("Corey");
            names2.Add("Guillermo");
            names2.Add("Steven");
            names2.Add("Eva");

            Console.WriteLine("Please type a name from the provided list: ");
            string input2 = Console.ReadLine();

            for (int k = 0; k < names2.Count; k++)
            {
                if (input2.Contains(names2[k]))
                {
                    Console.WriteLine(names2[k] + " is in my list of names. ");
                    break;
                }
            }
            Console.ReadLine();

            //9. Create a List of strings that has at least two identical strings in the List.
            //Ask the user to select text to search for in the List. Create a loop that iterates through the list and then
            //displays the indices of the array that contain matching text on the screen.
            List <string> names12 = new List <string> {
                "Curtis", "Dave", "Misty", "Adolfo", "Kevin", "Corey", "Guillermo", "Steven", "Eva", "Dave"
            };

            Console.WriteLine("Please search for a name on my list: ");
            string input3 = Console.ReadLine();

            for (int k = 0; k < names12.Count; k++)
            {
                if (names12[k] == input3)
                {
                    Console.WriteLine(input3 + k);
                }
            }
            Console.ReadLine();

            //10. Add code to that above loop that tells a user if they put in text that isn’t in the List.
            List <string> names12 = new List <string> {
                "Curtis", "Dave", "Misty", "Adolfo", "Kevin", "Corey", "Guillermo", "Steven", "Eva", "Dave"
            };

            Console.WriteLine("Please search for a name on my list: ");
            string input3 = Console.ReadLine();

            for (int k = 0; k < names12.Count; k++)
            {
                if (names12[k] == input3)
                {
                    Console.WriteLine(input3 + k);
                }
                else if (input3 != names12[k])
                {
                    Console.WriteLine(input3 + " Does not match my list.");
                    break;
                }
            }
            Console.ReadLine();

            //11. Create a List of strings that has at least two identical strings in the List.
            Create a foreach loop that evaluates each item in the list, and displays a message showing the string and
            whether or not it has already appeared in the list.

            List <string> x = new List <string>()
            {
                "Curtis", "Dave", "Misty", "Adolfo", "Kevin", "Corey", "Guillermo", "Steven", "Eva", "Dave"
            };

            foreach (string s in x)
            {
                foreach (string l in x)
                {
                    if ((s == l) && (x.IndexOf(s) != x.LastIndexOf(l)) && ((x.IndexOf(s) < x.LastIndexOf(l))))
                    {
                        Console.WriteLine(s + " is on the list multiple times. ");
                    }
                }
            }

            IEnumerable <string> y = x.AsQueryable().Distinct();

            List <string> n = y.ToList();

            var duplicates = n
                             .GroupBy(b => b)
                             .Where(g => g.Skip(1).Any())
                             .SelectMany(g => g);

            foreach (string s in n)
            {
                if (n != y)
                {
                    Console.WriteLine("These are the names contained within my list: " + s);
                }
                else
                {
                    Console.WriteLine("You have failed... ");
                }
            }
            Console.ReadLine();
        }
Example #36
0
        //Order the {@link #insertions} queue such that we group inserts
        //against the same entity together (without violating constraints).  The
        //original order is generated by cascade order, which in turn is based on
        //the directionality of foreign-keys. So even though we will be changing
        //the ordering here, we need to make absolutely certain that we do not
        //circumvent this FK ordering to the extent of causing constraint
        //violations
        private void SortInsertActions()
        {
            // IMPLEMENTATION NOTES:
            //
            // The main data structure in this ordering algorithm is the 'positionToAction'
            // map. Essentially this can be thought of as an put-ordered map (the problem with
            // actually implementing it that way and doing away with the 'nameList' is that
            // we'd end up having potential duplicate key values).  'positionToAction' maitains
            // a mapping from a position within the 'nameList' structure to a "partial queue"
            // of actions.

            Dictionary<int,List<EntityInsertAction>> positionToAction =
                new Dictionary<int, List<EntityInsertAction>>();
            List<string> nameList = new List<string>();

            while (!(insertions.Count == 0))
            {
                // todo-events : test behaviour
                // in Java they use an implicit cast to EntityInsertAction
                // but it may be not work because the insertions list may contain EntityIdentityInsertAction
                // (I don't like that "goto"too)
                object tempObject = insertions[0];
                insertions.RemoveAt(0);
                EntityInsertAction action = (EntityInsertAction)tempObject;
                string thisEntityName = action.EntityName;

                // see if we have already encountered this entity-name...
                if (!nameList.Contains(thisEntityName))
                {
                    // we have not, so create the proper entries in nameList and positionToAction
                    List<EntityInsertAction> segmentedActionQueue = new List<EntityInsertAction>();
                    segmentedActionQueue.Add(action);
                    nameList.Add(thisEntityName);
                    positionToAction[nameList.IndexOf(thisEntityName)] = segmentedActionQueue;
                }
                else
                {
                    // we have seen it before, so we need to determine if this insert action is
                    // is depenedent upon a previously processed action in terms of FK
                    // relationships (this FK checking is done against the entity's property-state
                    // associated with the action...)
                    int lastPos = nameList.LastIndexOf(thisEntityName);
                    object[] states = action.State;
                    for (int i = 0; i < states.Length; i++)
                    {
                        for (int j = 0; j < nameList.Count; j++)
                        {
                            List<EntityInsertAction> tmpList = positionToAction[j];
                            for (int k = 0; k < tmpList.Count; k++)
                            {
                                EntityInsertAction checkAction = tmpList[k];
                                if (checkAction.Instance == states[i] && j > lastPos)
                                {
                                    // 'checkAction' is inserting an entity upon which 'action' depends...
                                    // note: this is an assumption and may not be correct in the case of one-to-one
                                    List<EntityInsertAction> segmentedActionQueue = new List<EntityInsertAction>();
                                    segmentedActionQueue.Add(action);
                                    nameList.Add(thisEntityName);
                                    positionToAction[nameList.LastIndexOf(thisEntityName)] = segmentedActionQueue;
                                    goto loopInsertion;
                                }
                            }
                        }
                    }

                    List<EntityInsertAction> actionQueue = positionToAction[lastPos];
                    actionQueue.Add(action);
                }
            loopInsertion: ;
            }

            // now iterate back through positionToAction map and move entityInsertAction back to insertion list
            for (int p = 0; p < nameList.Count; p++)
            {
                List<EntityInsertAction> actionQueue = positionToAction[p];
                foreach (EntityInsertAction action in actionQueue)
                    insertions.Add(action);
            }
        }
Example #37
0
        private decimal MathParserLogic(List <string> tokens)
        {
            // CALCULATING THE EXPRESSIONS INSIDE THE BRACKETS
            // IF NEEDED, EXECUTE A FUNCTION

            // Variables replacement
            for (var i = 0; i < tokens.Count; i++)
            {
                if (LocalVariables.Keys.Contains(tokens[i]))
                {
                    tokens[i] = LocalVariables[tokens[i]].ToString(CultureInfo);
                }
            }
            while (tokens.IndexOf("(") != -1)
            {
                // getting data between "(", ")"
                var open  = tokens.LastIndexOf("(");
                var close = tokens.IndexOf(")", open); // in case open is -1, i.e. no "(" // , open == 0 ? 0 : open - 1

                if (open >= close)
                {
                    // if there is no closing bracket, throw a new exception
                    throw new ArithmeticException("No closing bracket/parenthesis! tkn: " + open.ToString(CultureInfo.InvariantCulture));
                }

                var roughExpr = new List <string>();

                for (var i = open + 1; i < close; i++)
                {
                    roughExpr.Add(tokens[i]);
                }

                decimal result; // the temporary result is stored here

                var functioName = tokens[open == 0 ? 0 : open - 1];
                var args        = new decimal[0];

                if (LocalFunctions.Keys.Contains(functioName))
                {
                    if (roughExpr.Contains(","))
                    {
                        // converting all arguments into a decimal array
                        for (var i = 0; i < roughExpr.Count; i++)
                        {
                            var firstCommaOrEndOfExpression = roughExpr.IndexOf(",", i) != -1 ? roughExpr.IndexOf(",", i) : roughExpr.Count;
                            var defaultExpr = new List <string>();

                            while (i < firstCommaOrEndOfExpression)
                            {
                                defaultExpr.Add(roughExpr[i]);
                                i++;
                            }

                            // changing the size of the array of arguments
                            Array.Resize(ref args, args.Length + 1);

                            if (defaultExpr.Count == 0)
                            {
                                args[args.Length - 1] = 0;
                            }
                            else
                            {
                                args[args.Length - 1] = BasicArithmeticalExpression(defaultExpr);
                            }
                        }

                        // finnaly, passing the arguments to the given function
                        result = decimal.Parse(LocalFunctions[functioName](args).ToString(CultureInfo), CultureInfo);
                    }
                    else
                    {
                        // but if we only have one argument, then we pass it directly to the function
                        result = decimal.Parse(LocalFunctions[functioName](new[] { BasicArithmeticalExpression(roughExpr) }).ToString(CultureInfo), CultureInfo);
                    }
                }
                else
                {
                    // if no function is need to execute following expression, pass it
                    // to the "BasicArithmeticalExpression" method.
                    result = BasicArithmeticalExpression(roughExpr);
                }

                // when all the calculations have been done
                // we replace the "opening bracket with the result"
                // and removing the rest.
                tokens[open] = result.ToString(CultureInfo);
                tokens.RemoveRange(open + 1, close - open);
                if (LocalFunctions.Keys.Contains(functioName))
                {
                    // if we also executed a function, removing
                    // the function name as well.
                    tokens.RemoveAt(open - 1);
                }
            }

            // at this point, we should have replaced all brackets
            // with the appropriate values, so we can simply
            // calculate the expression. it's not so complex
            // any more!
            return(BasicArithmeticalExpression(tokens));
        }
Example #38
0
        public static bool TryGetErrorMessageFromSignToolOutput(IList <string> lines, out string error)
        {
            error = null;
            var extended = new StringBuilder();

            var count = 0;

            var parsed = new List <Tuple <int, string> >();

            if (lines.Any(l => l.Contains("-2147024885/0x8007000b")))
            {
                error = "Package publisher and certificate subject are not the same. MSIX app cannot be signed with the selected certificate.";
                return(true);
            }

            foreach (var line in lines)
            {
                if (line.Contains("Issued by: "))
                {
                    count++;
                    continue;
                }

                if (!line.StartsWith("After "))
                {
                    continue;
                }

                /*
                 *  After EKU filter, 2 certs were left.
                 *  After expiry filter, 2 certs were left.
                 *  After Private Key filter, 0 certs were left.
                 */
                var match = Regex.Match(line, @"After (.*) filter, (\d+) certs were left.");
                if (!match.Success)
                {
                    continue;
                }

                extended.AppendLine("* " + line.Trim());
                parsed.Add(new Tuple <int, string>(int.Parse(match.Groups[2].Value), match.Groups[1].Value));
            }

            parsed.Insert(0, new Tuple <int, string>(count, null));
            for (var i = parsed.Count - 1; i > 0; i--)
            {
                if (parsed[i].Item1 == parsed[i - 1].Item1)
                {
                    parsed.RemoveAt(i);
                }
            }

            var findHash = parsed.FirstOrDefault(p => p.Item2 == "Hash");

            if (findHash != null && findHash.Item1 == 0)
            {
                var findHashIndex = parsed.LastIndexOf(findHash);
                if (findHashIndex == 2)
                {
                    switch (parsed.Skip(1).First().Item2.ToLowerInvariant())
                    {
                    case "private key":
                        error = "The selected certificate does not have a private key.";
                        break;

                    case "expiry":
                        error = "The selected certificate has expired.";
                        break;

                    case "eku":
                        error = "The selected certificate cannot be used for signing purposes (EKU mismatch).";
                        break;

                    default:
                        error = "The selected certificate does not meet the " + parsed[parsed.Count - 1].Item2 + " filter.";
                        break;
                    }

                    return(true);
                }
                else if (findHashIndex > 0)
                {
                    error = "The selected certificate failed validation of one of the following filters: " + string.Join(", ", parsed.Skip(1).Take(findHashIndex - 1).Select(x => x.Item2));
                    return(true);
                }
            }

            if (parsed.Count > 1)
            {
                if (parsed[^ 1].Item1 == 0)
Example #39
0
        public void checkingOrderOfCollection(string CassandraCollectionType, Type TypeOfDataToBeInputed, Type TypeOfKeyForMap = null, string pendingMode = "")
        {
            string cassandraDataTypeName    = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfDataToBeInputed);
            string cassandraKeyDataTypeName = "";

            string openBracket  = CassandraCollectionType == "list" ? "[" : "{";
            string closeBracket = CassandraCollectionType == "list" ? "]" : "}";
            string mapSyntax    = "";

            string randomKeyValue = string.Empty;

            if (TypeOfKeyForMap != null)
            {
                cassandraKeyDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfKeyForMap);
                mapSyntax = cassandraKeyDataTypeName + ",";

                if (TypeOfKeyForMap == typeof(DateTimeOffset))
                {
                    randomKeyValue = (string)(Randomm.RandomVal(typeof(DateTimeOffset)).GetType().GetMethod("ToString", new Type[] { typeof(string) }).Invoke(Randomm.RandomVal(typeof(DateTimeOffset)), new object[1] {
                        "yyyy-MM-dd H:mm:sszz00"
                    }) + "' : '");
                }
                else
                {
                    randomKeyValue = Randomm.RandomVal(TypeOfDataToBeInputed) + "' : '";
                }
            }


            string tableName = "table" + Guid.NewGuid().ToString("N");

            try
            {
                Session.WaitForSchemaAgreement(
                    QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
         tweet_id uuid PRIMARY KEY,
         some_collection {1}<{2}{3}>
         );", tableName, CassandraCollectionType, mapSyntax, cassandraDataTypeName)));
            }
            catch (AlreadyExistsException)
            {
            }
            Guid tweet_id = Guid.NewGuid();

            StringBuilder longQ = new StringBuilder();

            longQ.AppendLine("BEGIN BATCH ");

            int          CollectionElementsNo = 100;
            List <Int32> orderedAsInputed     = new List <Int32>(CollectionElementsNo);

            string inputSide = "some_collection + {1}";

            if (CassandraCollectionType == "list" && pendingMode == "prepending")
            {
                inputSide = "{1} + some_collection";
            }

            for (int i = 0; i < CollectionElementsNo; i++)
            {
                var data = i * (i % 2);
                longQ.AppendFormat(@"UPDATE {0} SET some_collection = " + inputSide + " WHERE tweet_id = {2};"
                                   , tableName, openBracket + randomKeyValue + data + closeBracket, tweet_id.ToString());
                orderedAsInputed.Add(data);
            }

            longQ.AppendLine("APPLY BATCH;");
            QueryTools.ExecuteSyncNonQuery(Session, longQ.ToString(), "Inserting...");

            if (CassandraCollectionType == "set")
            {
                orderedAsInputed.Sort();
                orderedAsInputed.RemoveRange(0, orderedAsInputed.LastIndexOf(0));
            }
            else if (CassandraCollectionType == "list" && pendingMode == "prepending")
            {
                orderedAsInputed.Reverse();
            }

            using (var rs = Session.Execute(string.Format("SELECT * FROM {0};", tableName), ConsistencyLevel.Default))
            {
                int ind = 0;
                foreach (var row in rs.GetRows())
                {
                    foreach (var value in row[1] as System.Collections.IEnumerable)
                    {
                        Assert.True(orderedAsInputed[ind] == (int)value);
                        ind++;
                    }
                }
            }

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName));
            QueryTools.ExecuteSyncNonQuery(Session, string.Format("DROP TABLE {0};", tableName));
        }
Example #40
0
        public override void WriteModel(bool save = true)
        {
            StreamWriter objWriter    = new StreamWriter(m_ModelFileName);
            StreamWriter mtlWriter    = new StreamWriter(m_ModelFileName.Substring(0, m_ModelFileName.Length - 4) + ".mtl");
            string       dir          = Path.GetDirectoryName(m_ModelFileName);
            string       baseFileName = Path.GetFileNameWithoutExtension(m_ModelFileName);

            objWriter.Write("#" + Program.AppTitle + " " + Program.AppVersion + " " + Program.AppDate + "\n\n");
            objWriter.Write("mtllib " + baseFileName + ".mtl" + "\n\n");    // Specify name of material library
            objWriter.Write("bonelib " + baseFileName + ".bones" + "\n\n"); // Specify name of bones list

            // OBJ does not support skinning, bones or vertex-specific object assignment so instead we use the bone ID
            // specified in the first vertex of each face to assign that whole face to an object
            int boneIndex = 0;
            List <ModelBase.BoneDef> flatBoneList = m_Model.m_BoneTree.GetAsList();

            foreach (ModelBase.BoneDef bone in m_Model.m_BoneTree)
            {
                foreach (ModelBase.GeometryDef geometry in bone.m_Geometries.Values)
                {
                    foreach (ModelBase.PolyListDef polyList in geometry.m_PolyLists.Values)
                    {
                        int fl = 0;
                        while (fl < polyList.m_FaceLists.Count)
                        {
                            ModelBase.FaceListDef faceList = polyList.m_FaceLists[fl];

                            int f     = 0;
                            int count = faceList.m_Faces.Count;
                            while (f < faceList.m_Faces.Count)
                            {
                                ModelBase.FaceDef face = faceList.m_Faces[f];

                                int objSplitBoneID = face.m_Vertices[0].m_VertexBoneIndex;
                                if (objSplitBoneID != boneIndex)
                                {
                                    ModelBase.BoneDef newBone = flatBoneList[objSplitBoneID];
                                    // For models using "areas" (multiple-parent bones) the vertices all seem to be
                                    // assigned to the first parent bone. We don't want to move faces about in such
                                    // cases so only move faces between bones within the same branch.
                                    if (bone.GetBranch().Contains(newBone))
                                    {
                                        if (!newBone.m_Geometries.ContainsKey(geometry.m_ID))
                                        {
                                            newBone.m_Geometries.Add(geometry.m_ID, new ModelBase.GeometryDef(geometry.m_ID));
                                        }
                                        if (!newBone.m_Geometries[geometry.m_ID].m_PolyLists.ContainsKey(polyList.m_MaterialName))
                                        {
                                            ModelBase.PolyListDef tmp = new ModelBase.PolyListDef(polyList.m_ID, polyList.m_MaterialName);
                                            tmp.m_FaceLists.Add(new ModelBase.FaceListDef());
                                            newBone.m_Geometries[geometry.m_ID].m_PolyLists.Add(polyList.m_MaterialName, tmp);
                                        }
                                        if (!newBone.m_MaterialsInBranch.Contains(polyList.m_MaterialName))
                                        {
                                            newBone.m_MaterialsInBranch.Add(polyList.m_MaterialName);
                                        }

                                        newBone.m_Geometries[geometry.m_ID].m_PolyLists[polyList.m_MaterialName].m_FaceLists[0].m_Faces.Add(face);
                                        faceList.m_Faces.RemoveAt(f);
                                    }
                                }

                                f++;
                            }

                            fl++;
                        }
                    }
                }

                boneIndex++;
            }

            // Write mtllib
            foreach (ModelBase.MaterialDef material in m_Model.m_Materials.Values)
            {
                //For every texture,
                string textureName = (material.m_TextureDefID != null) ? m_Model.m_Textures[material.m_TextureDefID].m_ID : null;
                //Create new material
                mtlWriter.Write("newmtl " /*+ ((i * 2) + j)*/ + material.m_ID + "\n");
                //Specify ambient colour - RGB 0-1
                mtlWriter.Write("Ka " + Helper.ToString(material.m_Ambient.R / 255.0f) +
                                " " + Helper.ToString(material.m_Ambient.G / 255.0f) +
                                " " + Helper.ToString(material.m_Ambient.B / 255.0f) + "\n");
                //Specify diffuse colour - RGB 0-1
                mtlWriter.Write("Kd " + Helper.ToString(material.m_Diffuse.R / 255.0f) +
                                " " + Helper.ToString(material.m_Diffuse.G / 255.0f) +
                                " " + Helper.ToString(material.m_Diffuse.B / 255.0f) + "\n");
                //Specify specular colour - RGB 0-1
                mtlWriter.Write("Ks " + Helper.ToString(material.m_Specular.R / 255.0f) +
                                " " + Helper.ToString(material.m_Specular.G / 255.0f) +
                                " " + Helper.ToString(material.m_Specular.B / 255.0f) + "\n");
                //Specify specular colour co-efficient - RGB 0-1
                //mtllib += "Ns " + material.m_SpeEmiColors + "\n";
                //Specify transparency - RGB Alpha channel 0-1
                mtlWriter.Write("d " + Helper.ToString(material.m_Alpha / 31f) + "\n");
                //Specify texture type 0 - 10
                //uint textype = (currentTexture.m_Params >> 26) & 0x7;
                mtlWriter.Write("illum 2\n");
                if (textureName != null && !textureName.Equals(""))
                {
                    //Specify name of texture image
                    mtlWriter.Write("map_Kd " + textureName + ".png" + "\n\n");
                    ExportTextureToPNG(dir, m_Model.m_Textures[material.m_TextureDefID]);
                }
                else
                {
                    mtlWriter.Write("\n\n");
                }
            }

            WriteBonesFileOBJ(m_ModelFileName.Substring(0, m_ModelFileName.Length - 4) + ".bones", m_Model.m_BoneTree);

            // Write each bone to file as a separate mesh/object using o command
            List <Vector3> verts         = new List <Vector3>();
            List <Vector2> textureCoords = new List <Vector2>();
            List <Color>   vertexColours = new List <Color>();

            foreach (ModelBase.BoneDef bone in m_Model.m_BoneTree)
            {
                objWriter.Write("o " + bone.m_ID + "\n");

                // Get a list of all verices and texture co-ordinates for the current bone
                List <Vector3> vertsCurBone         = new List <Vector3>();
                List <Vector2> textureCoordsCurBone = new List <Vector2>();
                List <Color>   vertexColoursCurBone = new List <Color>();

                foreach (ModelBase.GeometryDef geometry in bone.m_Geometries.Values)
                {
                    foreach (ModelBase.PolyListDef polyList in geometry.m_PolyLists.Values)
                    {
                        foreach (ModelBase.FaceListDef faceList in polyList.m_FaceLists)
                        {
                            foreach (ModelBase.FaceDef face in faceList.m_Faces)
                            {
                                foreach (ModelBase.VertexDef vert in face.m_Vertices)
                                {
                                    if (!vertsCurBone.Contains(vert.m_Position))
                                    {
                                        vertsCurBone.Add(vert.m_Position);
                                        verts.Add(vert.m_Position);
                                    }
                                    if (vert.m_TextureCoordinate != null && !textureCoordsCurBone.Contains((Vector2)vert.m_TextureCoordinate))
                                    {
                                        textureCoordsCurBone.Add((Vector2)vert.m_TextureCoordinate);
                                        textureCoords.Add((Vector2)vert.m_TextureCoordinate);
                                    }
                                    if (vert.m_VertexColour != null && !vertexColoursCurBone.Contains((Color)vert.m_VertexColour))
                                    {
                                        vertexColoursCurBone.Add((Color)vert.m_VertexColour);
                                        vertexColours.Add((Color)vert.m_VertexColour);
                                    }
                                }
                            }
                        }
                    }
                }

                // Print a list of all vertices, texture co-ordinates and vertex colours
                foreach (Vector3 vert in vertsCurBone)
                {
                    objWriter.Write("v " + Helper.ToString(vert.X) + " " + Helper.ToString(vert.Y) + " " + Helper.ToString(vert.Z) + "\n");
                }
                foreach (Vector2 textureCoord in textureCoordsCurBone)
                {
                    objWriter.Write("vt " + Helper.ToString(textureCoord.X) + " " + Helper.ToString(textureCoord.Y) + "\n");
                }
                foreach (Color vColour in vertexColoursCurBone)
                {
                    objWriter.Write("vc " + Helper.ToString(vColour.R / 255.0f) + " " + Helper.ToString(vColour.G / 255.0f) + " " +
                                    Helper.ToString(vColour.B / 255.0f) + "\n");
                }

                // For each material used in the current bone, print all faces
                foreach (ModelBase.GeometryDef geometry in bone.m_Geometries.Values)
                {
                    foreach (ModelBase.PolyListDef polyList in geometry.m_PolyLists.Values)
                    {
                        objWriter.Write("usemtl " + polyList.m_MaterialName + "\n");

                        foreach (ModelBase.FaceListDef faceList in polyList.m_FaceLists)
                        {
                            foreach (ModelBase.FaceDef face in faceList.m_Faces)
                            {
                                // Each face is a triangle or a quad, as they have already been extracted individually from
                                // the vertex lists
                                // Note: Indices start at 1 in OBJ
                                int numVerticesInFace = face.m_NumVertices;

                                objWriter.Write("f ");
                                foreach (ModelBase.VertexDef vert in face.m_Vertices)
                                {
                                    objWriter.Write((verts.LastIndexOf(vert.m_Position) + 1) +
                                                    "/" + ((vert.m_TextureCoordinate != null) ?
                                                           (textureCoords.LastIndexOf((Vector2)vert.m_TextureCoordinate) + 1).ToString() : "") +
                                                    "//" + ((vert.m_VertexColour != null) ?
                                                            (vertexColours.LastIndexOf((Color)vert.m_VertexColour) + 1).ToString() : "") + " ");
                                }
                                objWriter.Write("\n");
                            }
                        }
                    }
                }
            }

            objWriter.Close();
            mtlWriter.Close();
        }
Example #41
0
        public static string HTMLSubstring(string html, int length)
        {
            if (html == null)
            {
                throw new ArgumentNullException("html");
            }

            List <string> unclosedTags = new List <string>();

            bool isQuoted = false;

            if (html.Length > length)
            {
                for (int i = 0; i < html.Length; i++)
                {
                    char currentCharacter = html[i];

                    char nextCharacter = ' ';

                    if (i < html.Length - 1)
                    {
                        nextCharacter = html[i + 1];
                    }

                    // Check if quotes are on.
                    if (!isQuoted)
                    {
                        if (currentCharacter == '<' && nextCharacter != ' ' && nextCharacter != '>')
                        {
                            if (nextCharacter != '/') // Open tag.
                            {
                                int startIndex = i + 1;

                                if (startIndex < html.Length)
                                {
                                    int finishIndex = html.IndexOf(">", startIndex);

                                    if (finishIndex > 0)
                                    {
                                        if (html[finishIndex - 1] != '/')
                                        {
                                            string tag = html.Substring(startIndex, finishIndex - startIndex);

                                            if (tag.Contains(" "))
                                            {
                                                int temporaryFinishIndex = html.IndexOf(" ", startIndex);

                                                tag = html.Substring(startIndex, temporaryFinishIndex - startIndex);
                                            }

                                            if (!tag.Equals("br", StringComparison.InvariantCultureIgnoreCase))
                                            {
                                                unclosedTags.Add(tag);
                                            }
                                        }

                                        int tagLength = finishIndex + 1 - i;

                                        length += tagLength;

                                        i = finishIndex;
                                    }
                                }
                            }
                            else if (nextCharacter == '/') // Close tag.
                            {
                                int startIndex = i + 2;

                                if (startIndex < html.Length)
                                {
                                    int finishIndex = html.IndexOf(">", startIndex);

                                    if (finishIndex > 0)
                                    {
                                        string tag = html.Substring(startIndex, finishIndex - startIndex);

                                        // FILO.
                                        int index = unclosedTags.LastIndexOf(tag);

                                        if (index >= 0)
                                        {
                                            unclosedTags.RemoveAt(index);

                                            int tagLength = finishIndex + 1 - i;

                                            length += tagLength;

                                            i = finishIndex;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        if (currentCharacter == '"')
                        {
                            isQuoted = false;
                        }
                    }

                    if (i >= length)
                    {
                        html = string.Format("{0}...", html.Substring(0, i));

                        unclosedTags.Reverse();

                        foreach (string unclosedTag in unclosedTags)
                        {
                            html += string.Format("</{0}>", unclosedTag);
                        }
                    }
                }
            }

            return(html);
        }
Example #42
0
    void bakeAnimation(Transform bone, float time)
    {
        int    index       = bones.LastIndexOf(bone);
        string boneNameFul = GetFullName(bone, bone.name);

        //Debug.Log ("setting curve for " + boneNameFul + " at time " + time + " index is " + index + " curvePosX is " + curvePosX[index]);
        //Debug.Log (newClip.name);

        if (time > 0)
        {
            if ((curvePosX[index].Evaluate(time - frameTime) != bone.localPosition.x) ||
                (curvePosY[index].Evaluate(time - frameTime) != bone.localPosition.y) ||
                (curvePosZ[index].Evaluate(time - frameTime) != bone.localPosition.z))
            {
                curvePosX[index].AddKey(new Keyframe(time - frameTime, curvePosX[index].Evaluate(time - frameTime)));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localPosition.x", curvePosX[index]);

                curvePosY[index].AddKey(new Keyframe(time - frameTime, curvePosY[index].Evaluate(time - frameTime)));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localPosition.y", curvePosY[index]);

                curvePosZ[index].AddKey(new Keyframe(time - frameTime, curvePosZ[index].Evaluate(time - frameTime)));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localPosition.z", curvePosZ[index]);

                curvePosX[index].AddKey(new Keyframe(time, bone.localPosition.x));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localPosition.x", curvePosX[index]);

                curvePosY[index].AddKey(new Keyframe(time, bone.localPosition.y));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localPosition.y", curvePosY[index]);

                curvePosZ[index].AddKey(new Keyframe(time, bone.localPosition.z));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localPosition.z", curvePosZ[index]);

                //if(curvePosX[index].keys.Length>2)
                //	AnimationUtility.
                //	AnimationUtility.SetEditorCurve(newClip,EditorCurveBinding.FloatCurve(boneNameFul,typeof(Transform),"localPosition.x") ,curvePosX[index]);
            }
        }
        else
        {
            curvePosX[index].AddKey(new Keyframe(time, bone.localPosition.x));
            newClip.SetCurve(boneNameFul, typeof(Transform), "localPosition.x", curvePosX[index]);
            //AnimationUtility.SetEditorCurve(newClip,EditorCurveBinding.FloatCurve(boneNameFul,typeof(Transform),"m_LocalPosition.x") ,curvePosX[index]);


            curvePosY[index].AddKey(new Keyframe(time, bone.localPosition.y));
            newClip.SetCurve(boneNameFul, typeof(Transform), "localPosition.y", curvePosY[index]);

            curvePosZ[index].AddKey(new Keyframe(time, bone.localPosition.z));
            newClip.SetCurve(boneNameFul, typeof(Transform), "localPosition.z", curvePosZ[index]);
        }

        if (time > 0)
        {
            if ((curveRotX[index].Evaluate(time - frameTime) != bone.localRotation.x) ||
                (curveRotY[index].Evaluate(time - frameTime) != bone.localRotation.y) ||
                (curveRotZ[index].Evaluate(time - frameTime) != bone.localRotation.z) ||
                (curveRotW[index].Evaluate(time - frameTime) != bone.localRotation.w))
            {
                curveRotX[index].AddKey(new Keyframe(time - frameTime, curveRotX[index].Evaluate(time - frameTime)));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localRotation.x", curveRotX[index]);

                curveRotY[index].AddKey(new Keyframe(time - frameTime, curveRotY[index].Evaluate(time - frameTime)));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localRotation.y", curveRotY[index]);

                curveRotZ[index].AddKey(new Keyframe(time - frameTime, curveRotZ[index].Evaluate(time - frameTime)));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localRotation.z", curveRotZ[index]);

                curveRotW[index].AddKey(new Keyframe(time - frameTime, curveRotW[index].Evaluate(time - frameTime)));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localRotation.w", curveRotW[index]);

                curveRotX[index].AddKey(new Keyframe(time, bone.localRotation.x));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localRotation.x", curveRotX[index]);

                curveRotY[index].AddKey(new Keyframe(time, bone.localRotation.y));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localRotation.y", curveRotY[index]);

                curveRotZ[index].AddKey(new Keyframe(time, bone.localRotation.z));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localRotation.z", curveRotZ[index]);

                curveRotW[index].AddKey(new Keyframe(time, bone.localRotation.w));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localRotation.w", curveRotW[index]);
            }
        }
        else
        {
            curveRotX[index].AddKey(new Keyframe(time, bone.localRotation.x));
            newClip.SetCurve(boneNameFul, typeof(Transform), "localRotation.x", curveRotX[index]);

            curveRotY[index].AddKey(new Keyframe(time, bone.localRotation.y));
            newClip.SetCurve(boneNameFul, typeof(Transform), "localRotation.y", curveRotY[index]);

            curveRotZ[index].AddKey(new Keyframe(time, bone.localRotation.z));
            newClip.SetCurve(boneNameFul, typeof(Transform), "localRotation.z", curveRotZ[index]);

            curveRotW[index].AddKey(new Keyframe(time, bone.localRotation.w));
            newClip.SetCurve(boneNameFul, typeof(Transform), "localRotation.w", curveRotW[index]);
        }

        if (time > 0)
        {
            if ((curveScaleX[index].Evaluate(time - frameTime) != bone.localScale.x) ||
                (curveScaleY[index].Evaluate(time - frameTime) != bone.localScale.y) ||
                (curveScaleZ[index].Evaluate(time - frameTime) != bone.localScale.z))
            {
                curveScaleX[index].AddKey(new Keyframe(time - frameTime, curveScaleX[index].Evaluate(time - frameTime)));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localScale.x", curveScaleX[index]);

                curveScaleY[index].AddKey(new Keyframe(time - frameTime, curveScaleY[index].Evaluate(time - frameTime)));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localScale.y", curveScaleY[index]);

                curveScaleZ[index].AddKey(new Keyframe(time - frameTime, curveScaleZ[index].Evaluate(time - frameTime)));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localScale.z", curveScaleZ[index]);

                curveScaleX[index].AddKey(new Keyframe(time, bone.localScale.x));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localScale.x", curveScaleX[index]);

                curveScaleY[index].AddKey(new Keyframe(time, bone.localScale.y));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localScale.y", curveScaleY[index]);

                curveScaleZ[index].AddKey(new Keyframe(time, bone.localScale.z));
                newClip.SetCurve(boneNameFul, typeof(Transform), "localScale.z", curveScaleZ[index]);
            }
        }
        else
        {
            curveScaleX[index].AddKey(new Keyframe(time, bone.localScale.x));
            newClip.SetCurve(boneNameFul, typeof(Transform), "localScale.x", curveScaleX[index]);

            curveScaleY[index].AddKey(new Keyframe(time, bone.localScale.y));
            newClip.SetCurve(boneNameFul, typeof(Transform), "localScale.y", curveScaleY[index]);

            curveScaleZ[index].AddKey(new Keyframe(time, bone.localScale.z));
            newClip.SetCurve(boneNameFul, typeof(Transform), "localScale.z", curveScaleZ[index]);
        }
    }
        public static void Main()
        {
            List <int> inputList = new List <int>();

            inputList = Console.ReadLine().Split().Select(int.Parse).ToList();

            string[] command = Console.ReadLine().Split();

            while (!command[0].Equals("end"))
            {
                switch (command[0])
                {
                case "exchange":

                    int index = int.Parse(command[1]);

                    if (index < 0 || index >= inputList.Count)
                    {
                        Console.WriteLine("Invalid index");
                    }
                    else
                    {
                        // There is no point to split after the last index so we break to the command input:
                        if (index == inputList.Count - 1)
                        {
                            break;
                        }

                        int[] exchange = inputList.Skip(index + 1).Take(inputList.Count).ToArray();
                        inputList.RemoveRange(index + 1, inputList.Count - index - 1);
                        inputList.InsertRange(0, exchange);
                    }
                    break;

                case "max":

                    if (command[1].Equals("even"))
                    {
                        try
                        {
                            int maxElement      = inputList.Where(e => e % 2 == 0).Max();
                            int maxElementIndex = inputList.LastIndexOf(maxElement);
                            Console.WriteLine(maxElementIndex);
                        }
                        catch
                        {
                            Console.WriteLine("No matches");
                        }
                    }
                    else if (command[1].Equals("odd"))
                    {
                        try
                        {
                            int maxElement      = inputList.Where(e => e % 2 != 0).Max();
                            int maxElementIndex = inputList.LastIndexOf(maxElement);
                            Console.WriteLine(maxElementIndex);
                        }
                        catch
                        {
                            Console.WriteLine("No matches");
                        }
                    }
                    break;

                case "min":

                    if (command[1].Equals("even"))
                    {
                        try
                        {
                            int minElement      = inputList.Where(e => e % 2 == 0).Min();
                            int minElementIndex = inputList.LastIndexOf(minElement);
                            Console.WriteLine(minElementIndex);
                        }
                        catch
                        {
                            Console.WriteLine("No matches");
                        }
                    }
                    else if (command[1].Equals("odd"))
                    {
                        try
                        {
                            int minElement      = inputList.Where(e => e % 2 != 0).Min();
                            int minElementIndex = inputList.LastIndexOf(minElement);
                            Console.WriteLine(minElementIndex);
                        }
                        catch
                        {
                            Console.WriteLine("No matches");
                        }
                    }
                    break;

                case "first":

                    int countElements = int.Parse(command[1]);

                    if (countElements > inputList.Count)
                    {
                        Console.WriteLine("Invalid count");
                    }
                    else
                    {
                        if (command[2].Equals("even"))
                        {
                            int[] evenElements = inputList.Where(e => e % 2 == 0).Take(countElements).ToArray();
                            Console.WriteLine($"[{string.Join(", ", evenElements)}]");
                        }
                        else if (command[2].Equals("odd"))
                        {
                            int[] oddElements = inputList.Where(e => e % 2 != 0).Take(countElements).ToArray();
                            Console.WriteLine($"[{string.Join(", ", oddElements)}]");
                        }
                    }
                    break;

                case "last":

                    countElements = int.Parse(command[1]);

                    if (countElements > inputList.Count)
                    {
                        Console.WriteLine("Invalid count");
                    }
                    else
                    {
                        if (command[2].Equals("even"))
                        {
                            int[] evenElements = inputList.Where(e => e % 2 == 0).Reverse().Take(countElements).Reverse().ToArray();
                            Console.WriteLine($"[{string.Join(", ", evenElements)}]");
                        }
                        else if (command[2].Equals("odd"))
                        {
                            int[] oddElements = inputList.Where(e => e % 2 != 0).Reverse().Take(countElements).Reverse().ToArray();
                            Console.WriteLine($"[{string.Join(", ", oddElements)}]");
                        }
                    }
                    break;
                }

                command = Console.ReadLine().Split();
            }

            Console.WriteLine($"[{string.Join(", ", inputList)}]");
        }
        /// <summary>
        /// Navigates to the next (or previous) transaction to edit
        /// </summary>
        private void NavigateToTransaction(Direction direction)
        {
            // put a lock around the entire NavigateToTransaction logic so that the navigation and "other person editing" logic will work consistently even if multiple people are editing the same batch
            lock ( transactionMatchingLockObject )
            {
                hfDoFadeIn.Value    = "1";
                nbSaveError.Visible = false;
                int?       fromTransactionId = hfTransactionId.Value.AsIntegerOrNull();
                int?       toTransactionId   = null;
                List <int> historyList       = hfBackNextHistory.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).AsIntegerList().Where(a => a > 0).ToList();
                int        position          = hfHistoryPosition.Value.AsIntegerOrNull() ?? -1;

                if (direction == Direction.Prev)
                {
                    position--;
                }
                else
                {
                    position++;
                }

                if (historyList.Count > position)
                {
                    if (position >= 0)
                    {
                        toTransactionId = historyList[position];
                    }
                    else
                    {
                        // if we trying to go previous when we are already at the start of the list, wrap around to the last item in the list
                        toTransactionId = historyList.Last();
                        position        = historyList.Count - 1;
                    }
                }

                hfHistoryPosition.Value = position.ToString();

                int batchId     = hfBatchId.Value.AsInteger();
                var rockContext = new RockContext();
                var financialPersonBankAccountService = new FinancialPersonBankAccountService(rockContext);
                var financialTransactionService       = new FinancialTransactionService(rockContext);
                var qryTransactionsToMatch            = financialTransactionService.Queryable()
                                                        .Where(a => a.AuthorizedPersonAliasId == null && a.ProcessedByPersonAliasId == null);

                if (batchId != 0)
                {
                    qryTransactionsToMatch = qryTransactionsToMatch.Where(a => a.BatchId == batchId);
                }

                // if a specific transactionId was specified (because we are navigating thru history), load that one. Otherwise, if a batch is specified, get the first unmatched transaction in that batch
                if (toTransactionId.HasValue)
                {
                    qryTransactionsToMatch = financialTransactionService
                                             .Queryable("AuthorizedPersonAlias.Person,ProcessedByPersonAlias.Person")
                                             .Where(a => a.Id == toTransactionId);
                }

                if (historyList.Any() && !toTransactionId.HasValue)
                {
                    // since we are looking for a transaction we haven't viewed or matched yet, look for the next one in the database that we haven't seen yet
                    qryTransactionsToMatch = qryTransactionsToMatch.Where(a => !historyList.Contains(a.Id));
                }

                qryTransactionsToMatch = qryTransactionsToMatch.OrderBy(a => a.CreatedDateTime).ThenBy(a => a.Id);

                FinancialTransaction transactionToMatch = qryTransactionsToMatch.FirstOrDefault();
                if (transactionToMatch == null)
                {
                    // we exhausted the transactions that aren't processed and aren't in our history list, so remove those those restrictions and show all transactions that haven't been matched yet
                    var qryRemainingTransactionsToMatch = financialTransactionService
                                                          .Queryable("AuthorizedPersonAlias.Person,ProcessedByPersonAlias.Person")
                                                          .Where(a => a.AuthorizedPersonAliasId == null);

                    if (batchId != 0)
                    {
                        qryRemainingTransactionsToMatch = qryRemainingTransactionsToMatch.Where(a => a.BatchId == batchId);
                    }

                    // get the first transaction that we haven't visited yet, or the next one we have visited after one we are on, or simple the first unmatched one
                    transactionToMatch = qryRemainingTransactionsToMatch.Where(a => a.Id > fromTransactionId && !historyList.Contains(a.Id)).FirstOrDefault()
                                         ?? qryRemainingTransactionsToMatch.Where(a => a.Id > fromTransactionId).FirstOrDefault()
                                         ?? qryRemainingTransactionsToMatch.FirstOrDefault();
                    if (transactionToMatch != null)
                    {
                        historyList.Add(transactionToMatch.Id);
                        position = historyList.LastIndexOf(transactionToMatch.Id);
                        hfHistoryPosition.Value = position.ToString();
                    }
                }
                else
                {
                    if (!toTransactionId.HasValue)
                    {
                        historyList.Add(transactionToMatch.Id);
                    }
                }

                if (transactionToMatch == null)
                {
                    nbNoUnmatchedTransactionsRemaining.Visible = true;
                    lbFinish.Visible = true;
                    pnlEdit.Visible  = false;

                    btnFilter.Visible         = false;
                    rcwAddNewBusiness.Visible = false;
                    rcwAddNewFamily.Visible   = false;
                }
                else
                {
                    nbNoUnmatchedTransactionsRemaining.Visible = false;
                    lbFinish.Visible = false;
                    pnlEdit.Visible  = true;
                }

                nbIsInProcess.Visible = false;
                if (transactionToMatch != null)
                {
                    if (transactionToMatch.ProcessedByPersonAlias != null)
                    {
                        if (transactionToMatch.AuthorizedPersonAliasId.HasValue)
                        {
                            nbIsInProcess.Text    = string.Format("Warning. This transaction was matched by {0} at {1} ({2})", transactionToMatch.ProcessedByPersonAlias.Person, transactionToMatch.ProcessedDateTime.ToString(), transactionToMatch.ProcessedDateTime.ToRelativeDateString());
                            nbIsInProcess.Visible = true;
                        }
                        else
                        {
                            // display a warning if some other user has this marked as InProcess (and it isn't matched)
                            if (transactionToMatch.ProcessedByPersonAliasId != CurrentPersonAliasId)
                            {
                                nbIsInProcess.Text    = string.Format("Warning. This transaction is getting processed by {0} as of {1} ({2})", transactionToMatch.ProcessedByPersonAlias.Person, transactionToMatch.ProcessedDateTime.ToString(), transactionToMatch.ProcessedDateTime.ToRelativeDateString());
                                nbIsInProcess.Visible = true;
                            }
                        }
                    }

                    // Unless somebody else is processing it, immediately mark the transaction as getting processed by the current person so that other potentional transaction matching sessions will know that it is currently getting looked at
                    if (!transactionToMatch.ProcessedByPersonAliasId.HasValue)
                    {
                        transactionToMatch.ProcessedByPersonAlias   = null;
                        transactionToMatch.ProcessedByPersonAliasId = CurrentPersonAliasId;
                        transactionToMatch.ProcessedDateTime        = RockDateTime.Now;
                        rockContext.SaveChanges();
                    }

                    hfTransactionId.Value = transactionToMatch.Id.ToString();

                    // get the first 2 images (should be no more than 2, but just in case)
                    var transactionImages = transactionToMatch.Images.OrderBy(a => a.Order).Take(2).ToList();

                    ddlIndividual.Items.Clear();
                    ddlIndividual.Items.Add(new ListItem(null, null));

                    // clear any previously shown badges
                    ddlIndividual.Attributes.Remove("disabled");
                    badgeIndividualCount.InnerText = string.Empty;

                    // if this transaction has a CheckMicrParts, try to find matching person(s)
                    string checkMicrHashed = null;

                    if (!string.IsNullOrWhiteSpace(transactionToMatch.CheckMicrParts))
                    {
                        try
                        {
                            var checkMicrClearText = Encryption.DecryptString(transactionToMatch.CheckMicrParts);
                            var parts = checkMicrClearText.Split('_');
                            if (parts.Length >= 2)
                            {
                                checkMicrHashed = FinancialPersonBankAccount.EncodeAccountNumber(parts[0], parts[1]);
                            }
                        }
                        catch
                        {
                            // intentionally ignore exception when decripting CheckMicrParts since we'll be checking for null below
                        }
                    }

                    hfCheckMicrHashed.Value = checkMicrHashed;

                    if (!string.IsNullOrWhiteSpace(checkMicrHashed))
                    {
                        var matchedPersons = financialPersonBankAccountService.Queryable().Where(a => a.AccountNumberSecured == checkMicrHashed).Select(a => a.PersonAlias.Person).Distinct();
                        foreach (var person in matchedPersons.OrderBy(a => a.LastName).ThenBy(a => a.NickName))
                        {
                            ddlIndividual.Items.Add(new ListItem(person.FullNameReversed, person.Id.ToString()));
                        }
                    }

                    if (ddlIndividual.Items.Count == 2)
                    {
                        // only one person (and the None selection) are in the list, so init to the person
                        ddlIndividual.SelectedIndex = 1;
                    }
                    else
                    {
                        // either zero or multiple people are in the list, so default to none so they are forced to choose
                        ddlIndividual.SelectedIndex = 0;
                    }

                    if (transactionToMatch.AuthorizedPersonAlias != null && transactionToMatch.AuthorizedPersonAlias.Person != null)
                    {
                        var person = transactionToMatch.AuthorizedPersonAlias.Person;

                        // if the drop down does not contains the AuthorizedPerson of this transaction, add them to the drop down
                        // note, this can easily happen for non-check transactions
                        if (!ddlIndividual.Items.OfType <ListItem>().Any(a => a.Value == person.Id.ToString()))
                        {
                            ddlIndividual.Items.Add(new ListItem(person.FullNameReversed, person.Id.ToString()));
                        }

                        ddlIndividual.SelectedValue = person.Id.ToString();
                    }

                    if (ddlIndividual.Items.Count != 1)
                    {
                        badgeIndividualCount.InnerText = (ddlIndividual.Items.Count - 1).ToStringSafe();
                    }
                    else
                    {
                        ddlIndividual.Attributes["disabled"] = "disabled";
                        _focusControl = ppSelectNew;
                    }

                    ddlIndividual_SelectedIndexChanged(null, null);

                    ppSelectNew.SetValue(null);
                    if (transactionToMatch.TransactionDetails.Any())
                    {
                        cbTotalAmount.Text = transactionToMatch.TotalAmount.ToString();
                    }
                    else
                    {
                        cbTotalAmount.Text = string.Empty;
                    }

                    // update accountboxes
                    foreach (var accountBox in rptAccounts.ControlsOfTypeRecursive <CurrencyBox>())
                    {
                        accountBox.Text = string.Empty;
                    }

                    foreach (var detail in transactionToMatch.TransactionDetails)
                    {
                        var accountBox = rptAccounts.ControlsOfTypeRecursive <CurrencyBox>().Where(a => a.Attributes["data-account-id"].AsInteger() == detail.AccountId).FirstOrDefault();
                        if (accountBox != null)
                        {
                            accountBox.Text = detail.Amount.ToString();
                        }
                    }

                    tbSummary.Text = transactionToMatch.Summary;

                    if (transactionToMatch.Images.Any())
                    {
                        var primaryImage = transactionToMatch.Images
                                           .OrderBy(i => i.Order)
                                           .FirstOrDefault();
                        imgPrimary.ImageUrl = string.Format("~/GetImage.ashx?id={0}", primaryImage.BinaryFileId);
                        imgPrimary.Visible  = true;
                        nbNoTransactionImageWarning.Visible = false;

                        rptrImages.DataSource = transactionToMatch.Images
                                                .Where(i => !i.Id.Equals(primaryImage.Id))
                                                .OrderBy(i => i.Order)
                                                .ToList();
                        rptrImages.DataBind();
                    }
                    else
                    {
                        imgPrimary.Visible    = false;
                        rptrImages.DataSource = null;
                        rptrImages.DataBind();
                        nbNoTransactionImageWarning.Visible = true;
                    }
                }
                else
                {
                    hfTransactionId.Value = string.Empty;
                }

                // display how many unmatched transactions are remaining
                var qryTransactionCount = financialTransactionService.Queryable();
                if (batchId != 0)
                {
                    qryTransactionCount = qryTransactionCount.Where(a => a.BatchId == batchId);
                }

                // get count of transactions that haven't been matched (not including the one we are currently editing)
                int currentTranId         = hfTransactionId.Value.AsInteger();
                int matchedRemainingCount = qryTransactionCount.Count(a => a.AuthorizedPersonAliasId != null && a.Id != currentTranId);
                int totalBatchItemCount   = qryTransactionCount.Count();

                int percentComplete = (int)Math.Round((double)(100 * matchedRemainingCount) / totalBatchItemCount);

                lProgressBar.Text = string.Format(
                    @"<div class='progress'>
                            <div class='progress-bar progress-bar-info' role='progressbar' aria-valuenow='{0}' aria-valuemin='0' aria-valuemax='100' style='width: {0}%;'>
                                {0}%
                            </div>
                        </div>",
                    percentComplete);

                hfBackNextHistory.Value = historyList.AsDelimited(",");

                if (_focusControl == null)
                {
                    _focusControl = rptAccounts.ControlsOfTypeRecursive <Rock.Web.UI.Controls.CurrencyBox>().FirstOrDefault();
                }
            }
        }
Example #45
0
 /// <inheritdoc cref="List{T}.LastIndexOf(T)" />
 public int LastIndexOf(T item)
 {
     using (EnterReadLock.Enter(LockObject))
         return(_lstData.LastIndexOf(item));
 }
Example #46
0
    public void RemoveWatcher(FloatChangedWatcher watcher)
    {
        int lastIndex = _watchers.LastIndexOf(watcher);

        _watchers.RemoveAt(lastIndex);
    }
Example #47
0
        public void CreateCSV(string properties, string filename = "default.csv")
        {
            var splitResult = properties.Split(',');

            foreach (var property in splitResult)
            {
                propertyList.Add(property.Trim());
            }

            StringBuilder stringBuilder = new StringBuilder();
            Type          personType    = typeof(Person);

            stringBuilder.Append("sep=,\r\n");

            foreach (var property in propertyList)
            {
                stringBuilder.Append(property);
                if (propertyList.LastIndexOf(property) != propertyList.Count - 1)
                {
                    stringBuilder.Append(',');
                }
                else
                {
                    stringBuilder.Append("\r\n");
                }
            }

            foreach (var person in personList)
            {
                foreach (var property in propertyList)
                {
                    var value = personType.GetProperty(property).GetValue(person);
                    if (value != null)
                    {
                        if (value.ToString().Contains(','))
                        {
                            stringBuilder.Append($"\"{value}\"");
                        }
                        else
                        {
                            stringBuilder.Append($"{value}");
                        }
                    }
                    else
                    {
                        stringBuilder.Append($"{value}");
                    }

                    if (propertyList.LastIndexOf(property) != propertyList.Count - 1)
                    {
                        stringBuilder.Append(',');
                    }
                    else
                    {
                        stringBuilder.Append("\r\n");
                    }
                }
            }

            using (var file = new StreamWriter(filename))
            {
                file.Write(stringBuilder.ToString());
            }
        }
        public bool createMob(mob newMob)
        {
            String mobStr = newMob.mID.ToString();

            mobStr += ",'" + newMob.mSprName;
            mobStr += "','" + newMob.mJpnName;
            mobStr += "','" + newMob.mEngName;
            mobStr += "'," + newMob.mLvl.ToString();
            mobStr += "," + newMob.mHP.ToString();
            mobStr += "," + newMob.mSP.ToString();
            mobStr += "," + newMob.mBaseXP.ToString();
            mobStr += "," + newMob.mJobXP.ToString();
            mobStr += "," + newMob.mAtkRng.ToString();
            mobStr += "," + newMob.mMinAtk.ToString();
            mobStr += "," + newMob.mMaxAtk.ToString();
            mobStr += "," + newMob.mDef.ToString();
            mobStr += "," + newMob.mMDef.ToString();
            mobStr += "," + newMob.mStr.ToString();
            mobStr += "," + newMob.mAgi.ToString();
            mobStr += "," + newMob.mVit.ToString();
            mobStr += "," + newMob.mInt.ToString();
            mobStr += "," + newMob.mDex.ToString();
            mobStr += "," + newMob.mLuk.ToString();
            mobStr += "," + newMob.mSkRng.ToString();
            mobStr += "," + newMob.mVwRng.ToString();
            mobStr += "," + newMob.mScale.ToString();
            mobStr += "," + newMob.mRace.ToString();
            mobStr += "," + newMob.mEle.ToString();
            mobStr += "," + newMob.mBevMask.ToString();
            mobStr += "," + newMob.mWlkSpd.ToString();
            mobStr += "," + newMob.mAtkDly.ToString();
            mobStr += "," + newMob.mAtkMot.ToString();
            mobStr += "," + newMob.mDmgMot.ToString();
            mobStr += "," + newMob.mMXP.ToString();
            mobStr += "," + newMob.mMDrop1ID.ToString();
            mobStr += "," + newMob.mMDrop1Perc.ToString();
            mobStr += "," + newMob.mMDrop2ID.ToString();
            mobStr += "," + newMob.mMDrop2Perc.ToString();
            mobStr += "," + newMob.mMDrop3ID.ToString();
            mobStr += "," + newMob.mMDrop3Perc.ToString();
            mobStr += "," + newMob.mDrop1ID.ToString();
            mobStr += "," + newMob.mDrop1Perc.ToString();
            mobStr += "," + newMob.mDrop2ID.ToString();
            mobStr += "," + newMob.mDrop2Perc.ToString();
            mobStr += "," + newMob.mDrop3ID.ToString();
            mobStr += "," + newMob.mDrop3Perc.ToString();
            mobStr += "," + newMob.mDrop4ID.ToString();
            mobStr += "," + newMob.mDrop4Perc.ToString();
            mobStr += "," + newMob.mDrop5ID.ToString();
            mobStr += "," + newMob.mDrop5Perc.ToString();
            mobStr += "," + newMob.mDrop6ID.ToString();
            mobStr += "," + newMob.mDrop6Perc.ToString();
            mobStr += "," + newMob.mDrop7ID.ToString();
            mobStr += "," + newMob.mDrop7Perc.ToString();
            mobStr += "," + newMob.mDrop8ID.ToString();
            mobStr += "," + newMob.mDrop8Perc.ToString();
            mobStr += "," + newMob.mDrop9ID.ToString();
            mobStr += "," + newMob.mDrop9Perc.ToString();
            mobStr += "," + newMob.mCardDropID.ToString();
            mobStr += "," + newMob.mCardDropPerc.ToString();

            mobs.Add(new mob(mobStr, true, newMob.mobLocale, dhLog));


            if (mobs[mobs.LastIndexOf(mobs.Last())].bWarningsOccurred && !bShowErrorsInApp)
            {
                MessageBox.Show(null, "Warnings occurred while saving this mob.  Please check the log file(s) for more information.", "Mob Creation Generated Warnings", MessageBoxButtons.OK);
            }
            if (mobs[mobs.LastIndexOf(mobs.Last())].bCritFailure)
            {
                return(false);
            }

            checkConstraints("mob");

            if (bDataConstraintErrExists)
            {
                return(false);
            }

            appendSourceFile(newMob.mobLocale, mobStr);

            return(true);
        }
Example #49
0
 public void setSectList(string section, string[] tab)
 {
     List<string> sections = new List<string>();
     foreach (INILine line in iniContent) sections.Add(line.section);
     string iSection = section.ToLower(Statics.Culture);
     int firstIndex = sections.IndexOf(iSection);
     int lastIndex = sections.LastIndexOf(iSection);
     List<string> iTab = new List<string>();
     List<string> lTab = new List<string>();
     foreach (string tmpStr in tab) {
         iTab.Add(tmpStr.ToLower(Statics.Culture));
         lTab.Add(tmpStr);
     }
     if (firstIndex == -1) {
         if (iniContent.Count > 0) {
             INILine line = iniContent[iniContent.Count - 1];
             if (line.entry != "" || line.comment != "") {
                 INILine.setSection = line.section;
                 iniContent.Add(new INILine(""));
                 firstIndex++;
             }
         }
         INILine.setSection = section;
         firstIndex = lastIndex = iniContent.Count;
         iniContent.Add(new INILine("[" + section + "]"));
     }
     for (int i = lastIndex; i > firstIndex; i--) {
         INILine line = iniContent[i];
         int index = iTab.IndexOf(line.iEntry);
         if (index != -1) {
             iTab.RemoveAt(index);
             lTab.RemoveAt(index);
         } else if (line.comment != "") {
             line.entry = INIComment + line.entry;
             modified = true;
         } else {
             iniContent.RemoveAt(i);
             lastIndex--;
             modified = true;
         }
     }
     INILine.setSection = section;
     if (iniContent[lastIndex].entry != "" || iniContent[lastIndex].comment != "") iniContent.Insert(++lastIndex, new INILine(""));
     for (int i = lTab.Count - 1; i >= 0; i--) {
         iniContent.Insert(lastIndex, new INILine(lTab[i]));
         modified = true;
     }
 }
Example #50
0
    static void Main()
    {
        List <string> carros1 = new List <string>();

        string[] carros2 = new string[10];

        carros1.Add("Golf");
        carros1.Add("HRV");
        carros1.Add("Focus");
        carros1.Add("Argo");
        carros1.Add("HRV");

        // carros2.AddRange(carros1); Carro 2 recebe os elementos de carro 1

        // carros2.Clear(); Limpa todos os elementos da lista

        if (carros1.Contains("Gol"))
        {
            Console.WriteLine("Elemento está na lista.");
        }
        else
        {
            Console.WriteLine("Elemento não está na lista.");
        }

        carros1.CopyTo(carros2, 2); //Para onde quero copiar e a partir de qual posição

        carros1.Insert(1, "Cruze"); //Inserir na posicao 1 o Cruze

        int localizacao = carros1.LastIndexOf("HRV");

        /*
         * carros1.RemoveAt(0);
         *
         * if (carros1.Remove("Argo"))
         * {
         *  Console.WriteLine("Argo removido da lista!");
         * }
         * else
         * {
         *  Console.WriteLine("Carro não removido!");
         * }
         */

        //carros1.Reverse(); Inverter lista

        carros1.Sort(); //Ordenar lista

        int tamanho = carros1.Count;

        carros1.Capacity = 15;
        int capacidade = carros1.Capacity;

        Console.WriteLine("Tamanho da lista: {0}", tamanho);
        Console.WriteLine("Capacidade: {0}", capacidade);

        foreach (string c in carros1)
        {
            Console.WriteLine("Carro: {0}", c);
        }

        string carro   = "HRV";
        int    posicao = 0;

        posicao = carros1.IndexOf(carro);
        Console.WriteLine("Carro {0} está na posição {1}", carro, posicao);
        Console.WriteLine("Último HRV está na posição {0}", localizacao);
    }
Example #51
0
 private void keySet(string section, string key, bool useString, string sValue, double dValue)
 {
     List<string> sections = new List<string>();
     List<string> keys = new List<string>();
     List<string> comments = new List<string>();
     foreach (INILine line in iniContent) {
         sections.Add(line.section);
         keys.Add(line.iKey);
         comments.Add(line.comment);
     }
     bool isDef = useString ? isDefault(section, key, sValue) : isDefault(section, key, dValue);
     INIVariableDef vd = getVarDefn(section, key);
     string iSection = section.ToLower(Statics.Culture);
     string iKey = key.ToLower(Statics.Culture);
     int firstIndex = sections.IndexOf(iSection);
     int lastIndex = sections.LastIndexOf(iSection);
     int index = keys.IndexOf(iKey);
     INILine.setSection = section;
     INILine tmp = new INILine(key + "=");
     tmp.defVal = vd.defValue;
     tmp.varType = vd.type;
     tmp.varDict = vd.dict;
     tmp.varBool = vd.boolType;
     tmp.useMinMax = vd.useMinMax;
     tmp.min = vd.min;
     tmp.max = vd.max;
     if (useString) tmp.sValue = sValue;
     else {
         if (vd.precision != -1) dValue = double.Parse (dValue.ToString ("F" + vd.precision.ToString ()));
         tmp.dValue = dValue;
     }
     if (firstIndex == -1) {
         if (!saveDef && isDef) return;
         if (iniContent.Count > 0) {
             INILine line = iniContent[iniContent.Count - 1];
             if (line.entry != "" || line.comment != "") {
                 INILine.setSection = line.section;
                 iniContent.Add(new INILine(""));
                 firstIndex++;
             }
         }
         INILine.setSection = section;
         iniContent.Add(new INILine("[" + section + "]"));
         iniContent.Add(tmp);
         iniContent.Add(new INILine(""));
     } else if (index >= firstIndex && index <= lastIndex) {
         if (!saveDef && isDef && comments[index] == "") iniContent.RemoveAt(index);
         else if (useString && iniContent[index].value == sValue || !useString && iniContent[index].dValue == dValue) return;
         else if (useString) iniContent[index].sValue = sValue;
         else iniContent[index].dValue = dValue;
     } else {
         if (!saveDef && isDef) return;
         INILine line = iniContent[lastIndex++];
         if (line.entry != "" || line.comment != "") {
             iniContent.Insert(lastIndex, new INILine(""));
             iniContent.Insert(lastIndex, tmp);
         } else iniContent.Insert(lastIndex - 1, tmp);
     }
     modified = true;
 }
Example #52
0
        /// <summary>
        /// Replaces all strings having the form \label{name_of_label} with consecutive elements in Numbers, all
        /// strings of the form \ref{name_of_label} with numbers corresponding to the name_of_label
        /// Strings of the form "\label{name_of_label}" are added to the list
        /// Fills properties "LabelsFull" and "ReferencesFull"
        /// </summary>
        public void Replace()
        {
            const string AnyToFind = @"(.*?)";


            Regex LabelsRegex = new Regex(@"\\" + "label" + @"\{" + AnyToFind + @"\}");
            //Regex LabelsRegex = new Regex((MyStringOperations.ReplaceParameters(LabelsPattern, AnyToFind)));
            //Regex ReferenceRegex = new Regex(MyStringOperations.ReplaceParameters(ReferencePattern, AnyToFind));
            Regex ReferenceRegex = new Regex(Regex.Escape(@"\") + "ref" + Regex.Escape(@"{") + AnyToFind + Regex.Escape(@"}"));



            //Put into FoundLabels all labels found in the string Text
            MatchCollection FoundLabels = LabelsRegex.Matches(Text);


            const int StartNumber = 1;
            int       Number      = StartNumber;


            //Replace all labels with appropriate numbers
            foreach (Match Found in FoundLabels)
            {
                string LabelsString = MyStringOperations.ReplaceParameters(ReferencePattern, Found.Groups[1].ToString());

                Regex LabelsInstance = new Regex(LabelsString);


                string LabelFull = MyStringOperations.ReplaceParameters(LabelsPattern, Found.Groups[1].ToString());



                Text = LabelsInstance.Replace(Text, Number.ToString());
                Numbers.Add(Number);


                if (Labels.Contains(Found.Groups[1].ToString()))
                {
                    const string Duplicates = "Duplicate labels: ";
                    MessageBox.Show(Duplicates + Found.Groups[1].ToString());
                    //throw new InvalidOperationException(Duplicates + Found.Groups[1].ToString());
                }

                Labels.Add(Found.Groups[1].ToString());

                LabelsFull.Add(@Found.ToString());
                Number++;
            }


            MatchCollection FoundReferences = ReferenceRegex.Matches(Text);

            //Replace all references with appropriate numbers


            //Fill the properties: References and ReferencesFull
            foreach (Match Found in FoundReferences)
            {
                if (!References.Contains(Found.Groups[1].ToString()))
                {
                    References.Add(Found.Groups[1].ToString());
                    ReferencesFull.Add(@Found.ToString());
                }
            }


            foreach (string Reference in References)
            {
                if (!Labels.Contains(Reference))
                {
                    const string Unresolved = "Unresolved reference: ";
                    MessageBox.Show(Unresolved + Reference);
                    //throw new InvalidOperationException(Unresolved + Reference);
                }
                else
                {
                    int    ReferenceNumber = Labels.LastIndexOf(Reference) + 1;
                    string InstanceString  = MyStringOperations.ReplaceParameters(ReferencePattern, Reference);
                    Regex  Instance        = new Regex(InstanceString);
                    Text = Instance.Replace(Text, Numbers[ReferenceNumber - 1].ToString());
                }
            }
        }
Example #53
0
        static void handleResult(IAsyncResult result)
        {
            //string outputFile = @"C:\dev\csharp\Stream_Data.txt";     //Uncomment and update if you want to write to a local file.
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;

            using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
            using (Stream stream = response.GetResponseStream())
            using (MemoryStream memory = new MemoryStream())
            {
                byte[] compressedBuffer = new byte[8192];
                byte[] uncompressedBuffer = new byte[8192];
                List<byte> output = new List<byte>();

                while (stream.CanRead)
                {
                    AddToConsole(" +++ Reading Stream");

                    try
                    {
                        int readCount = stream.Read(compressedBuffer, 0, compressedBuffer.Length);

                        memory.Write(compressedBuffer.Take(readCount).ToArray(), 0, readCount);
                        memory.Position = 0;

                        int uncompressedLength = memory.Read(uncompressedBuffer, 0, uncompressedBuffer.Length);

                        output.AddRange(uncompressedBuffer.Take(uncompressedLength));

                        byte[] bytesToDecode = output.Take(output.LastIndexOf(0x0A) + 1).ToArray();
                        string outputString = Encoding.UTF8.GetString(bytesToDecode);
                        output.RemoveRange(0, bytesToDecode.Length);

                        string[] lines = outputString.Split(new[] { Environment.NewLine }, new StringSplitOptions());

                        for (int i = 0; i < (lines.Length - 1); i++)
                        {
                            string heartBeatCheck = lines[i];
                            if (heartBeatCheck.Trim().Length > 0)
                            {
                                AddToConsole(lines[i]);  //Just print out to console window...
                                //File.AppendAllText(outputFile, lines[i] + Environment.NewLine); //Write out to the file...
                            }
                            else
                            {
                                AddToConsole(" ♥♥♥ Heartbeat Received");
                            }
                        }
                    }
                    catch (Exception error)
                    {
                        AddToConsole(error.Message);
                        // Handle the error as needed here
                    }

                    memory.SetLength(0);    // Everything needs to reach this line otherwise you will end up with
                                            // merged activities and loads of errors. i.e. do not use "return", "continue" etc.
                                            // above this line without setting the memory length to ZERO first.
                }

                if (!stream.CanRead)
                {
                    AddToConsole(" --- Cannot Read Stream");
                    // Handle the situation as needed here. The stream is probably corrupted.
                }
            }
        }
Example #54
0
        /************************************************************************
        *  //计算公式实例:r*(a*(a*(b+c)-d)-e)*(a*(a*(b+c)-d)-e)/(a*(a*(b+c)-d)-e)-s
        *  1、提取计算公式:式1:a*(a*(b+c)-d)-e)*(a*(a*(b+c)-d)-e)/(a*(a*(b+c)-d)-e 和 式0:r*-s
        *  2、对计算公式 式1进行递归:得:式3:a*(b+c)-d)-e)*(a*(a*(b+c)-d)-e)/(a*(a*(b+c)-d
        * 对计算公式 式1进行递归:得:式4:b+c)-d)-e)*(a*(a*(b+c)-d)-e)/(a*(a*(b+c
        * 对计算公式 式1进行递归:得:式5:a*(a*(b+c)-d)-e=n
        * 对计算公式 式1进行递归:得:式6:a*(b+c)-d=m
        * 对计算公式 式1进行递归:得:式7:b+c  计算得:b+c=z;
        *  3、将z代入式6中,得a*z-d=m;
        * 3、将m代入式5中,得a*m-e=n;
        *  4、将n代入式4中得:式8:b+c)-d)-e)*n/(a*(a*(b+c
        * 将式8分解为两部分:式9:b+c)-d)-e和式10:*n/(a*(a*(b+c
        * 计算式9:b+c)-d)-e=o,将o代入式10中得:o*n/(a*(a*(b+c=p
        *
        ************************************************************************/

        #region 分层去除公式中的括号进行计算:
        private List <string> BracketRemove(List <string> list)
        {
            while (list.Contains("(") || list.Contains(")"))
            {
                List <string> listTmp1     = new List <string>(list);
                List <string> listTmp2     = new List <string>();   //子项;
                int           frontBracket = list.IndexOf("(");
                int           backBracket  = list.LastIndexOf(")");

                #region  括号的第一种情况:a * (arrayList) / b
                if (frontBracket >= 0 && frontBracket < backBracket)
                {
                    list.RemoveRange(frontBracket, backBracket - frontBracket + 1);
                    listTmp1.RemoveRange(0, frontBracket + 1);
                    int backBracket2 = listTmp1.LastIndexOf(")");
                    listTmp1.RemoveRange(backBracket2, listTmp1.Count - backBracket2);

                    listTmp2 = new List <string>(BracketRemove(listTmp1));
                    list.InsertRange(frontBracket, listTmp2);
                }
                #endregion
                #region  括号的第二种情况:a + b) * (a + b
                else if (backBracket > 0 && backBracket < frontBracket)
                {
                    //计算)前的部分;
                    list.RemoveRange(0, backBracket + 1);
                    listTmp1.RemoveRange(backBracket, listTmp1.Count - backBracket);

                    listTmp2 = new List <string>(BracketRemove(listTmp1));
                    list.InsertRange(0, listTmp2);

                    //计算(后的部分;
                    int frontBracket2 = list.IndexOf("(");
                    listTmp1 = new List <string>(list);
                    list.RemoveRange(frontBracket2, list.Count - frontBracket2);
                    listTmp1.RemoveRange(0, frontBracket2 + 1);

                    listTmp2 = new List <string>(BracketRemove(listTmp1));
                    list.InsertRange(frontBracket2, listTmp2);
                }
                #endregion
                #region  括号的第三种情况:a * ( b + c
                else if (backBracket < 0 && frontBracket > 0)
                {
                    int frontBracket2 = list.IndexOf("(");
                    list.RemoveRange(frontBracket2, list.Count - frontBracket2);
                    listTmp1.RemoveRange(0, frontBracket2 + 1);

                    listTmp2 = new List <string>(BracketRemove(listTmp1));
                    list.InsertRange(frontBracket2, listTmp2);
                }
                #endregion
                #region  括号的第四种情况:a + b )* c
                else if (frontBracket < 0 && backBracket > 0)
                {
                    int backBracket2 = list.IndexOf(")");
                    list.RemoveRange(0, backBracket2 + 1);
                    listTmp1.RemoveRange(backBracket2, listTmp1.Count - backBracket2);

                    listTmp2 = new List <string>(BracketRemove(listTmp1));
                    list.InsertRange(0, listTmp2);
                }
                #endregion
            }
            double temp = MathCal(list);
            list.RemoveRange(0, list.Count);
            list.Add(Convert.ToString(temp));
            return(list);
        }
        /// <summary>
        /// On Level Change
        /// </summary>
        void HandleGameSceneLevelChangeDetected(object sender, EventArgs e)
        {
            Reset ();
            List<string> variables = new List<string>();

            // IF A QUALITY IS IN THE LEVEL, AND IT HAS A VARIENT (E.G. FOR COLOR, AT LEAST 2 COLORS ARE USED)
            // THEN IT IS INCLUDED IN THE LEVEL TITLE AND WILL BE WORTH POINTS
            foreach (string key in QualityManager.Instance.qualityDict.Keys) {
                if ( key == "QOrientation") continue;
                var variations = QualityManager.Instance.qualityDict[key];
                if( variations[0] != null && variations[1] != null && variations[2] != null ) {
                    variables.Add(key.Substring(1));
                }
            }

            switch(GameScene.currentLevel) {
            case 0:
                levelTitle.Title = "crystallon tutorial";
                break;
            case 999:
                levelTitle.Title = "crystallon challenge mode";
                variables[variables.LastIndexOf("Particle")] = LoadingScene.GAME_SCENE_DATA.fourthQuality;
                if(GameScene.gameTimeLimit > 0.0f) {
                    float minutes = GameScene.gameTimeLimit/60.0f;
                    levelTitle.Title += ": " + minutes.ToString("#0.#") + " minute limit";
                }
                break;
            default:
                levelTitle.Title = "crystallon puzzle " + GameScene.currentLevel.ToString();
                break;
            }
            levelTitle.SetQualityNames( variables.ToArray() );
            levelTitle.SlideIn();
        }
Example #56
0
 /// <summary>
 /// Searches for the specified object and returns the zero-based index of the last occurrence within the range of elements in the EventList&lt;IFeature&gt; that contains the specified number of elements and ends at the specified index.
 /// </summary>
 /// <param name="item">The object to locate in the EventList&lt;IFeature&gt;. The value can be null for reference types.</param>
 /// <param name="index">The zero-based starting index of the backward search.</param>
 /// <param name="count">The number of elements in the section to search.</param>
 /// <returns>The zero-based index of the last occurrence of item within the range of elements in the EventList&lt;IFeature&gt; that contains count number of elements and ends at index, if found; otherwise, �</returns>
 /// <exception cref="System.ArgumentOutOfRangeException">index is outside the range of valid indexes for the EventList&lt;IFeature&gt;.-or-count is less than 0.-or-index and count do not specify a valid section in the EventList&lt;IFeature&gt;.</exception>
 public virtual int LastIndexOf(IFeature item, int index, int count)
 {
     return(_list.LastIndexOf(item, index, count));
 }
Example #57
0
        private String GetParentFolderFromPath(String Path)
            {
            String Result =  String.Empty;
            List<Char> TempList = new List<Char>();
           
            foreach (Char Letter in Path)
            {
                TempList.Add(Letter);
            }

            TempList.RemoveRange(0, TempList.LastIndexOf('\\'));
            try
            {
                TempList.Remove('\\');
            }
            catch
            {

            }

            foreach (Char Letter in TempList)
            {
                Result = Result + Letter;
            }


            return Result;

            }
        private Quad GetQuad(double ColumnValue, double RowValue, List <double> ColumnHeaders, List <double> RowHeaders, List <List <double> > Data)
        {
            //check for boundaries

            double ColumnLeft, ColumnRight, RowAbove, RowBelow;
            int    columnLeftIndex, columnRightIndex, rowAboveIndex, rowBelowIndex;


            if (RowHeaders.Count != Data.Count || ColumnHeaders.Count != Data[0].Count)
            {
                throw new Exception("Inconsistent data. Row or column headers do not match data.");
            }

            //SPECIAL CASES: coumn or row value out of range
            //----------------------------------------------------

            if (ColumnValue < ColumnHeaders[0] || ColumnValue > ColumnHeaders[ColumnHeaders.Count - 1] || RowValue <RowHeaders[0] || RowValue> RowHeaders[RowHeaders.Count - 1])
            {
                if (ColumnValue < ColumnHeaders[0] || ColumnValue > ColumnHeaders[ColumnHeaders.Count - 1])
                {
                    if (ColumnValue < ColumnHeaders[0])
                    {
                        columnLeftIndex  = 0;
                        columnRightIndex = 0;
                    }
                    else // if ( ColumnValue > ColumnHeaders[ColumnHeaders.Count - 1])
                    {
                        columnLeftIndex  = ColumnHeaders.Count - 1;
                        columnRightIndex = ColumnHeaders.Count - 1;
                    }

                    //Find low and high ROW values
                    RowAbove      = RowHeaders.Where(rv => rv <= RowValue).Max();
                    rowAboveIndex = RowHeaders.LastIndexOf(RowAbove);
                    RowBelow      = RowHeaders.Where(rv => rv >= RowValue).Min();
                    rowBelowIndex = RowHeaders.LastIndexOf(RowBelow);
                }


                else //if (RowValue < RowHeaders[0] || RowValue > RowHeaders[RowHeaders.Count - 1])
                {
                    if (RowValue < RowHeaders[0])
                    {
                        rowAboveIndex = 0;
                        rowBelowIndex = 0;
                    }
                    else  //if (RowValue > RowHeaders[RowHeaders.Count-1])
                    {
                        rowAboveIndex = RowHeaders.Count - 1;
                        rowBelowIndex = RowHeaders.Count - 1;
                    }
                    //Find low and high COLUMN values
                    ColumnLeft       = ColumnHeaders.Where(cv => cv <= ColumnValue).Max();
                    columnLeftIndex  = RowHeaders.LastIndexOf(ColumnLeft);
                    ColumnRight      = ColumnHeaders.Where(cv => cv >= ColumnValue).Min();
                    columnRightIndex = RowHeaders.LastIndexOf(ColumnRight);
                }
            }
            else
            {
                //Interpolated value within data table
                // REGULAR CASE
                //----------------------------------------------------

                List <List <DataPoint2D> > DataPoints = new List <List <DataPoint2D> >();

                //Create array of datapoints
                for (int i = 0; i < RowHeaders.Count; i++)
                {
                    int j = 0;
                    List <DataPoint2D> thisRowOfPoints = new List <DataPoint2D>();

                    foreach (var item in Data[i])
                    {
                        thisRowOfPoints.Add(new DataPoint2D((decimal)ColumnHeaders[j], (decimal)RowHeaders[i], (decimal)Data[i][j]));
                    }
                    DataPoints.Add(thisRowOfPoints);
                }

                ColumnLeft       = ColumnHeaders.Where(cv => cv <= ColumnValue).Max();
                columnLeftIndex  = ColumnHeaders.FindIndex(x => x == ColumnLeft);
                ColumnRight      = ColumnHeaders.Where(cv => cv >= ColumnValue).Min();
                columnRightIndex = ColumnHeaders.FindIndex(x => x == ColumnRight);


                RowAbove      = RowHeaders.Where(cv => cv <= RowValue).Max();
                rowAboveIndex = RowHeaders.FindIndex(x => x == RowAbove);
                RowBelow      = RowHeaders.Where(cv => cv >= RowValue).Min();
                rowBelowIndex = RowHeaders.FindIndex(x => x == RowBelow);
            }


            DataPoint2D lowerLeftPoint  = new DataPoint2D((decimal)ColumnHeaders[columnLeftIndex], (decimal)RowHeaders[rowBelowIndex], (decimal)Data[rowBelowIndex][columnLeftIndex]);
            DataPoint2D lowerRightPoint = new DataPoint2D((decimal)ColumnHeaders[columnRightIndex], (decimal)RowHeaders[rowBelowIndex], (decimal)Data[rowBelowIndex][columnRightIndex]);
            DataPoint2D upperLeftPoint  = new DataPoint2D((decimal)ColumnHeaders[columnLeftIndex], (decimal)RowHeaders[rowAboveIndex], (decimal)Data[rowAboveIndex][columnLeftIndex]);
            DataPoint2D upperRightPoint = new DataPoint2D((decimal)ColumnHeaders[columnRightIndex], (decimal)RowHeaders[rowAboveIndex], (decimal)Data[rowAboveIndex][columnRightIndex]);

            Quad q = new Quad()
            {
                LowerLeftPoint  = lowerLeftPoint,
                LowerRightPoint = lowerRightPoint,
                UpperLeftPoint  = upperLeftPoint,
                UpperRightPoint = upperRightPoint
            };

            return(q);
        }
        public HttpResponseMessage SpecBuild(int id,  JObject moveTaskParams)
        {
            dynamic json = moveTaskParams;
            string jsonString = Convert.ToString(json.data);
            var response = Request.CreateResponse();
            List<CategoryViewModel> jCategory = (List<CategoryViewModel>)javaScriptSerializ­er.Deserialize(jsonString, typeof(List<CategoryViewModel>));

            //Iterate through data list collection
            List <List <string>> propNames = new List<List<string>>();
            List<List<string>> propParamsVal = new List<List<string>>();
            List<string> propLabel = new List<string>();
            List<string> propValues = new List<string>();
            List<string> propParams = new List<string>();
            List<string> propMathsParams = new List<string>();
            List<string> propInputParams = new List<string>();
            int LoopCounter = 0;
            LoopCounter = 0;

            foreach (var item in jCategory)
            {
                //
                LoopCounter = 0;
                propValues.Add(item.Name);
                propValues.Add(item.Description);
                propNames.Add(propValues);
                propValues = new List<string>();

                foreach (var list in item.Functions)
                {
                    //Propoerties for the row
                    LoopCounter = LoopCounter + 1;
                    propValues.Add(Convert.ToString(list.ID));
                    propValues.Add(Convert.ToString(list.Name));
                    propValues.Add(Convert.ToString(list.Function));
                    propValues.Add(Convert.ToString(list.Type));

                    //Logic string
                    List<string> logicString = new List<string>();
                    foreach (var logicvar in list.Logic)
                    {
                        logicString.Add(Convert.ToString(logicvar.Bracket1 + " " + logicvar.Input1 + " "
                            + " " + logicvar.LogicInd + " " + logicvar.Input2 + " " + logicvar.Bracket2 + " " + logicvar.Operator));
                    }

                    StringBuilder builderLogic = new StringBuilder();
                    foreach (var logiclevel in logicString)
                    {
                        // Append each int to the StringBuilder overload.
                        builderLogic.Append(logiclevel).Append(" ");
                    }
                    //Add row
                    propValues.Add(Convert.ToString(builderLogic));

                    //Functions
                    if (list.Function != "Input")
                    {
                        if(list.Function == "Maths")
                        {
                            //Maths string builder
                            List<string> mathString = new List<string>();
                            foreach (var Mathvar in list.Parameter)
                            {
                                Maths MathsObject = new Maths();
                                foreach (var MathvarLevel in Mathvar)
                                {
                                    if(MathvarLevel.Key == "Bracket1")
                                    {
                                        MathsObject.Bracket1 = MathvarLevel.Value;
                                    }
                                    else if (MathvarLevel.Key == "Input1")
                                    {
                                        MathsObject.Input1 = MathvarLevel.Value;
                                    }
                                    else if (MathvarLevel.Key == "Logic")
                                    {
                                        MathsObject.Logic = MathvarLevel.Value;
                                    }
                                    else if (MathvarLevel.Key == "Input2")
                                    {
                                        MathsObject.Input2 = MathvarLevel.Value;
                                    }
                                    else if (MathvarLevel.Key == "Bracket2")
                                    {
                                        MathsObject.Bracket2 = MathvarLevel.Value;
                                    }
                                    else if (MathvarLevel.Key == "Rounding")
                                    {
                                        if(MathvarLevel.Value != null)
                                        {
                                            MathsObject.Rounding = Convert.ToInt16(MathvarLevel.Value);
                                        }
                                        else
                                        {
                                            MathsObject.Rounding = null;
                                        }
                                    }
                                    else if (MathvarLevel.Key == "RoundingType")
                                    {
                                        MathsObject.RoundingType = MathvarLevel.Value;
                                    }
                                    else if (MathvarLevel.Key == "Logic2")
                                    {
                                        MathsObject.Logic2 = MathvarLevel.Value;
                                    }
                                }
                                //Show maths formula with rounding
                                if(MathsObject.Rounding > 0)
                                {
                                    mathString.Add(Convert.ToString(MathsObject.Bracket1 + "" + MathsObject.Input1 + " "
                                   + MathsObject.Logic + " " + MathsObject.Input2 + "" + MathsObject.Bracket2 + " "
                                   + MathsObject.Rounding + "dp " + MathsObject.RoundingType + " " + MathsObject.Logic2));
                                }
                                else
                                {
                                    mathString.Add(Convert.ToString(MathsObject.Bracket1 + "" + MathsObject.Input1 + " "
                                   + MathsObject.Logic + " " + MathsObject.Input2 + "" + MathsObject.Bracket2 + " "
                                   + MathsObject.Rounding + "" + MathsObject.RoundingType + "" + MathsObject.Logic2));
                                }
                            }
                            StringBuilder MathStringbuilder = new StringBuilder();
                            foreach (var bitmathlevel in mathString)
                            {
                                // Append each int to the StringBuilder overload.
                                MathStringbuilder.Append(bitmathlevel).Append(" ");
                            }
                            //Add to List
                            propValues.Add(Convert.ToString(MathStringbuilder));
                            propMathsParams = new List<string>();
                        }
                        else
                        {
                            foreach (var bit in list.Parameter)
                            {
                                foreach (var bitlevel in bit)
                                {
                                    propParams.Add(Convert.ToString(bitlevel.Key));
                                    propParams.Add(":");
                                    propParams.Add(Convert.ToString(bitlevel.Value));
                                    propParams.Add("~");
                                }
                                propParams.RemoveAt(propParams.LastIndexOf("~"));
                                StringBuilder builder = new StringBuilder();
                                foreach (var bitlevel in propParams)
                                {
                                    // Append each int to the StringBuilder overload.
                                    builder.Append(bitlevel).Append(" ");
                                }
                                propValues.Add(Convert.ToString(builder));
                                propParams = new List<string>();
                            }
                        }
                    }
                    else
                    {
                        foreach(var InputVal in list.Parameter)
                        {
                            foreach(var InputVal1 in InputVal)
                            {
                                if(InputVal1.Key == "templateOptions")
                                {
                                    foreach(var InputVal2 in InputVal1.Value)
                                    {
                                        if(InputVal2.Key != "options")
                                        {
                                            propInputParams.Add(InputVal2.Key);
                                            propInputParams.Add(":");
                                            propInputParams.Add(Convert.ToString(InputVal2.Value));
                                            propInputParams.Add("~");
                                        }
                                    }
                                }
                            }
                        }
                        propInputParams.RemoveAt(propInputParams.LastIndexOf("~"));
                        StringBuilder inputbuilder = new StringBuilder();
                        foreach (var bitlevel2 in propInputParams)
                        {
                            // Append each int to the StringBuilder overload.
                            inputbuilder.Append(bitlevel2).Append(" ");
                        }
                        propValues.Add(Convert.ToString(inputbuilder));
                        propInputParams = new List<string>();
                    }
                    propNames.Add(propValues);
                    propValues = new List<string>();
                }
            }
            response.Content = new StringContent(JsonConvert.SerializeObject(propNames));
            response.StatusCode = HttpStatusCode.OK;
            return response;
        }
Example #60
0
        private double MathParserLogic(List <string> tokens)
        {
            // Variables replacement
            for (var i = 0; i < tokens.Count; i++)
            {
                if (LocalVariables.Keys.Contains(tokens[i]))
                {
                    tokens[i] = LocalVariables[tokens[i]].ToString(CultureInfo);
                }
            }

            while (tokens.IndexOf("(") != -1)
            {
                // getting data between "(" and ")"
                var open  = tokens.LastIndexOf("(");
                var close = tokens.IndexOf(")", open); // in case open is -1, i.e. no "(" // , open == 0 ? 0 : open - 1

                if (open >= close)
                {
                    throw new ArithmeticException("No closing bracket/parenthesis. Token: " + open.ToString(CultureInfo));
                }

                var roughExpr = new List <string>();

                for (var i = open + 1; i < close; i++)
                {
                    roughExpr.Add(tokens[i]);
                }

                double tmpResult;

                var args         = new List <double>();
                var functionName = tokens[open == 0 ? 0 : open - 1];

                if (LocalFunctions.Keys.Contains(functionName))
                {
                    if (roughExpr.Contains(","))
                    {
                        // converting all arguments into a double array
                        for (var i = 0; i < roughExpr.Count; i++)
                        {
                            var defaultExpr = new List <string>();
                            var firstCommaOrEndOfExpression =
                                roughExpr.IndexOf(",", i) != -1
                                    ? roughExpr.IndexOf(",", i)
                                    : roughExpr.Count;

                            while (i < firstCommaOrEndOfExpression)
                            {
                                defaultExpr.Add(roughExpr[i++]);
                            }

                            args.Add(defaultExpr.Count == 0 ? 0 : BasicArithmeticalExpression(defaultExpr));
                        }

                        // finally, passing the arguments to the given function
                        tmpResult = double.Parse(LocalFunctions[functionName](args.ToArray()).ToString(CultureInfo), CultureInfo);
                    }
                    else
                    {
                        if (roughExpr.Count == 0)
                        {
                            tmpResult = LocalFunctions[functionName](new double[0]);
                        }
                        else
                        {
                            tmpResult = double.Parse(LocalFunctions[functionName](new[]
                            {
                                BasicArithmeticalExpression(roughExpr)
                            }).ToString(CultureInfo), CultureInfo);
                        }
                    }
                }
                else
                {
                    // if no function is need to execute following expression, pass it
                    // to the "BasicArithmeticalExpression" method.
                    tmpResult = BasicArithmeticalExpression(roughExpr);
                }

                // when all the calculations have been done
                // we replace the "opening bracket with the result"
                // and removing the rest.
                tokens[open] = tmpResult.ToString(CultureInfo);
                tokens.RemoveRange(open + 1, close - open);

                if (LocalFunctions.Keys.Contains(functionName))
                {
                    // if we also executed a function, removing
                    // the function name as well.
                    tokens.RemoveAt(open - 1);
                }
            }

            // at this point, we should have replaced all brackets
            // with the appropriate values, so we can simply
            // calculate the expression. it's not so complex
            // any more!
            return(BasicArithmeticalExpression(tokens));
        }