Example #1
0
		List<byte> CreateInputBytes(List<byte> messageBytes)
		{
			var bytes = new List<byte>();
			var previousByte = new byte();
			messageBytes.RemoveRange(0, messageBytes.IndexOf(0x7E) + 1);
			messageBytes.RemoveRange(messageBytes.IndexOf(0x3E), messageBytes.Count - messageBytes.IndexOf(0x3E));
			foreach (var b in messageBytes)
			{
				if ((b == 0x7D) || (b == 0x3D))
				{ previousByte = b; continue; }
				if (previousByte == 0x7D)
				{
					previousByte = new byte();
					if (b == 0x5E)
					{ bytes.Add(0x7E); continue; }
					if (b == 0x5D)
					{ bytes.Add(0x7D); continue; }
				}
				if (previousByte == 0x3D)
				{
					previousByte = new byte();
					if (b == 0x1E)
					{ bytes.Add(0x3E); continue; }
					if (b == 0x1D)
					{ bytes.Add(0x3D); continue; }
				}
				bytes.Add(b);
			}
			return bytes;
		}
Example #2
0
	public static AudioClip TrimSilence(List<float> samples, float min, int channels, int hz, bool _3D, bool stream) {
		int i;
 
		// remove samples at the beginning
		for (i=0; i<samples.Count; i++) {
			if (Mathf.Abs(samples[i]) > min) {
				break;
			}
		} 
		samples.RemoveRange(0, i);

		// sanity check
		if ( samples.Count != 0 )
		{ 
			// remove samples at the end
			for (i=samples.Count - 1; i>0; i--) {
				if (Mathf.Abs(samples[i]) > min) {
					break;
				}
			}
			samples.RemoveRange(i, samples.Count - i);
			UnityEngine.Debug.Log ("SaveWav.TrimSilence() samples after begin trim = " + samples.Count);
		}
		else
			UnityEngine.Debug.Log ("SaveWav.TrimSilence() no samples!");

		var clip = AudioClip.Create("TempClip", samples.Count, channels, hz, _3D, stream);
 
		if ( samples.Count != 0 )
			clip.SetData(samples.ToArray(), 0);

		return clip;
	}
Example #3
0
 private static void Last(List<int> array, string p1, string p2)
 {
     int count = int.Parse(p1);
     if (count > array.Count)
     {
         Console.WriteLine("Invalid count");
     }
     else
     {
         List<int> temp = new List<int>();
         if (p2 == "odd")
         {
             temp = array.Where(x => x % 2 == 1).ToList();
             if (count < temp.Count)
             {
                 temp.RemoveRange(0, temp.Count - count);
             }
             Console.WriteLine("[{0}]", string.Join(", ", temp));
         }
         else
         {
             temp = array.Where(x => x % 2 == 0).ToList();
             if (count < temp.Count)
             {
                 temp.RemoveRange(0, temp.Count - count);
             }
             Console.WriteLine("[{0}]", string.Join(", ", temp));
         }
     }
 }
        private void button1_Click(object sender, EventArgs e)
        {
            license = richTextBox1.Lines;
            IEnumerable<string> files = Directory.GetFiles (folder, textBox1.Text, SearchOption.AllDirectories);
            foreach (string file in files)
            {
                List<string> newLines = new List<string> ();
                newLines.AddRange (license);
                string[] lines = File.ReadAllLines (file);

                if (lines[0].StartsWith ("/*"))
                {
                    int endLine = 0;
                    for (int i = 0; i < lines.Length; i++)
                    {
                        if (lines[i].StartsWith (" */"))
                        {
                            endLine = i;
                            break;
                        }
                    }
                    List<string> l = new List<string>(lines);
                    l.RemoveRange(0, endLine + 1);
                    if (l[0] == "")
                        l.RemoveRange (0, 1);
                    newLines.AddRange (l);
                }
                else
                {
                    newLines.AddRange (lines);
                }
                File.WriteAllLines (file, newLines.ToArray ());
            }
        }
Example #5
0
        /// <summary>
        /// Declares a variable if there is a declaration and deletes unnessesary stuff
        /// </summary>
        /// <param name="listE"> stream of tokens </param>
        /// <returns> true if we need to launch the function again </returns>
        public static bool DeclareVariable(List<Element> listE)
        {
            if (listE.Count > 2) // it can be a declaration only if the list has more than 2 elements
            {
                if (listE[0].Type == C.Number && listE[1].Type == C.Control) // if it is a number
                {
                    string name = listE[0].GetNumber().Name;
                    if (name != "" && listE[1].ToString() == "=") // if it is a variable
                    {
                        listE.RemoveRange(0, 2);
                        Number num = new Number(Parse(listE).Value.ToString());
                        num.Name = name;
                        Variable.Add(num);

                        return false;
                    }
                }
            }

            int index = listE.FindIndex(delegate(Element e)
                                        { if (e.ToString() == "=") return true; return false; });
            if (index != -1) { listE.RemoveRange(0, index + 1); return true; }

            return false;
        }
    static void Main()
    {
        string s;
        int inputLines = int.Parse(Console.ReadLine());
        int desiredWidth = int.Parse(Console.ReadLine());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < inputLines; i++)
        {
            s = Console.ReadLine();
            sb.Append(s.Trim() + " ");
        }
        sb.Remove(sb.Length - 1, 1);
        string[] sWords = sb.ToString().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        List<string> words = new List<string>(sWords);
        do
        {

            sb.Clear();
            sb.Append(words[0]);
            int currentWord = 1;
            while (sb.Length < desiredWidth && currentWord < words.Count)
            {
                sb.Append(" " + words[currentWord]);
                currentWord++;
            }
            if (sb.Length > desiredWidth)
            {
                sb.Remove(sb.Length - words[currentWord - 1].Length - 1, words[currentWord - 1].Length + 1);
                currentWord--;
            }
                if (sb.Length == desiredWidth || currentWord == 1)
            {
                Console.WriteLine(sb);
                words.RemoveRange(0, currentWord);
                continue;
            }
            int spacecount = currentWord - 1;
            int sizeOfSpaces = (desiredWidth - sb.Length + spacecount) / spacecount; // / (currentWord - 1)
            int numOfLongSpaces = (desiredWidth - sb.Length + spacecount) % spacecount;
            sb.Clear();
            sb.Append(words[0]);
            for (int i = 1; i <= spacecount; i++)
            {
                if (i <= numOfLongSpaces)
                    sb.Append(" ");
                sb.Append(new string(' ',sizeOfSpaces) + words[i]);
            }
            Console.WriteLine(sb);
            words.RemoveRange(0, currentWord);
        } while (words.Count > 0);
    }
Example #7
0
        public object CreateDataShapeObject(DTO.ExpenseGroup expenseGroup, List<string> lstFields)
        {
            List<string> lstFieldsIncluded = new List<string>(lstFields);

            if (!lstFieldsIncluded.Any())
            {
                return expenseGroup;
            }
            else
            {
                var lstExpenseFields = lstFieldsIncluded.Where(s => s.Contains("expenses")).ToList();

                bool returnPartialExpense = lstFieldsIncluded.Any() && !lstFieldsIncluded.Contains("expenses");

                if (returnPartialExpense)
                {
                    lstFieldsIncluded.RemoveRange(lstExpenseFields);
                    lstExpenseFields = lstExpenseFields.Select(f => f.Substring(f.IndexOf(".") + 1)).ToList();
                }
                else
                {
                    lstExpenseFields.Remove("expenses");
                    lstFieldsIncluded.RemoveRange(lstExpenseFields);
                }


                ExpandoObject objToReturn = new ExpandoObject();
                foreach (var field in lstFieldsIncluded)
                {
                    var fieldValue = expenseGroup.GetType()
                        .GetProperty(field, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance)
                        .GetValue(expenseGroup, null);

                    ((IDictionary<string, object>)objToReturn).Add(field, fieldValue);
                }

                if(returnPartialExpense)
                {
                    List<object> expenses = new List<object>();
                    foreach(var expense in expenseGroup.Expenses)
                    {
                        expenses.Add(expenseFactory.CreateDataShapeObject(expense, lstExpenseFields));
                    }
                    ((IDictionary<string, object>)objToReturn).Add("expenses", expenses);
                }

                return objToReturn;
            }
        }
Example #8
0
        private void proc(List<int> Input, int step)
        {
            if (Input.Count < 1 || SELECT - step > Input.Count)
                return;
            if (step == SELECT - 1)
            {
                foreach (var item in Input)
                {
                    result[step] = item;
                    //OutputToArray();
                    //tets
                    print(result);
                }
            }

            else
            {
                foreach (var item in Input)
                {
                    List<int> tempInput = new List<int>();
                    tempInput.AddRange(Input);
                    result[step] = item;
                    tempInput.RemoveRange(0, tempInput.IndexOf(item) + 1);
                    proc(tempInput, step + 1);
                }
            }
        }
Example #9
0
	public static AudioClip TrimSilence(List<float> samples, float min, int channels, int hz, bool _3D, bool stream) {
		int i;

		for (i=0; i<samples.Count; i++) {
			if (Mathf.Abs(samples[i]) > min) {
				break;
			}
		}

		samples.RemoveRange(0, i);

		for (i=samples.Count - 1; i>0; i--) {
			if (Mathf.Abs(samples[i]) > min) {
				break;
			}
		}

		samples.RemoveRange(i, samples.Count - i);

		var clip = AudioClip.Create("TempClip", samples.Count, channels, hz, _3D, stream);

		clip.SetData(samples.ToArray(), 0);

		return clip;
	}
        public void ZnajdzOtoczke(List<Punkt> lista)
        {
            List<Punkt> listaTmp = new List<Punkt>();
            Stack stos = new Stack();

            stos.Push(lista[0]);
            stos.Push(lista[1]);
            stos.Push(lista[2]);

            listaTmp.Add(lista[0]);
            listaTmp.Add(lista[1]);
            listaTmp.Add(lista[2]);

            for (int i = 3; i < lista.Count; i++)
            {
                int j = i;
                while (ObliczDet(listaTmp[stos.Count - 2], listaTmp[stos.Count - 1], lista[i]) < 0)
                {
                    //Console.WriteLine(ObliczDet(lista[j - 2], lista[j - 1], lista[i]));
                    stos.Pop();
                    listaTmp.RemoveRange(stos.Count, 1);
                }
                stos.Push(lista[i]);
                listaTmp.Add(lista[i]);
            }
            int ileWierz = stos.Count;
            for (int i = 0; i < ileWierz; i++)
            {
                wierzcholki.Add((Punkt)stos.Pop());
            }
            wierzcholki.Reverse();
        }
Example #11
0
 public void FilterResultsInInterval(DateTime dtStart, DateTime dtEnd, List<Object> list)
 {
     if (null == list) return;
     if (list.Count < 2) return;
     list.Sort();
     list.RemoveRange(1, list.Count - 1);
 }
    /// <summary>
    /// Joins all sub sub scopes of the given <paramref name="scope"/>, reduces the number of sub 
    /// scopes by 1 and uniformly partitions the sub sub scopes again, maintaining the order.
    /// </summary>
    /// <exception cref="InvalidOperationException">Thrown when there are less than 2 sub-scopes available or when VillageCount does not equal the number of sub-scopes.</exception>
    /// <param name="scope">The current scope whose sub scopes to reduce.</param>
    /// <returns><c>null</c>.</returns>
    public override IOperation Apply() {
      IScope scope = ExecutionContext.Scope;
      if (VillageCountParameter.ActualValue == null) VillageCountParameter.ActualValue = new IntValue(scope.SubScopes.Count);
      int villageCount = VillageCountParameter.ActualValue.Value;
      if (villageCount <= 1)
        throw new InvalidOperationException(Name + ": Reunification requires 2 or more sub-scopes");
      if (villageCount != scope.SubScopes.Count)
        throw new InvalidOperationException(Name + ": VillageCount does not equal the number of sub-scopes");

      // get all villages
      List<IScope> population = new List<IScope>();
      for (int i = 0; i < villageCount; i++) {
        population.AddRange(scope.SubScopes[i].SubScopes);
        scope.SubScopes[i].SubScopes.Clear();
      }

      // reduce number of villages by 1 and partition the population again
      scope.SubScopes.RemoveAt(scope.SubScopes.Count - 1);
      villageCount--;
      int populationPerVillage = population.Count / villageCount;
      for (int i = 0; i < villageCount; i++) {
        scope.SubScopes[i].SubScopes.AddRange(population.GetRange(0, populationPerVillage));
        population.RemoveRange(0, populationPerVillage);
      }

      // add remaining individuals to last village
      scope.SubScopes[scope.SubScopes.Count - 1].SubScopes.AddRange(population);
      population.Clear();

      VillageCountParameter.ActualValue.Value = villageCount;

      return base.Apply();
    }
Example #13
0
 static void Main(string[] args)
 {
     InitComplements();
       var seq = new List<byte[]>();
       var b = new Block { Count = -1 };
       Index line = Index.None, start = Index.None, end = Index.None;
       using (var r = new BinaryReader(Console.OpenStandardInput())) {
      using (var w = Console.OpenStandardOutput()) {
         while (b.Read(r) > 0) {
            seq.Add(b.Data);
            if (line.Pos < 0) line = b.IndexOf(Gt, 0);
            while (line.Pos >= 0) {
               if (start.Pos < 0) {
                  var off = line.InBlock(b) ? line.Pos : 0;
                  start = b.IndexOf(Lf, off);
                  if (start.Pos < 0) {
                      w.Write(b.Data, off, b.Data.Length - off);
                      seq.Clear(); break;
                  }
                  w.Write(b.Data, off, start.Pos + 1 - off);
               }
               if (end.Pos < 0) {
                  end = b.IndexOf(Gt, start.InBlock(b) ? start.Pos : 0);
                  if (end.Pos < 0) break;
               }
               w.Reverse(start.Pos, end.Pos, seq);
               if (seq.Count > 1) seq.RemoveRange(0, seq.Count - 1);
               line = end; end = Index.None; start = Index.None;
            }
         }
         if (start.Pos >= 0 && end.Pos < 0)
            w.Reverse(start.Pos, seq[seq.Count -1].Length, seq);
      }
       }
 }
Example #14
0
        private static void Adjust_score_for_frame_11(List<int> frameScores)
        {
            if (frameScores.Count <= 10) return;

            frameScores.RemoveRange(10, frameScores.Count() - 10);
            frameScores.Add(0);
        }
        public ASCommandResponse(HttpWebResponse httpResponse)
        {
            httpStatus = httpResponse.StatusCode;

            Stream responseStream = httpResponse.GetResponseStream();
            List<byte> bytes = new List<byte>();
            byte[] byteBuffer = new byte[256];
            int count = 0;

            // Read the WBXML data from the response stream
            // 256 bytes at a time.
            count = responseStream.Read(byteBuffer, 0, 256);
            while (count > 0)
            {
                // Add the 256 bytes to the List
                bytes.AddRange(byteBuffer);

                if (count < 256)
                {
                    // If the last read did not actually read 256 bytes
                    // remove the extra.
                    int excess = 256 - count;
                    bytes.RemoveRange(bytes.Count - excess, excess);
                }

                // Read the next 256 bytes from the response stream
                count = responseStream.Read(byteBuffer, 0, 256);
            }

            wbxmlBytes = bytes.ToArray();

            // Decode the WBXML
            xmlString = DecodeWBXML(wbxmlBytes);
        }
        protected override void OnCreate(Android.OS.Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
           
						m_ImageLoader = new ImageLoader(this);

						
            _friends = Util.GenerateFriends();
            _friends.RemoveRange(0, _friends.Count - 2);
            var title = Intent.GetStringExtra("Title");
            var image = Intent.GetStringExtra("Image");

            title = string.IsNullOrWhiteSpace(title) ? "New Friend" : title;
            this.Title = title;

            if (string.IsNullOrWhiteSpace(image))
                image = _friends[0].Image;


            m_ImageLoader.DisplayImage(image, this.FindViewById<ImageView>(Resource.Id.friend_image), -1);
            this.FindViewById<TextView>(Resource.Id.friend_description).Text = title;

            var grid = FindViewById<GridView>(Resource.Id.grid);
            grid.Adapter = new MonkeyAdapter(this, _friends);
            grid.ItemClick += GridOnItemClick;

            //set title here
						SupportActionBar.Title = Title;
        }
Example #17
0
        public Sampler(List<List<String>> csvData, int sampleRate)
        {
            this.csvData = csvData;
            this.sampleRate = sampleRate;

            // Find column numbers of relevant data
            foreach (List<String> row in csvData)
            {
                int i = 0;
                foreach (String content in row)
                {
                    if (content == "Time") { timestampPosition = i; }
                    else if (content == "L POR X [px]") { eyeXColumnNo = i; }
                    else if (content == "L POR Y [px]") { eyeYColumnNo = i; }
                    else
                    {
                        foreach (Electrode electrode in (Electrode[])Enum.GetValues(typeof(Electrode)))
                        {
                            if (content == "EEG_RAW_" + electrode)
                            {
                                columnNumbers.Add(electrode, i);
                            }
                        }
                    }
                    i++;
                }
                if (i > 0) break;
            }

            csvData.RemoveRange(0, 2);
            csvData.RemoveAt(csvData.Count - 1);

            FindAllGoodSamples();
        }
        public void DownloadImage(string link, string pathAdding = null) {
            var path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            var fileName = link.Split('/')[7];
            var subs = pathAdding.Split('/');
            var name = subs[3];
            var list = new List<string>(subs);
            list.RemoveRange(0, 3);

            CreateDirectoryIfNeed(path);
            foreach (var info in list) {
                if (info.Contains("http"))
                    continue;

                if (string.IsNullOrEmpty(info))
                    continue;

                if (info.Contains("?mature"))
                    path += "\\" + info.Split('?')[0];
                else
                    path += "\\" + info;

                CreateDirectoryIfNeed(path);
            }

            _downloader.DownloadImage(link, path + "\\" + fileName);
        }
Example #19
0
        public List<int> GetPriceSum(List<int> costs, int numberOfGroup)
        {
            var result = new List<int>();

            if (numberOfGroup < 0) numberOfGroup = 1;

            var group = costs.Count % numberOfGroup == 0 ?
                costs.Count / numberOfGroup : costs.Count / numberOfGroup + 1;

            for (int i = 0; i < group; i++)
            {
                int total;
                if (costs.Count >= numberOfGroup)
                {
                    total = costs.Take(numberOfGroup).Sum();
                    result.Add(total);
                }
                else
                {
                    total = costs.Sum();
                    result.Add(total);
                    break;
                }

                costs.RemoveRange(0, numberOfGroup);
            }

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

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

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

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

        TestLibrary.TestFramework.BeginScenario("PosTest1: Remove all the elements in the int type list");

        try
        {
            int[] iArray = { 1, 9, 3, 6, -1, 8, 7, 10, 2, 4 };
            List<int> listObject = new List<int>(iArray);
            listObject.RemoveRange(0, 10);
            if (listObject.Count != 0)
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,count is: " + listObject.Count);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
Example #22
0
        private static void CheckForFlush(Player player)
        {
            var allCards = player.Hand.Concat(deck.BoardCards).ToList();//Combine the board & the players cards.
            List<int> flushCardsRanks = new List<int>();

            for (int a = 0; a < 4; a++)
            {
                foreach (Card card in allCards)
                {
                    if (card.Suit == a)
                    {
                        flushCardsRanks.Add(card.Rank);
                    }
                }

                if (flushCardsRanks.Count > 4)
                {
                    CheckForStraight(player, flushCardsRanks, true); //Sends all cards with same suit for straight check.

                    if (player.HandRank < 5) //No straight/royal flush setted by CheckfotStraight(), setting normal flush.
                    {
                        flushCardsRanks.Sort();
                        flushCardsRanks.RemoveRange(0, flushCardsRanks.Count - 5); //Leaving top 5 ranks from the flush.
                        flushCardsRanks.Reverse();
                        List<int> kickers = new List<int>();
                        kickers.Add(0); //No kickers in Flush.
                        player.SetRank(5, flushCardsRanks, kickers);
                    }
                    break; //Max one flush in a hand. Breaking.
                }

                flushCardsRanks.Clear();
            }
        }
        public override object Deserialize(List<byte> byteList, TLPropertyAttribute attribute)
        {
            int count = byteList.ReadByte();
            int startOffset = 1;

            if (count >= 254)
            {
                count = byteList.ReadByte();
                count += byteList.ReadByte() << 8;
                count += byteList.ReadByte() << 16;
                startOffset = 4;
            }

            TLBytes bytes = new TLBytes(byteList.Take(count).ToArray());
            byteList.RemoveRange(0, count);

            int offset = (count + startOffset) % 4;
            if (offset != 0)
            {
                int offsetCount = 4 - offset;
                for (int i = 0; i < offsetCount; i++)
                    byteList.ReadByte();
            }

            return bytes;
        }
Example #24
0
        public List<KeyValuePair<string, string>> GetKeysAndValues(string category)
        {
            // if category doesn't exist, should return an empty list.
            string returnString = new string(' ', MAXKEYSLENGTH);
            int res = GetPrivateProfileString(category, null, null, returnString, MAXKEYSLENGTH, this.m_fileName);
            /*if (res == 0)
            {
             maybe we just wrote 0 characters. TODO. how to distinguish between error case and nothing found case?
                Win32Exception wexp = new Win32Exception(Marshal.GetLastWin32Error());
                throw new IniFileParsingException("win32:" + wexp.Message);
            }*/
            if (res == MAXKEYSLENGTH - 2) //see docs: means buffer is full
            {
                throw new IniFileParsingException("data in key names is too long. must be <" + MAXKEYSLENGTH);
            }
            List<string> listKeys = new List<string>(returnString.Split('\0'));
            listKeys.RemoveRange(listKeys.Count - 2, 2); //removes the last 2 entries.

            //now let's build the actual list
            List<KeyValuePair<string, string>> result = new List<KeyValuePair<string,string>>();
            foreach (string sKey in listKeys)
            {
                result.Add( new KeyValuePair<string,string>(sKey, this.ReadValue(category, sKey)));
            }
            return result;
        }
Example #25
0
 public override void ProcessTree()
 {
     if (Root == null || Root.Items.Count == 0)
         return;
     List<ANY_TreeNode> Nodes = new List<ANY_TreeNode>();
     List<SourceEntity> Result = new List<SourceEntity>();
     foreach (ANY_TreeNode node in Root.Items)
     {
         if (node.Value.Count == 0)
             continue;
         if (node is CommentStart)
             Nodes.Add(node);
         if (node is CommentEnd)
         {
             int startIndex;
             for (startIndex = Nodes.Count - 1; startIndex >= 0; --startIndex)
                 if (node.Value[0] == Nodes[startIndex].Value[0])
                     break;
             if (startIndex < 0)
                 continue;
             ANY_TreeNode newNode = new ANY_TreeNode(Nodes[startIndex].Value, Nodes[startIndex].Location.Merge(node.Location));
             for (int i = startIndex + 1; i < Nodes.Count; ++i)
                 if (Nodes[i].GetType() == typeof(ANY_TreeNode))
                     newNode.Items.Add(Nodes[i]);
             Nodes.RemoveRange(startIndex, Nodes.Count - startIndex);
             Nodes.Add(newNode);
         }
     }
     foreach (ANY_TreeNode node in Nodes)
         if (node.GetType() == typeof(ANY_TreeNode))
             Result.Add(node);
     Root.Items = Result;
 }
Example #26
0
        public void Test(int arg)
        {
            ArrayList items = new ArrayList();
            items.Add(1);
            items.AddRange(1, 2, 3);
            items.Clear();
            bool b1 = items.Contains(2);
            items.Insert(0, 1);
            items.InsertRange(1, 0, 5);
            items.RemoveAt(4);
            items.RemoveRange(4, 3);
            items.Remove(1);
            object[] newItems = items.GetRange(5, 2);
            object[] newItems2 = items.GetRange(5, arg);

            List<int> numbers = new List<int>();
            numbers.Add(1);
            numbers.AddRange(1, 2, 3);
            numbers.Clear();
            bool b2 = numbers.Contains(4);
            numbers.Insert(1, 10);
            numbers.InsertRange(2, 10, 3);
            numbers.RemoveAt(4);
            numbers.RemoveRange(4, 2);
            int[] newNumbers = items.GetRange(5, 2);
            int[] newNumbers2 = items.GetRange(5, arg);

            string[] words = new string[5];
            words[0] = "hello";
            words[1] = "world";
            bool b3 = words.Contains("hi");
            string[] newWords = words.GetRange(5, 2);
            string[] newWords2 = words.GetRange(5, arg);
        }
Example #27
0
        private static List<decimal> Test(List<decimal> testSetIpds, List<decimal> trainingIpds, int sampleSize)
        {
            List<decimal> results = new List<decimal>();

            while (testSetIpds.Count > 0)
            {
                List<decimal> sampleIpds;

                if (testSetIpds.Count > sampleSize)
                {
                    sampleIpds = testSetIpds.GetRange(0, sampleSize);
                    testSetIpds.RemoveRange(0, sampleSize);
                }
                else
                {
                    sampleIpds = testSetIpds.GetRange(0, testSetIpds.Count);
                    testSetIpds.Clear();
                }

                decimal result = CalculateKs(sampleIpds, trainingIpds);

                results.Add(result);
            }

            return results;
        }
        /// <summary>
        /// Apply selection to the specified population.
        /// </summary>
        /// 
        /// <param name="chromosomes">Population, which should be filtered.</param>
        /// <param name="size">The amount of chromosomes to keep.</param>
        /// 
        /// <remarks>Filters specified population keeping only specified amount of best
        /// chromosomes.</remarks>
        /// 
        public void ApplySelection( List<IChromosome> chromosomes, int size )
        {
            // sort chromosomes
            //chromosomes.Sort( );

            // current population size
            int elitesize = chromosomes.Count;

            // Sorting by fitness
            for (int i = elitesize - 1; i >= 1; i--)
            {
                for (int j = 0; j < i; j++)
                {
                    if (chromosomes[j].Fitness > chromosomes[j + 1].Fitness)
                    {
                        // faz a ordenacao
                        IChromosome aux = chromosomes[j];
                        chromosomes[j] = chromosomes[j + 1];
                        chromosomes[j + 1] = aux;
                    }
                }
            }

            // remove bad chromosomes
            chromosomes.RemoveRange( size, chromosomes.Count - size );
        }
Example #29
0
        public static string ReplacePathSegment(string path, string value, List<object> segments)
        {
            var segment = segments.SingleOrDefault(s => s.Equals(string.Format("?{0}=", value)) || s.Equals(string.Format("&{0}=", value)));
            if (segment != null)
            {
                var index = segments.IndexOf(segment);
                path = path.Replace(string.Format("{{{0}}}", value), string.Concat(segments[index + 1]));
                segments.RemoveRange(index, 2);

                // Replace missing ? if the segment was first in the series (after format)
                if(index == 1 && segments.Count > 1)
                {
                    var first = segments[index].ToString();
                    if(first.StartsWith("&"))
                    {
                        segments[index] = string.Concat("?", first.Substring(1));
                    }
                }
            }
            else
            {
                path = path.Replace(string.Format("/{{{0}}}", value), "");
            }
            return path;
        }
 public override void Visit(ParallelComposition node)
 {
     List<string> children = PopChildren();
     List<string> procChildren = new List<string>(children);
     procChildren.RemoveRange(0, 2);
     Return(CheckProc(Join(@" \mid\ ", procChildren), children));
 }