public static FishArbitratedBehaviour[][] GroupByPriorities(ArrayList behaviours)
    {
        // map priority -> behaviours
        Hashtable dict = new Hashtable();
        foreach(FishArbitratedBehaviour beh in behaviours){
            int priority = beh.priority;
            ArrayList list;
            if(!dict.ContainsKey(priority)){
                list = new ArrayList();
                dict[priority] = list;
            }else{
                list = (ArrayList)dict[priority];
            }
            list.Add(beh);
        }

        // arrange behaviour groups in execution order (highest priorities first)
        ArrayList priorities = new ArrayList(dict.Keys);
        FishArbitratedBehaviour[][] grouped = new FishArbitratedBehaviour[priorities.Count][];

        priorities.Sort();
        priorities.Reverse();
        for(int i = 0; i < priorities.Count; i++){
            int priority = (int)priorities[i];
            ArrayList group = (ArrayList)dict[priority];
            grouped[i] = (FishArbitratedBehaviour[])group.ToArray(typeof(FishArbitratedBehaviour));
        }

        return grouped;
    }
Example #2
0
    // Use this for initialization
    void Start()
    {
        ArrayList list = new ArrayList ();
        int score = PlayerPrefs.GetInt ("endScore");

        for (int i = 1; i<=10; i++) {
            key = "highScore" + i;
            keyscore = PlayerPrefs.GetInt(key);
            list.Add(keyscore);

            //PlayerPrefs.SetInt (key, 0);
        }

        lowestScore = PlayerPrefs.GetInt ("highScore10");
        Debug.Log ("lowest score" + lowestScore);

        if (score > lowestScore)
        {
            list.Add (score);
            list.Sort ();
            list.Reverse();
            list.RemoveAt(10);

            for (int i = 1; i<=10; i++) {
                key = "highScore" + i;
                PlayerPrefs.SetInt(key, (int)list[i-1]);
            }
        }
    }
Example #3
0
 //按条件对数组进行排序
 public static ArrayList SortingArrayList(ArrayList List)
 {
     if (List == null) return List;
     ArrayList NewList = null;
     List.Reverse();
     NewList = List;
     return NewList;
 }
Example #4
0
 private static ArrayList CalculatePath(Node node)
 {
     ArrayList list = new ArrayList();
     while (node != null) {
         list.Add(node);
         node = node.parent;
     }
     list.Reverse();
     return list;
 }
Example #5
0
 public ArrayList reconstructPath(Dictionary<GameObject, GameObject> cameFrom, GameObject current)
 {
     ArrayList totalPath = new ArrayList();
     totalPath.Add(current);
     while (cameFrom.ContainsKey(current)) {
         current = cameFrom[current];
         totalPath.Add(current);
     }
     totalPath.Reverse();
     return totalPath;
 }
 static void Main()
 {
     ArrayList ar = new ArrayList(10);
     ar.Add("이승만");
     ar.Add("박정희");
     ar.Add("최규하");
     ar.Add("전두환");
     ar.Add("노태우");
     ar.Add("김영삼");
     ar.Add("김대중");
     ar.Add("노무현");
     ar.Add("이명박");
     foreach (object o in ar) Console.Write(o + ",");
     ar.Sort();
     ar.Reverse();
     Console.WriteLine();
     foreach (object o in ar) Console.Write(o + ",");
 }
Example #7
0
    // Use this for initialization
    void Start()
    {
        //creates an array of an undetermined size and type
        ArrayList aList = new ArrayList();

        //create an array of all objects in the scene
        Object[] AllObjects = GameObject.FindObjectsOfType(typeof(Object)) as Object[];

        //iterate through all objects
        foreach (Object o in AllObjects)
        {
            if (o.GetType() == typeof(GameObject))
            {
                aList.Add(o);
            }
        }

        if (aList.Contains(SpecificObject))
        {
            Debug.Log(aList.IndexOf(SpecificObject));
        }

        if (aList.Contains(gameObject))
        {
            aList.Remove(gameObject);
        }

        //initialize the AllGameObjects array
        AllGameObjects = new GameObject[aList.Count];

        //copy the list to the array
        DistanceComparer dc = new DistanceComparer();
        dc.Target = gameObject;
        aList.Sort(dc);

        aList.CopyTo(AllGameObjects);
        ArrayList sorted = new ArrayList();
        sorted.AddRange(messyInts);
        sorted.Sort();
        sorted.Reverse();
        sorted.CopyTo(messyInts);
    }
Example #8
0
    public void CmdMoveUnitToTile( GameObject unit, GameObject src, GameObject dest)
    {
        Pathfinder finder = GameObject.Find ("GameMaster").GetComponent<Pathfinder>();
        Dictionary<HexTile, HexTile> thePath = finder.GetPathToTile( unit.GetComponent<Moveable>(),
                                                                     src.GetComponent<HexTile>(),
                                                                     dest.GetComponent<HexTile>());

        //		unit.transform.position = dest.transform.position + new Vector3( 32, 0, 0);

        Debug.Log( thePath.Count + " elements. " + thePath.ToString());

        //		foreach( KeyValuePair<HexTile, HexTile> tile in thePath)
        //		{
        //			Debug.Log( tile.Key.transform.position + " to " + tile.Value.transform.position);
        //		}

        HexTile theTile = dest.GetComponent<HexTile>();
        int j = 0;
        ArrayList pathOrder = new ArrayList() { theTile.gameObject};
        while (theTile != src.GetComponent<HexTile>())
        {
            theTile = thePath[ theTile];
            pathOrder.Add ( theTile.gameObject);
            Debug.Log( j++ + ": " + theTile);
        }

        pathOrder.Reverse ();

        src.GetComponent<HexTile>().occupants.Remove( unit);
        unit.GetComponent<Moveable>().occupying = src.GetComponent<HexTile>();
        unit.GetComponent<Moveable>().pathToTake = pathOrder;

        //		unit.GetComponent<Moveable>().occupying = dest.GetComponent<HexTile>();
        //		dest.GetComponent<HexTile>().occupants.Add( unit);
        //		unit.transform.position = dest.transform.position;

        RpcIssueMoveOrderToClients( unit, src, dest);
    }
 //
 // Object-graph support
 internal RigidBodyBase[] HitTestBodies(Point p)
 {
     ArrayList list = new ArrayList();
     foreach (RigidBodyBase body in Bodies)
     {
         if (body.HitTest(p))
             list.Add(body);
     }
     list.Reverse(); // Return in top-to-bottom order (more intuitive for UI).
     return list.ToArray(typeof(RigidBodyBase)) as RigidBodyBase[];
 }
Example #10
0
 public void setY(float y)
 {
     float old_y = y;
     float cur_y = transform.localPosition.y;
     move_y = new ArrayList();
     bool f = false;
     move_y.Add((float)(cur_y + y) / 2);
     while (!f)
     {
         if (Mathf.Abs((old_y - (float)move_y[move_y.Count - 1])) < 0.05f)
         {
             move_y.Add(y);
             f = true;
         }
         else
         {
             move_y.Insert(0, ((float)move_y[0] + cur_y) / 2);
             move_y.Add((y + (float)move_y[move_y.Count - 1]) / 2);
         }
     }
     move_y.Reverse();
 }
Example #11
0
		//Calculate the path until we find the end or an error occured or we have searched all nodes/the maxFrameTime was exceded
		public void Calc (bool multithreaded) {
			float startTime = Time.realtimeSinceStartup;
			
			start.script = this;
			start.parent = null;
			
			int counter = 0;
			//Continue to search while there hasn't ocurred an error and the end hasn't been found
			while (!foundEnd && !error) {
				counter++;
				//Debug.Log ("C0 "+counter);
				//Close the current node, if the current node is the target node then the path is finnished
				if (current==end) {
					foundEnd = true;
					break;
				}
				
				//Debug.Log ("C1 "+counter);
				
				if (current == null) {
					Debug.LogWarning ("Current is Null");
					return;
				}
				
				//@Performance Just for debug info
				closedNodes++;
				//Loop through all walkable neighbours of the node
				
				//Debug.Log ("C2 "+counter);
				//Debug.Log (current.neighbours.Length);
				
				current.Open (open, this, start, end, angleCost);
				/*for (int i=0;i<current.enabledConnections.Length;i++) {
					//Debug.DrawLine (current.vectorPos,current.neighbours[i].vectorPos,Color.red); //Uncomment for debug
					//We shouldn't test the start node
					
					if (current.enabledConnections[i].endNode != start) {
						Open (i);
					}
				}*/
				
				//Debug.Log ("C3 "+counter);
				
				//No nodes left to search?
				if (open.numberOfItems <= 1) {
					Debug.LogWarning ("No open points, whole area searched");
					error = true;
					return;
				}
				
				//Debug.Log ("C4 "+counter);
				
				//Select the node with the smallest F score and remove it from the open array
				current = open.Remove ();
				
				//Debug.Log ("C5 "+counter);
				
				//Have we exceded the maxFrameTime, if so we should wait one frame before continuing the search since we don't want the game to lag
				if (!multithreaded && (stepByStep || Time.realtimeSinceStartup-startTime>=maxFrameTime)) {//@Performance remove that step By Step thing in the IF, if you don't use in the seeker component
				
					t += Time.realtimeSinceStartup-startTime;
					frames++;
					
					//A class can't hold a coroutine, so a separate function need to handle the yield (StartPathYield)
					return;
				}
			
			}
			
			if (!error) {
				
				if (end == start) {
					path = new Node[2] {end,start};
				
				
					t += Time.realtimeSinceStartup-startTime;
					
					//@Performance Debug calls cost performance
					Debug.Log ("A* Pathfinding Completed Succesfully : End code 1\nTime: "+t+" Seconds\nFrames "+frames+"\nAverage Seconds/Frame "+(t/frames)+"\nPoints:"+path.Length+"\nSearched Nodes"+closedNodes+"\nPath Length (G score) Was "+end.g);
					
				} else if (AstarPath.active.simplify == Simplify.Simple) {
					if (active.gridGenerator != GridGenerator.Grid && active.gridGenerator != GridGenerator.Texture) {
						Debug.LogError ("Simplification can not be used with grid generators other than 'Texture' and 'Grid', excpect weird results");
					}
					Debug.LogWarning ("The Simple Simplification is broken");
					/*Node c = end;
					int p = 0;
					//Follow the parents of all nodes to the start point, but only add nodes if there is a change in direction
					int preDir = c.invParentDirection;
					ArrayList a = new ArrayList ();
					a.Add (c);
					while (c.parent != null) {
						
						if (c.parent.invParentDirection != preDir) {
							a.Add (c.parent);
							preDir = c.parent.invParentDirection;
						}
						
						c = c.parent;
						p++;
						
						if (c == start) {
							
							break;
						}
						
						if (p > 300) {
							Debug.LogError ("Preventing possible infinity loop");
							break;
						}
					}
					
					//Then reverse it so the start node gets the first place in the array
					a.Reverse ();
					
					path = a.ToArray (typeof (Node)) as Node[];
				
					t += Time.realtimeSinceStartup-startTime;
					
					//@Performance Debug calls cost performance
					Debug.Log ("A* Pathfinding Completed Succesfully : End code 2\nTime: "+t+" Seconds\nFrames "+frames+"\nAverage Seconds/Frame "+(t/frames)+"\nPoints:"+path.Length+" (simplified)"+"\nSearched Nodes"+closedNodes+"\nPath Length (G score) Was "+end.g);*/
					
				} else if (AstarPath.active.simplify == Simplify.Full) {
					if (active.gridGenerator != GridGenerator.Grid && active.gridGenerator != GridGenerator.Texture) {
						Debug.LogError ("Simplification can not be used with grid generators other than 'Texture' and 'Grid' excpect weird results");
					}
					
					Node c = end;
					ArrayList a = new ArrayList ();
					a.Add (c);
					int p = 0;
					
					//Follow the parents of all nodes to the start point
					while (c.parent != null) {
						a.Add (c.parent);
						
						c = c.parent;
						p++;
						if (c == start) {
							
							break;
						}
						
						//@Performance this IF is almost completely unnecessary
						//if (p > 300) {
						//	Debug.LogError ("Preventing possible infinity loop, remove this code if you have very long paths");
						//	break;
						//}
					}
					
					for (int i=2;i<a.Count;i++) {
						if (i >= a.Count) {
							break;
						}
						
						if (CheckLine ((Node)a[i],(Node)a[i-2],maxAngle)) {
							a.RemoveAt (i-1);
							i=2;
						}
					}
					//Then reverse it so the start node gets the first place in the array
					a.Reverse ();
					
					path = a.ToArray (typeof (Node)) as Node[];
				
				
					t += Time.realtimeSinceStartup-startTime;
					
					//@Performance Debug calls cost performance
					Debug.Log ("A* Pathfinding Completed Succesfully : End code 3\nTime: "+t+" Seconds\nFrames "+frames+"\nAverage Seconds/Frame "+(t/frames)+"\nPoints:"+path.Length+" (simplified)"+"\nSearched Nodes"+closedNodes+"\nPath Length (G score) Was "+end.g);
					
					//We have now found the end and filled the "path" array
					//The next update the Seeker script will find that this is done and send a message with the data
				}
				 else {
					Node c = end;
					ArrayList a = new ArrayList ();
					a.Add (c);
					int p = 0;
					
					//Follow the parents of all nodes to the start point
					while (c.parent != null) {
						a.Add (c.parent);
						
						c = c.parent;
						p++;
						if (c == start) {
							
							break;
						}
						
						//@Performance this IF is almost completely unnecessary
						if (p > 700) {
							Debug.LogError ("Preventing possible infinity loop, remove this code if you have very long paths (i.e more than 300 nodes)");
							break;
						}
					}
					//Then reverse it so the start node gets the first place in the array
					a.Reverse ();
					
					path = a.ToArray (typeof (Node)) as Node[];
				
				
					t += Time.realtimeSinceStartup-startTime;
					
					//@Performance Debug calls cost performance
					Debug.Log ("A* Pathfinding Completed Succesfully : End code 4\nTime: "+t+" Seconds\nFrames "+frames+"\nAverage Seconds/Frame "+(t/frames)+"\nPoints:"+path.Length+"\nSearched Nodes"+closedNodes+"\nPath Length (G score) Was "+end.g);
					
					//We have now found the end and filled the "path" array
					//The next frame the Seeker script will find that this is done and send a message with the path data
					
				}
			}
			
			//@Performance Remove the next lines if you don't use caching
			//These lines pushes the latest path on the cache array (the latest is always first) while keaping a constant length of the array
			for (int i=cache.Length-1;i > 0;i--) {
				cache[i] = cache[i-1];
			}
			cache[0] = this;
			
			//t += Time.realtimeSinceStartup-startTime;
			
			//(FindObjectOfType (typeof(Clicker)) as Clicker).NavigationMesh (path);
			//path = AstarProcess.PostProcess.NavigationMesh (path,active.meshNodePosition == MeshNodePosition.Edge);
		
		}
Example #12
0
 private ArrayList<string> GetPath(string url, out int numDomainParts, out int numTldParts, bool fullPath)
 {
     string leftPart;
     ArrayList<string> path;
     ArrayList<KeyDat<string, string>> queryParsed;
     UrlNormalizer.ParseUrl(url, out leftPart, out path, out queryParsed);
     string host = leftPart.Split(':')[1].Trim('/');
     string[] tldParts = UrlNormalizer.GetTldFromDomainName(host).Split('.');
     numTldParts = tldParts.Length;
     string[] hostParts = host.Split('.');
     numDomainParts = hostParts.Length;
     ArrayList<string> branch = new ArrayList<string>(hostParts);
     branch.Reverse();
     branch.AddRange(path);
     //Console.WriteLine(branch);
     if (!fullPath && path.Count > 0)
     {
         branch.RemoveAt(branch.Count - 1);
     }
     return branch;
 }
Example #13
0
        public override void Parse(Project project, string filename)
        {
            /* File header */
            Begin(filename + ".dsw");

            Match("Microsoft Developer Studio Workspace File, Format Version 6.00");
            Match("# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!");
            Match("");
            Match("###############################################################################");
            Match("");

            Hashtable dependencies = new Hashtable();

            string[] matches;
            while (!Match("Global:", true))
            {
                Package package = new Package();
                project.Package.Add(package);

                matches            = Regex("Project: \"(.+)\"=(.+) - Package Owner=<4>");
                package.Name       = matches[0];
                package.Path       = Path.GetDirectoryName(matches[1]);
                package.ScriptName = Path.GetFileName(matches[1]);
                package.Language   = "c++";
                Match("");

                Match("Package=<5>");
                Match("{{{");
                Match("}}}");
                Match("");
                Match("Package=<4>");
                Match("{{{");

                /* Get the package dependencies, cache until I have configs */
                ArrayList deps = new ArrayList();
                while (Match("    Begin Project Dependency", true))
                {
                    matches = Regex("    Project_Dep_Name (.+)");
                    deps.Add(matches[0]);
                    Match("    End Project Dependency");
                }
                dependencies[package] = (string[])deps.ToArray(typeof(string));

                Match("}}}");
                Match("");
                Match("###############################################################################");
                Match("");
            }

            Match("");
            Match("Package=<5>");
            Match("{{{");
            Match("}}}");
            Match("");
            Match("Package=<3>");
            Match("{{{");
            Match("}}}");
            Match("");
            Match("###############################################################################");
            Match("");

            foreach (Package package in project.Package)
            {
                filename = Path.Combine(Path.Combine(project.Path, package.Path), package.ScriptName);
                switch (package.Language)
                {
                case "c++":
                    ParseCpp(project, package, filename);
                    break;

                default:
                    throw new NotImplementedException("Loading of " + package.Language + " packages not implemented");
                }

                ArrayList temp = new ArrayList();
                foreach (Configuration config in package.Config)
                {
                    config.Dependencies = (string[])dependencies[package];
                    temp.Add(config);
                }

                /* VS6 stores configs in reverse order */
                temp.Reverse();
                for (int i = 0; i < package.Config.Count; ++i)
                {
                    package.Config[i] = (Configuration)temp[i];
                }
            }
        }
Example #14
0
			public bool AddToOpenObjects(string sfm, byte[] sfmData, int line)
			{
				// first check to see if it can be added to the current element
				if (m_current.AddSFM(sfm, sfmData, line, m_converter))
					return true;

				bool retVal = false;	// not added


				// search the tree of open objects and get a list of valid objects to recieve this 'sfm'
				// once it is correct - it can be optimized, but first get it working...
				//				if (m_current.CanAddSFM(sfm, m_converter))
				//				{
				//					// add the sfm and data to the ImportObject here
				//					// m_current.a
				//					return false;
				//				}
				//				if (m_current.CanAddSFMasAutoField(sfm, m_converter))
				//				{
				//					// add the sfm and data to the ImportObject here
				//					// m_current.a
				//					return false;
				//				}

				// can't add to current, so starting from the root - check the open items
				ImportObject start = m_root;
				ArrayList possibleObjects = new ArrayList();
				SearchChildrenForMatches(start, sfm, ref possibleObjects);

				if (possibleObjects.Count == 0)
				{
					// no matches for this sfm - now what ... open items possibly already contain this sfm
					if (!Current.AddSFMasAutoField(sfm, sfmData, line, m_converter))
					{
//						System.Diagnostics.Debug.WriteLine("******** hmmm ERROR??? ****************");
//						System.Diagnostics.Debug.WriteLine("Can't add <"+sfm+"> to open items, and not an auto field.");
//						System.Diagnostics.Debug.WriteLine("Possibly a case where the sfm is already used and a new one needs to be started.?");
					}

				}
				else if (possibleObjects.Count > 1)
				{
					// more than one match for this sfm - now what ...
					// check each one and see if it will go there
					possibleObjects.Reverse();
					// reversed the order of the items so that it is deepest first,
					// ex: a subentry would now be tested before the entry - needed for context
					foreach (ImportObject found in possibleObjects)
					{
						if (!found.AddSFM(sfm, sfmData, line, m_converter))
						{
							if (!found.AddSFMasAutoField(sfm, sfmData, line, m_converter))
							{
								continue;
							}
							else
							{
								retVal = true;
								break;
							}
						}
						else
						{
							retVal = true;
							break;
						}
					}
					if (!retVal)
						System.Diagnostics.Debug.WriteLine("******** ERROR??? ****************");
				}
				else
				{
					// only one place to add this one
					ImportObject found = possibleObjects[0] as ImportObject;
					if (!found.AddSFM(sfm, sfmData, line, m_converter))
					{
						if (!found.AddSFMasAutoField(sfm, sfmData, line, m_converter))
						{
							System.Diagnostics.Debug.WriteLine("******** ERROR??? ****************");
						}
						else
						{
							retVal = true;
						}
					}
					else
					{
						retVal = true;
					}
				}
				return retVal;
			}
Example #15
0
        public void TestArrayListWrappers()
        {
            //--------------------------------------------------------------------------
            // Variable definitions.
            //--------------------------------------------------------------------------
            ArrayList arrList = null;

            string[] strHeroes =
            {
                "Aquaman",
                "Atom",
                "Batman",
                "Black Canary",
                "Captain America",
                "Captain Atom",
                "Catwoman",
                "Cyborg",
                "Flash",
                "Green Arrow",
                "Green Lantern",
                "Hawkman",
                "Huntress",
                "Ironman",
                "Nightwing",
                "Robin",
                "SpiderMan",
                "Steel",
                "Superman",
                "Thor",
                "Wildcat",
                "Wonder Woman",
            };

            //
            // Construct array list.
            //
            arrList = new ArrayList((ICollection)strHeroes);

            //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of 
            //BinarySearch, Following variable cotains each one of these types of array lists

            ArrayList[] arrayListTypes = {
                                    (ArrayList)arrList.Clone(),
                                    (ArrayList)ArrayList.Adapter(arrList).Clone(),
                                    (ArrayList)ArrayList.FixedSize(arrList).Clone(),
                                    (ArrayList)arrList.GetRange(0, arrList.Count).Clone(),
                                    (ArrayList)ArrayList.Synchronized(arrList).Clone()};

            foreach (ArrayList arrayListType in arrayListTypes)
            {
                arrList = arrayListType;

                //
                // []  Reverse entire array list.
                //
                arrList.Reverse(0, arrList.Count);

                // Verify items have been reversed.
                for (int ii = 0; ii < arrList.Count; ++ii)
                {
                    Assert.Equal(0, strHeroes[ii].CompareTo((String)arrList[arrList.Count - ii - 1]));
                }

                //
                // []  Attempt invalid Reverse using negative index
                //
                //
                Assert.Throws<ArgumentOutOfRangeException>(() => arrList.Reverse(-100, arrList.Count));

                //
                //  []  Attempt Reverse using out of range index
                //
                Assert.Throws<ArgumentException>(() => arrList.Reverse(1000, arrList.Count));

                //
                //  []  Attempt Reverse using negative count.
                //
                Assert.Throws<ArgumentOutOfRangeException>(() => arrList.Reverse(0, -arrList.Count));

                //
                //  []  Attempt Reverse using zero count.
                //
                arrList.Reverse(0, 0);

                // Verify no reversal (List should still be reveresed of the original.)
                for (int ii = 0; ii < arrList.Count; ++ii)
                {
                    Assert.Equal(0, strHeroes[ii].CompareTo((string)arrList[arrList.Count - ii - 1]));
                }
            }
        }
Example #16
0
        /*
         * Generate a markov phrase
         */
        public void generateSentence(int sentences)
        {
            // Vector to hold the phrase
            ArrayList newPhrase = new ArrayList();

            // string for the next word
            string nextWord = "";

            // Select the first word
            ArrayList startWords    = markovChain["_start"];
            int       startWordsLen = startWords.Count;

            while (nextWord == null || nextWord.Length == 0)
            {
                nextWord = (string)startWords[rnd.Next(startWordsLen)];
            }
            newPhrase.Add(nextWord);
            ArrayList previousWords = new ArrayList(nextWord.Split(' ').ToArray());

            previousWords.Reverse();
            previousWords.Capacity = prefixSize;
            string prefix;

            // Keep looping through the words until all sentences are constructed
            for (int i = 0; i < sentences;)
            {
                previousWords = new ArrayList(previousWords.GetRange(0, prefixSize));
                StringBuilder prefixBuilder = new StringBuilder();
                for (int u = previousWords.Count - 1; u >= 0; u--)
                {
                    prefixBuilder.Append(previousWords[u]).Append(" ");
                }
                prefix = prefixBuilder.ToString().Trim();
                //Attempt to get value
                ArrayList wordSelection = null;
                markovChain.TryGetValue(prefix.ToLower(), out wordSelection);
                //Roll again if it can't
                if (wordSelection == null || wordSelection.Count == 0)
                {
                    //Keep rolling while it can't
                    while (nextWord == null || nextWord.Length == 0 ||
                           wordSelection == null || wordSelection.Count < 1)
                    {
                        nextWord = (string)startWords[rnd.Next(startWordsLen)];
                        //Try to get a value from the chain
                        markovChain.TryGetValue(nextWord.ToLower(), out wordSelection);
                    }
                    //Adds the new sentence beginning to the new phrase
                    newPhrase.Add(nextWord);
                    previousWords = new ArrayList(nextWord.Split(' ').ToArray());
                    previousWords.Reverse();
                    continue;
                }

                int wordSelectionLen = wordSelection.Count;
                nextWord = (string)wordSelection[rnd.Next(wordSelectionLen)];
                previousWords.Insert(0, nextWord);

                int Length = nextWord.Length;
                if (Length > 0)
                {
                    newPhrase.Add(nextWord);
                    if (nextWord[Length - 1] == '.')
                    {
                        i++;
                    }
                }
            }
            StringBuilder outputBuilder = new StringBuilder();

            for (int i = 0; i < newPhrase.Count; i++)
            {
                string word = (string)newPhrase[i];
                outputBuilder.Append(word).Append(" ");
            }
            Console.WriteLine(outputBuilder.ToString());
        }
Example #17
0
        static void Main(string[] args)
        {
            try
            {
                //ArrayList - список с элементами любого типа данных
                Console.WriteLine("ArrayList : ");
                ArrayList list = new ArrayList()
                {
                    1, 2, 3, 4, 6, "help", '+', 3, 99
                };


                Get get = new Get();
                get.GetList(list);
                list.Add(5);
                list.Add(5.7);
                list.Add(new string[] { "Hello", "World" });
                list.AddRange(new string[] { "Hello", "World" });
                get.GetList(list);
                list.RemoveRange(3, 2);
                list.RemoveAt(list.LastIndexOf(3));
                get.GetList(list);
                list.Reverse();
                get.GetList(list);
                list.Reverse();
                get.GetList(list);
                Console.WriteLine(value: $"\nКоличество элементов в списке равно {list.Count}");
                Console.WriteLine("\n-----------------------------------------------------\n");

                //List - список элементов с опередленным типом данных
                Console.WriteLine("List<T> : ");

                List <int> numlist = new List <int> {
                    1, 5, 9, 8, 2, 4, 2
                };
                numlist.Add(9999);
                numlist.AddRange(new int[] { 33, 55, 88 });
                get.GetList(numlist);
                numlist.RemoveAt(4);
                numlist.Remove(2);
                get.GetList(numlist);
                numlist.Reverse();
                get.GetList(numlist);
                Console.WriteLine(value: $"\nКоличество элементов в списке равно {numlist.Count}");
                Console.WriteLine();

                List <Person> personlist = new List <Person>(1);
                personlist.Add(new Person()
                {
                    Name = "Petya", Age = 9
                });
                personlist.Add(new Person()
                {
                    Name = "Vasya", Age = 42
                });
                personlist.Add(new Person()
                {
                    Name = "Tom", Age = 24
                });
                personlist.Add(new Person()
                {
                    Name = "Sam", Age = 95
                });
                personlist.Add(new Person()
                {
                    Name = "Katya", Age = 19
                });
                get.GetList(personlist);
                personlist.RemoveAt(3);
                get.GetList(personlist);
                Console.WriteLine(value: $"\nКоличество элементов в списке равно {personlist.Count}");


                Console.WriteLine("\n-----------------------------------------------------\n");
                //LinkedList - список хранящий ссылки на следующий и предыдущий элемент списка, а так же содержащий само значение элемента определенного типа данных
                Console.WriteLine("LinkedList<T> : ");

                LinkedList <int> listLink = new LinkedList <int>();
                listLink.AddLast(3);
                listLink.AddFirst(11);
                listLink.AddLast(22);
                listLink.AddAfter(listLink.FindLast(11), 5);
                listLink.AddLast(8);
                listLink.AddFirst(11);
                listLink.AddBefore(listLink.Find(11), 2);
                get.GetList(listLink);

                LinkedList <Person> listPerson = new LinkedList <Person>();
                listPerson.AddLast(new Person {
                    Name = "Alex", Age = 19
                });
                LinkedListNode <Person> sam = listPerson.AddBefore(listPerson.First, new Person {
                    Name = "Sam", Age = 21
                });                                                                                                         // создание объекта с ссылкой на Sam, предыдущий и следующий элемент
                listPerson.AddFirst(new Person {
                    Name = "Tom", Age = 19
                });
                listPerson.AddBefore(listPerson.Last, new Person {
                    Name = "Vasya", Age = 22
                });

                get.GetList(listPerson);
                Console.WriteLine(value: $"Имя : {sam.Next.Value.Name}. Возвраст : {sam.Next.Value.Age}");
                Console.WriteLine(value: $"Имя : {sam.Previous.Value.Name}. Возвраст : {sam.Previous.Value.Age}");


                Console.WriteLine(value: $"\n Количество элементов в списке : {listPerson.Count}");


                Console.WriteLine("\n-----------------------------------------------------\n");

                // Queue - очередь, работающая по принципу "Первый вошёл - первый вышел"
                Console.WriteLine("Queue<T> : ");

                Queue <int> numberQue = new Queue <int>();

                numberQue.Enqueue(99);
                numberQue.Enqueue(15);
                numberQue.Enqueue(1);
                numberQue.Enqueue(25);
                get.GetList(numberQue);
                int que = numberQue.Dequeue();
                Console.WriteLine("\n" + que);
                get.GetList(numberQue);
                que = numberQue.Peek();
                Console.WriteLine("\n" + que);
                get.GetList(numberQue);

                Console.WriteLine(value: $"\n Количество элементов в списке : {numberQue.Count}");

                Queue <Person> personQue = new Queue <Person>();
                personQue.Enqueue(new Person {
                    Name = "Tom", Age = 20
                });
                personQue.Enqueue(new Person {
                    Name = "Jerry", Age = 11
                });
                personQue.Enqueue(new Person {
                    Name = "Sam", Age = 40
                });
                get.GetList(personQue);
                var pers = personQue.Dequeue();
                Console.WriteLine("\n" + pers.Name + " " + pers.Age);
                get.GetList(personQue);
                pers = personQue.Peek();
                Console.WriteLine("\n" + pers.Name + " " + pers.Age);
                get.GetList(personQue);

                Console.WriteLine(value: $"Количесвто элементов в списке : {personQue.Count}");

                Console.WriteLine("\n-----------------------------------------------------\n");

                // Stack - коллекция ,которая работает по принципу "Последний вошёл - первый вышел"
                Console.WriteLine("Stack<T> : ");
                Stack <int> NumStack = new Stack <int>();
                NumStack.Push(5);
                NumStack.Push(11);
                NumStack.Push(999);
                get.GetList(NumStack);
                int num = NumStack.Pop();
                Console.WriteLine("\n" + num);
                get.GetList(NumStack);
                num = NumStack.Peek();
                Console.WriteLine("\n" + num);
                get.GetList(NumStack);

                Console.WriteLine(value: $"\nКоличество элементов в списке : {NumStack.Count}");

                Stack <Person> personStack = new Stack <Person>();
                personStack.Push(new Person {
                    Name = "Tom", Age = 33
                });
                personStack.Push(new Person {
                    Name = "Jerry", Age = 22
                });
                personStack.Push(new Person {
                    Name = "Petya", Age = 335
                });
                get.GetList(personStack);
                Person perss = personStack.Pop();
                Console.WriteLine("\n" + perss.Name + " " + perss.Age);
                get.GetList(personStack);

                Console.WriteLine("\n-----------------------------------------------------\n");
                //Dictionary - коллекция типа "Ключ - значение"
                Console.WriteLine("Dictionary<T,V> : ");
                Dictionary <string, int> personDict = new Dictionary <string, int>(3);

                personDict.Add("Tom", 56);
                personDict["Jerry"]  = 14;
                personDict["qweqwr"] = 0;
                get.GetList(personDict);
                personDict.Remove("qweqwr");
                get.GetList(personDict);

                Console.WriteLine(value: $"\n Количество элементов в коллекции : {personDict.Count}");

                Dictionary <string, string> countries = new Dictionary <string, string>(3)
                {
                    { "Россия", "Москва" },
                    { "Германия", "Берлин" },
                    { "Франция", "Париж" },
                };
                get.GetList(countries);

                Dictionary <string, string> countries2 = new Dictionary <string, string>
                {
                    ["Россия"]   = "Москва",
                    ["Германия"] = "Берлин",
                    ["Франция"]  = "Париж",
                };
                get.GetList(countries2);



                Console.WriteLine("\n-----------------------------------------------------\n");
                //ObservableCollection - коллекция, схожая с List, но может при изменении списка выполнять метод
                ObservableCollection <Person> people = new ObservableCollection <Person>
                {
                    new Person {
                        Name = "Tom", Age = 19
                    },
                    new Person {
                        Name = "Jerry", Age = 32
                    },
                    new Person {
                        Name = "Sam", Age = 129
                    }
                };
                people.CollectionChanged += Change.people_CollectionChange;
                get.GetList(people);
                people.Add(new Person {
                    Name = "Vasya", Age = 53
                });
                get.GetList(people);
                people.RemoveAt(3);
                get.GetList(people);
                people[0] = new Person {
                    Name = "Tom2", Age = 333
                };
                get.GetList(people);


                Console.WriteLine("\n-----------------------------------------------------\n");

                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(value: $"\n {ex.Message}");
                Console.ReadKey();
            }
        }
        /*
         * Detectar os ciclos dentro do grafo para transforma-los em objetos coloridos
         */
        internal String CreateShapes()
        {
            Shapes    shapes          = new Shapes();
            Shape     shape           = new Shape();
            ArrayList processedCurves = new ArrayList();

            Pixel lastPixel  = null;
            Pixel firstPixel = null;
            Color color;
            bool  hasCurve = true;

            foreach (Curve curve in curvesC)
            {
                Curve processingCurve = curve;
                color = processingCurve.color;
                if (!processedCurves.Contains(processingCurve))
                {
                    processedCurves.Add(processingCurve);
                    ArrayList curveArray = (ArrayList)processingCurve.curve;

                    firstPixel = getFirstPixel(curveArray);
                    lastPixel  = getLastPixel(curveArray);
                    shape.Add(curve);
                    if (!firstPixel.Equals(lastPixel)) // se primeiro e ultimo são iguais, então o circuito já esta fechado
                    {
                        hasCurve = true;
                        while (hasCurve)
                        {
                            foreach (Curve newCurve in curvesC)                                                            // verifico todas as curvas procurando uma que comece ou termine com o ultimo pixel da pesquisada
                            {
                                if ((newCurve.color == color && newCurve != curve && !processedCurves.Contains(newCurve))) // Precisa ser uma curva não processessada e com cor igual
                                {
                                    hasCurve = false;
                                    ArrayList newCurveArray = (ArrayList)newCurve.curve;
                                    TaggedUndirectedEdge <Pixel, EdgeTag> firstNewEdge = (TaggedUndirectedEdge <Pixel, EdgeTag>)newCurveArray[0];
                                    TaggedUndirectedEdge <Pixel, EdgeTag> lastNewEdge  = (TaggedUndirectedEdge <Pixel, EdgeTag>)newCurveArray[newCurveArray.Count - 1];

                                    if (firstNewEdge.Source.Equals(lastPixel) || firstNewEdge.Target.Equals(lastPixel) || lastNewEdge.Target.Equals(lastPixel) || lastNewEdge.Source.Equals(lastPixel)) // se a curva analizada possui o primeiro ou ultimo pixel igual a um pixel do lastEdge // simplificado apenas para conter um dos pixeis da ultima aresta da curva
                                    {
                                        if (firstNewEdge.Source.Equals(lastPixel) || firstNewEdge.Target.Equals(lastPixel))
                                        {
                                            if (newCurveArray.Count == 1)
                                            {
                                                if (((TaggedUndirectedEdge <Pixel, EdgeTag>)newCurveArray[0]).Source.Equals(lastPixel))
                                                {
                                                    lastPixel = ((TaggedUndirectedEdge <Pixel, EdgeTag>)newCurveArray[0]).Target;
                                                }
                                                else
                                                {
                                                    lastPixel = ((TaggedUndirectedEdge <Pixel, EdgeTag>)newCurveArray[0]).Source;
                                                }
                                            }
                                            else
                                            {
                                                lastPixel = getLastPixel(newCurveArray);
                                            }
                                        }
                                        else
                                        {
                                            if (newCurveArray.Count == 1)
                                            {
                                                if (((TaggedUndirectedEdge <Pixel, EdgeTag>)newCurveArray[0]).Source.Equals(lastPixel))
                                                {
                                                    lastPixel = ((TaggedUndirectedEdge <Pixel, EdgeTag>)newCurveArray[0]).Target;
                                                }
                                                else
                                                {
                                                    lastPixel = ((TaggedUndirectedEdge <Pixel, EdgeTag>)newCurveArray[0]).Source;
                                                }
                                            }
                                            else
                                            {
                                                lastPixel = getFirstPixel(newCurveArray);
                                                newCurveArray.Reverse();
                                            }
                                        }


                                        processedCurves.Add(newCurve);
                                        if (!lastPixel.Equals(firstPixel))
                                        {
                                            shape.Add(newCurve);
                                            hasCurve = true;
                                            break;
                                        }
                                        else // terminou o grupo de curvas
                                        {
                                            shape.Add(newCurve);
                                            shapes.Add(shape);
                                            hasCurve = false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        shapes.Add(shape);
                    }
                    shape = new Shape();
                }
            }

            //remove shapes iguais de cores diferentes
            ArrayList remove = new ArrayList();

            foreach (Shape shapeItem in shapes)
            {
                foreach (Shape shapeItem2 in shapes)
                {
                    if (!remove.Contains(shapeItem) && !remove.Contains(shapeItem2) && shapeItem.getColor() != Color.Beige && shapeItem2.getColor() != Color.Beige)
                    {
                        if (shapeItem.getColor() != shapeItem2.getColor() && shapeItem.isSameShape(shapeItem2))
                        {
                            Color c = new Color();
                            //localiza o pixel de cor dentro do poligono
                            foreach (Pixel v in g.Vertices)
                            {
                                if (v.pixelInsidePolygon(shapeItem.ToPoints()))
                                {
                                    c = v.color;
                                    break;
                                }
                            }

                            if (shapeItem.getColor() == c)
                            {
                                remove.Add(shapeItem2);
                                break;
                            }
                            else
                            if (shapeItem2.getColor() == c)
                            {
                                remove.Add(shapeItem);
                                break;
                            }
                        }
                    }
                }
            }


            foreach (Shape item in remove)
            {
                shapes.Remove(item);
            }

            //Ordena do objeto com maior area para os de menor area
            shapes.Sort();

            SvgVector svg = new SvgVector();

            svg.Height = Height * scale;
            svg.Width  = Width * scale;
            svg.scale  = 1;

            return(svg.NewImage(g, shapes, "NewImage.svg"));
        }
        //
        // Draw finance chart track line with legend
        //
        private void trackFinance(MultiChart m, int mouseX)
        {
            // Clear the current dynamic layer and get the DrawArea object to draw on it.
            DrawArea d = m.initDynamicLayer();

            // It is possible for a FinanceChart to be empty, so we need to check for it.
            if (m.getChartCount() == 0)
            {
                return;
            }

            // Get the data x-value that is nearest to the mouse
            int xValue = (int)(((XYChart)m.getChart(0)).getNearestXValue(mouseX));

            // Iterate the XY charts (main price chart and indicator charts) in the FinanceChart
            XYChart c = null;

            for (int i = 0; i < m.getChartCount(); ++i)
            {
                c = (XYChart)m.getChart(i);

                // Variables to hold the legend entries
                string    ohlcLegend    = "";
                ArrayList legendEntries = new ArrayList();

                // Iterate through all layers to find the highest data point
                for (int j = 0; j < c.getLayerCount(); ++j)
                {
                    Layer layer        = c.getLayerByZ(j);
                    int   xIndex       = layer.getXIndexOf(xValue);
                    int   dataSetCount = layer.getDataSetCount();

                    // In a FinanceChart, only layers showing OHLC data can have 4 data sets
                    if (dataSetCount == 4)
                    {
                        double highValue  = layer.getDataSet(0).getValue(xIndex);
                        double lowValue   = layer.getDataSet(1).getValue(xIndex);
                        double openValue  = layer.getDataSet(2).getValue(xIndex);
                        double closeValue = layer.getDataSet(3).getValue(xIndex);

                        if (closeValue != Chart.NoValue)
                        {
                            // Build the OHLC legend
                            ohlcLegend = "Open: " + c.formatValue(openValue, "{value|P4}") + ", High: " +
                                         c.formatValue(highValue, "{value|P4}") + ", Low: " + c.formatValue(lowValue,
                                                                                                            "{value|P4}") + ", Close: " + c.formatValue(closeValue, "{value|P4}");

                            // We also draw an upward or downward triangle for up and down days and the %
                            // change
                            double lastCloseValue = layer.getDataSet(3).getValue(xIndex - 1);
                            if (lastCloseValue != Chart.NoValue)
                            {
                                double change  = closeValue - lastCloseValue;
                                double percent = change * 100 / closeValue;
                                string symbol  = ((change >= 0) ?
                                                  "<*font,color=008800*><*img=@triangle,width=8,color=008800*>" :
                                                  "<*font,color=CC0000*><*img=@invertedtriangle,width=8,color=CC0000*>");

                                ohlcLegend = ohlcLegend + "  " + symbol + " " + c.formatValue(change,
                                                                                              "{value|P4}") + " (" + c.formatValue(percent, "{value|2}") + "%)<*/font*>"
                                ;
                            }

                            // Use a <*block*> to make sure the line does not wrap within the legend entry
                            ohlcLegend = "<*block*>" + ohlcLegend + "      <*/*>";
                        }
                    }
                    else
                    {
                        // Iterate through all the data sets in the layer
                        for (int k = 0; k < layer.getDataSetCount(); ++k)
                        {
                            ChartDirector.DataSet dataSet = layer.getDataSetByZ(k);

                            string name  = dataSet.getDataName();
                            double value = dataSet.getValue(xIndex);
                            if ((!string.IsNullOrEmpty(name)) && (value != Chart.NoValue))
                            {
                                // In a FinanceChart, the data set name consists of the indicator name and its
                                // latest value. It is like "Vol: 123M" or "RSI (14): 55.34". As we are
                                // generating the values dynamically, we need to extract the indictor name
                                // out, and also the volume unit (if any).

                                // The unit character, if any, is the last character and must not be a digit.
                                string unitChar = name.Substring(name.Length - 1);
                                if (unitChar.CompareTo("0") >= 0 && unitChar.CompareTo("9") <= 0)
                                {
                                    unitChar = "";
                                }

                                // The indicator name is the part of the name up to the colon character.
                                int delimiterPosition = name.IndexOf(":");
                                if (delimiterPosition != -1)
                                {
                                    name = name.Substring(0, delimiterPosition);
                                }

                                // In a FinanceChart, if there are two data sets, it must be representing a
                                // range.
                                if (dataSetCount == 2)
                                {
                                    // We show both values in the range in a single legend entry
                                    value = layer.getDataSet(0).getValue(xIndex);
                                    double value2 = layer.getDataSet(1).getValue(xIndex);
                                    name = name + ": " + c.formatValue(Math.Min(value, value2), "{value|P3}")
                                           + " - " + c.formatValue(Math.Max(value, value2), "{value|P3}");
                                }
                                else
                                {
                                    // In a FinanceChart, only the layer for volume bars has 3 data sets for
                                    // up/down/flat days
                                    if (dataSetCount == 3)
                                    {
                                        // The actual volume is the sum of the 3 data sets.
                                        value = layer.getDataSet(0).getValue(xIndex) + layer.getDataSet(1
                                                                                                        ).getValue(xIndex) + layer.getDataSet(2).getValue(xIndex);
                                    }

                                    // Create the legend entry
                                    name = name + ": " + c.formatValue(value, "{value|P3}") + unitChar;
                                }

                                // Build the legend entry, consist of a colored square box and the name (with
                                // the data value in it).
                                legendEntries.Add("<*block*><*img=@square,width=8,edgeColor=000000,color=" +
                                                  dataSet.getDataColor().ToString("x") + "*> " + name + "<*/*>");
                            }
                        }
                    }
                }

                // Get the plot area position relative to the entire FinanceChart
                PlotArea plotArea      = c.getPlotArea();
                int      plotAreaLeftX = plotArea.getLeftX() + c.getAbsOffsetX();
                int      plotAreaTopY  = plotArea.getTopY() + c.getAbsOffsetY();

                // The legend is formed by concatenating the legend entries.
                legendEntries.Reverse();
                string legendText = String.Join("      ", (string[])legendEntries.ToArray(typeof(string)));

                // Add the date and the ohlcLegend (if any) at the beginning of the legend
                legendText = "<*block,valign=top,maxWidth=" + (plotArea.getWidth() - 5) +
                             "*><*font=Arial Bold*>[" + c.xAxis().getFormattedLabel(xValue, "mmm dd, yyyy") +
                             "]<*/font*>      " + ohlcLegend + legendText;

                // Draw a vertical track line at the x-position
                d.vline(plotAreaTopY, plotAreaTopY + plotArea.getHeight(), c.getXCoor(xValue) +
                        c.getAbsOffsetX(), d.dashLineColor(0x000000, 0x0101));

                // Display the legend on the top of the plot area
                TTFText t = d.text(legendText, "Arial", 8);
                t.draw(plotAreaLeftX + 5, plotAreaTopY + 3, 0x000000, Chart.TopLeft);
            }
        }
Example #20
0
        static void Main(string[] args)
        {
            // Regions allow code to be, collapsable keeping code more organized.
            #region ArrayList Code
            // ArrayList are resizable arrays that can hold different data types
            // This section just goes over the various types of methods that can be used
            // in array lists

            ArrayList aList = new ArrayList();
            aList.Add("Bob");
            aList.Add(40);

            Console.WriteLine("Count: {0}", aList.Count);

            Console.WriteLine("Capacity: {0}", aList.Capacity);

            ArrayList aList2 = new ArrayList();

            aList2.AddRange(new object[] { "Mike", "Sally", "Egg" });

            aList2.Sort();
            aList2.Reverse();

            aList2.Insert(1, "Turkey");

            ArrayList range = aList2.GetRange(0, 2);

            foreach (object o in range)
            {
                Console.WriteLine(o);
            }

            Console.WriteLine("Turkey Index: {0}", aList2.IndexOf("Turkey", 0));

            string[] myArray = (string[])aList2.ToArray(typeof(string));

            string[] customers = { "Bob", "Sally", "Sue" };

            ArrayList custArrayList = new ArrayList();

            custArrayList.AddRange(customers);

            foreach (string s in custArrayList)
            {
                Console.WriteLine(s);
            }

            #endregion

            #region Dictionary Code
            // Dictionaries store key value pairs
            // Code demonstrates various methods used in dictionaries

            // must state what data type will bassociated with key and value
            Dictionary <string, string> superheroes = new Dictionary <string, string>();

            superheroes.Add("Clark Kent", "Superman");
            superheroes.Add("Bruce Wayne", "Batman");
            superheroes.Add("Barry West", "Flash");

            superheroes.Remove("Barry West");

            Console.WriteLine("Count : {0}", superheroes.Count);
            Console.WriteLine("Clark Kent : {0}", superheroes.ContainsKey("Clark Kent"));
            superheroes.TryGetValue("Clark Kent", out string test);

            Console.WriteLine($"Clark Kent : {test}");

            foreach (KeyValuePair <string, string> item in superheroes)
            {
                Console.WriteLine("{0} : {1}", item.Key, item.Value);
            }

            superheroes.Clear();

            #endregion

            #region QueueCode
            // Queues are a FIFO collection
            Queue queue = new Queue();
            queue.Enqueue(1);
            queue.Enqueue(2);
            queue.Enqueue(3);

            Console.WriteLine("1 in Queue : {0}", queue.Contains(1));
            Console.WriteLine("Remove head : {0}", queue.Dequeue());
            Console.WriteLine("Peek at head : {0}", queue.Peek());

            object[] numArray = queue.ToArray();

            Console.WriteLine(string.Join(", ", numArray));

            foreach (object o in queue)
            {
                Console.WriteLine($"Queue : {o}");
            }

            #endregion

            #region StackCode
            // Stacks are LIFO collection

            Stack stack = new Stack();

            stack.Push(1);
            stack.Push(2);
            stack.Push(3);

            Console.WriteLine("Peek at top of stack : {0}", stack.Peek());
            Console.WriteLine("Remove top of stack : {0}", stack.Pop());
            Console.WriteLine("Stack Contain 1 : {0}", stack.Contains(1));

            object[] numArray2 = stack.ToArray();

            Console.WriteLine(string.Join(", ", numArray2));

            foreach (object o in stack)
            {
                Console.WriteLine($"Stack : {o}");
            }

            stack.Clear();

            #endregion

            Console.ReadLine();
        }
Example #21
0
    private void Start()
    {
        {
            /*
             * Section 5.12 ArrayList
             */
            ArrayList arrayList    = new ArrayList();
            int[]     primeNumbers = new int[] { 1, 3, 5, 7, 11, 13, 17 };
            int       i            = 3;
            arrayList.Add(i);
            Debug.Log(arrayList[0]);
        }

        {
            /*
             * Section 5.12.1 A Basic Example
             */
            ArrayList arrayList  = new ArrayList();
            Object[]  allObjects = FindObjectsOfType(typeof(Object));
            foreach (Object o in allObjects)
            {
                Debug.Log(o);
                //arrayList.Add(o);
            }
            foreach (Object o in allObjects)
            {
                GameObject go = o as GameObject;
                if (go != null)
                {
                    arrayList.Add(go);
                }
            }

            //initialize GameObjects Array
            //GameObject[] gameObjects = new GameObject[arrayList.Count];

            /* don't use a type definition
             * if there's a use of the name
             * gameObjects defined as a public
             * GameObjects[] that will show
             * up in the Inspector panel.
             */
            gameObjects = new GameObject[arrayList.Count];
            // copy the list to the array
            arrayList.CopyTo(gameObjects);
            foreach (GameObject go in gameObjects)
            {
                Debug.Log(go.name);
            }

            /*
             * Section 5.12.2 ArrayList.Contains();
             */
            if (arrayList.Contains(specificObject))
            {
                Debug.Log("SpecificObject:");
                Debug.Log(specificObject);
                Debug.Log("is in arrayList at index ");
                Debug.Log(arrayList.IndexOf(specificObject));
            }

            /*
             * Section 5.12.3 Remove
             */
            if (arrayList.Contains(specificObject))
            {
                arrayList.Remove(specificObject);
                //now update the list in the inspector panel
                gameObjects = new GameObject[arrayList.Count];
                arrayList.CopyTo(gameObjects);
            }
        }
        {
            /*
             * Section 5.12.4 Sort and Reverse
             */

            ArrayList sorted = new ArrayList();
            sorted.AddRange(messyInts);
            sorted.Sort();
            sorted.CopyTo(messyInts);

            sorted.Reverse();
            sorted.CopyTo(messyInts);
        }
        {
            /*
             * Section 5.12.5 What We've Learned
             */
            ArrayList arrayList = new ArrayList();
            arrayList.Add(123);
            arrayList.Add("strings");
        }
    }
Example #22
0
 public void ReadConditions(MemoryStore rdfStore, Dictionary<string, Gazetteer> gazetteers)
 {
     ArrayList<string> crumbs = new ArrayList<string>(new string[] { mUri });
     Entity[] objects = rdfStore.SelectSubjects(P_IDENTIFIED_BY, new Entity(mUri));
     if (objects.Length > 0)
     {
         Resource[] objTypes = rdfStore.SelectObjects(objects[0].Uri, P_TYPE);
         if (objTypes.Length > 0)
         {
             crumbs.Add(objTypes[0].Uri);
             Resource[] superClass = rdfStore.SelectObjects((Entity)objTypes[0], P_SUBCLASS_OF);
             while (superClass.Length > 0)
             {
                 crumbs.Add(superClass[0].Uri);
                 superClass = rdfStore.SelectObjects((Entity)superClass[0], P_SUBCLASS_OF);
             }
         }
     }
     crumbs.Reverse();
     foreach (string uri in crumbs)
     {
         Resource[] conditionGazetteers = rdfStore.SelectObjects(uri, P_HAS_SENTENCE_LEVEL_CONDITION);
         foreach (Entity conditionGazetteer in conditionGazetteers)
         {
             mConditions.Add(new Condition(gazetteers[conditionGazetteer.Uri], Condition.Level.Sentence));
         }
         conditionGazetteers = rdfStore.SelectObjects(uri, P_HAS_BLOCK_LEVEL_CONDITION);
         foreach (Entity conditionGazetteer in conditionGazetteers)
         {
             mConditions.Add(new Condition(gazetteers[conditionGazetteer.Uri], Condition.Level.Block));
         }
         conditionGazetteers = rdfStore.SelectObjects(uri, P_HAS_DOCUMENT_LEVEL_CONDITION);
         foreach (Entity conditionGazetteer in conditionGazetteers)
         {
             mConditions.Add(new Condition(gazetteers[conditionGazetteer.Uri], Condition.Level.Document));
         }
     }
 }
Example #23
0
    // Use this for initialization
    void Start()
    {
        instance = this;
        print ("Initialize game");

        graph = GetComponent<CityGraph> ();

        powerplantShop = GameObject.FindObjectOfType<PowerPlantShop> ();

        //setup players
        players = new ArrayList();

        playerOrderPieces = new ArrayList ();

        playerOrderPieces.Add (GameObject.Find("PlayerOrderPiece1"));
        playerOrderPieces.Add (GameObject.Find("PlayerOrderPiece2"));
        playerOrderPieces.Add (GameObject.Find("PlayerOrderPiece3"));
        playerOrderPieces.Add (GameObject.Find("PlayerOrderPiece4"));

        //create objects from GUI setup
        Player[] p = FindObjectsOfType(typeof(Player)) as Player[];
        for (int i = 0; i < p.Length; i++) {
            players.Add (p [i]);
            ((GameObject)playerOrderPieces[i]).GetComponent<Renderer>().material.color = p[i].color;
        }

        players.Sort ();
        players.Reverse ();

        //create material store
        materialStore = new PowerPlantMaterialStore ();

        InitializePayoutTable ();
        //		InitializePowerPlants ();
        //		DealCards ();
        //
        //		ShufflePowerPlantCards ();
    }
Example #24
0
        public void TestArrayListWrappers()
        {
            //--------------------------------------------------------------------------
            // Variable definitions.
            //--------------------------------------------------------------------------
            ArrayList arrList = null;

            string[] strHeroes =
            {
                "Aquaman",
                "Atom",
                "Batman",
                "Black Canary",
                "Captain America",
                "Captain Atom",
                "Catwoman",
                "Cyborg",
                "Flash",
                "Green Arrow",
                "Green Lantern",
                "Hawkman",
                "Huntress",
                "Ironman",
                "Nightwing",
                "Robin",
                "SpiderMan",
                "Steel",
                "Superman",
                "Thor",
                "Wildcat",
                "Wonder Woman",
            };

            //
            // Construct array list.
            //
            arrList = new ArrayList((ICollection)strHeroes);

            //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of
            //BinarySearch, Following variable cotains each one of these types of array lists

            ArrayList[] arrayListTypes =
            {
                (ArrayList)arrList.Clone(),
                (ArrayList)ArrayList.Adapter(arrList).Clone(),
                (ArrayList)ArrayList.FixedSize(arrList).Clone(),
                (ArrayList)arrList.GetRange(0,                  arrList.Count).Clone(),
                (ArrayList)ArrayList.Synchronized(arrList).Clone()
            };

            foreach (ArrayList arrayListType in arrayListTypes)
            {
                arrList = arrayListType;

                //
                // []  Reverse entire array list.
                //
                arrList.Reverse(0, arrList.Count);

                // Verify items have been reversed.
                for (int ii = 0; ii < arrList.Count; ++ii)
                {
                    Assert.Equal(0, strHeroes[ii].CompareTo((String)arrList[arrList.Count - ii - 1]));
                }

                //
                // []  Attempt invalid Reverse using negative index
                //
                //
                Assert.Throws <ArgumentOutOfRangeException>(() => arrList.Reverse(-100, arrList.Count));

                //
                //  []  Attempt Reverse using out of range index
                //
                Assert.Throws <ArgumentException>(() => arrList.Reverse(1000, arrList.Count));

                //
                //  []  Attempt Reverse using negative count.
                //
                Assert.Throws <ArgumentOutOfRangeException>(() => arrList.Reverse(0, -arrList.Count));

                //
                //  []  Attempt Reverse using zero count.
                //
                arrList.Reverse(0, 0);

                // Verify no reversal (List should still be reveresed of the original.)
                for (int ii = 0; ii < arrList.Count; ++ii)
                {
                    Assert.Equal(0, strHeroes[ii].CompareTo((string)arrList[arrList.Count - ii - 1]));
                }
            }
        }
Example #25
0
        /// <summary>
        /// Calculates the top, non-grabStack position.
        /// </summary>
        /// <returns></returns>
        private float GetTopPosition()
        {
            float topPosition = 0;
            ArrayList<Block> blocks = new ArrayList<Block>();
            blocks.AddAll(currentStack);
            blocks.Reverse();

            foreach (Block block in blocks)
            {
                // See if we are moving or if we have no height
                if (block.IsMoving || block.Height == 0)
                    continue;

                // Grab this one
                topPosition = block.TopPosition;
                break;
            }
            return topPosition;
        }
Example #26
0
        public void Test02()
        {
            //--------------------------------------------------------------------------
            // Variable definitions.
            //--------------------------------------------------------------------------
            ArrayList arrList = null;

            string[] strHeroes =
            {
                "Aquaman",
                "Atom",
                "Batman",
                "Black Canary",
                "Captain America",
                "Captain Atom",
                "Catwoman",
                "Cyborg",
                "Flash",
                "Green Arrow",
                "Green Lantern",
                "Hawkman",
                "Huntress",
                "Ironman",
                "Nightwing",
                "Robin",
                "SpiderMan",
                "Steel",
                "Superman",
                "Thor",
                "Wildcat",
                "Wonder Woman",
            };

            //
            // Construct array list.
            //
            arrList = new ArrayList((ICollection)strHeroes);

            //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of
            //BinarySearch, Following variable cotains each one of these types of array lists

            ArrayList[] arrayListTypes =
            {
                (ArrayList)arrList.Clone(),
                (ArrayList)ArrayList.Adapter(arrList).Clone(),
                (ArrayList)ArrayList.FixedSize(arrList).Clone(),
                (ArrayList)arrList.GetRange(0,                  arrList.Count).Clone(),
                (ArrayList)ArrayList.Synchronized(arrList).Clone()
            };

            foreach (ArrayList arrayListType in arrayListTypes)
            {
                arrList = arrayListType;

                //
                // []  Reverse entire array list.
                //
                // Reverse entire array list.
                arrList.Reverse();

                // Verify items have been reversed.
                for (int ii = 0; ii < arrList.Count; ++ii)
                {
                    Assert.Equal(0, strHeroes[ii].CompareTo((String)arrList[arrList.Count - ii - 1]));
                }

                //[]Team review feedback - Reversing lists of varying sizes inclusing 0
                arrList = new ArrayList();
                arrList.Reverse();

                arrList = new ArrayList();
                for (int i = 0; i < 1; i++)
                {
                    arrList.Add(i);
                }

                arrList.Reverse();
            }
        }
    /// <summary>
    /// Ensures the given node within the tree.
    /// </summary>
    /// <param name="node">Node to ensure</param>
    /// <param name="nodeId">Ensure by NodeID</param>
    protected void EnsureNode(TreeNode node, int nodeId)
    {
        if (node == null)
        {
            // If not already exists, do not add
            if (allNodes[nodeId] != null)
            {
                return;
            }
            else
            {
                // Get the node
                node = TreeProvider.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES, true);

                if (!SelectPublishedData)
                {
                    node = DocumentHelper.GetDocument(node, TreeProvider);
                }
            }
        }
        else
        {
            nodeId = node.NodeID;
        }

        if (node != null)
        {
            // Get the correct parent node
            System.Web.UI.WebControls.TreeNode parentNode = (System.Web.UI.WebControls.TreeNode)allNodes[node.NodeParentID];
            if (parentNode != null)
            {
                // Expand the parent
                parentNode.Expanded = true;

                // If still not present, add the node
                if (allNodes[nodeId] == null)
                {
                    TreeSiteMapNode sourceNode = new TreeSiteMapNode(MapProvider, nodeId.ToString());
                    sourceNode.TreeNode = node;

                    System.Web.UI.WebControls.TreeNode newNode = CreateNode(sourceNode, 0, true);

                    parentNode.ChildNodes.Add(newNode);
                }
            }
            else
            {
                // Get the correct node and add it to list of processed nodes
                TreeSiteMapNode targetNode = MapProvider.GetNodeByAliasPath(node.NodeAliasPath);

                if (targetNode != null)
                {
                    ArrayList procNodes = new ArrayList();
                    procNodes.Add(targetNode.NodeData["NodeID"]);

                    if (targetNode.ParentNode != null)
                    {
                        // Repeat until existing parent node in allNodes is found
                        do
                        {

                            int targetParentNodeId = (int)((TreeSiteMapNode)targetNode.ParentNode).NodeData["NodeID"];
                            procNodes.Add(targetParentNodeId);
                            targetNode = (TreeSiteMapNode)targetNode.ParentNode;

                        } while ((targetNode.ParentNode != null) && (allNodes[(int)(((TreeSiteMapNode)(targetNode.ParentNode)).NodeData["NodeID"])] == null));
                    }

                    // Process nodes in reverse order
                    procNodes.Reverse();
                    foreach (int nodeID in procNodes)
                    {
                        EnsureNode(null, nodeID);
                    }
                }
            }
        }

        return;
    }
Example #28
0
        static void Main(string[] args)
        {
            ArrayList a = new ArrayList();

            a.Add(12);
            a.Add(32);
            a.Add(21);
            a.Add(45);
            a.Sort();
            Console.WriteLine(a.Capacity);
            Console.WriteLine(a.BinarySearch(32));
            Console.WriteLine(a.SyncRoot);
            object[] o = a.ToArray();
            foreach (object i in o)
            {
                Console.WriteLine(i);
            }
            foreach (object i in a)
            {
                Console.WriteLine(i);
            }

            Array v = a.ToArray();

            foreach (object i in v)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine(a.Count);

            Console.WriteLine(a.Contains(21));
            //elements

            foreach (int i in a.GetRange(0, 3))
            {
                Console.WriteLine(i);
            }

            IEnumerator aa  = a.GetEnumerator();
            IEnumerator aaa = a.GetEnumerator(0, 2);

            Console.WriteLine(aaa.MoveNext());
            Console.WriteLine(aaa.Current);
            Console.WriteLine(aa.MoveNext());
            Console.WriteLine(aa.Equals(aaa));

            Console.WriteLine(a.IndexOf(21));
            a.Insert(1, 10);
            a.Reverse();
            foreach (object i in a)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine(a.IsFixedSize);
            Console.WriteLine(a.LastIndexOf(45));
            a.Remove(45);
            foreach (object i in a)
            {
                Console.WriteLine(i);
            }



            //sortedList in generic

            Console.WriteLine("sortedList in generic mode");


            SortedList <int, string> s = new SortedList <int, string>();

            s.Add(1, "veera");
            s.Add(2, "madhu");
            s.Add(0, "veerababu");
            foreach (int i in s.Keys)
            {
                Console.WriteLine(s[i]);
            }

            foreach (string i in s.Values)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine(s.Count);
            s.RemoveAt(0);
            foreach (string i in s.Values)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine(s.ContainsValue("madhu"));
            Console.WriteLine(s.ContainsKey(1));
            Console.WriteLine(s.ContainsKey(4));
            Console.WriteLine(s.IndexOfValue("veerab"));


            //sortedLIst in Non-generic mode

            Console.WriteLine("sortedList in Non-generic mode");
            SortedList ss = new SortedList();


            //sorted table automatically sorted based on keys.
            ss.Add(1, "veera");
            ss.Add(2, "srinu");
            ss.Add(0, "sai");
            foreach (object i in ss.Keys)
            {
                Console.WriteLine(i);
            }
            foreach (object i in ss.Values)
            {
                Console.WriteLine(i);
            }
            object m = ss.Clone();

            Console.WriteLine(m);
        }
    private static void GoalPathI(ArrayList goalpath,
		DBNode node, DBNode goal, Stack path)
    {
        //Console.WriteLine ("GoalPathI");
        if (node == null)
            return;

        if (node == goal) {
            foreach (DBNode pNode in path)
                goalpath.Add (pNode);

            goalpath.Reverse ();
            goalpath.Add (node);

            return;
        }

        foreach (DBNode child in node.Children) {
            path.Push (node);
            GoalPathI (goalpath, child, goal, path);
            path.Pop ();
        }
    }
Example #30
0
        /// <summary>
        /// ArrayList 的例子.
        /// </summary>
        public void ArrayListSample()
        {
            Console.WriteLine("****ArrayList : 使用大小可按需动态增加的数组");

            // 初始化.
            ArrayList dataList = new ArrayList();

            Console.WriteLine("***加入测试数据. 100/300/200/400 ");
            dataList.Add(100);
            dataList.Add(300);
            dataList.Add(200);
            dataList.Add(400);


            Console.WriteLine("***数据个数={0}", dataList.Count);

            Console.WriteLine("***测试 遍历数据:");
            foreach (int val in dataList)
            {
                Console.WriteLine(val);
            }

            Console.WriteLine("***测试 索引器:");
            for (int i = 0; i < dataList.Count; i++)
            {
                Console.WriteLine("索引为{0} 数据为{1}", i, dataList[i]);
            }

            Console.WriteLine("***测试 IndexOf :");
            int index = dataList.IndexOf(200);

            Console.WriteLine("200 所在的位置在:{0}", index);

            Console.WriteLine("***测试 IndexOf 从1开始找:");
            index = dataList.IndexOf(200, 1);
            Console.WriteLine("200 所在的位置在:{0}", index);

            Console.WriteLine("***测试 IndexOf 从3开始找:");
            index = dataList.IndexOf(200, 3);
            Console.WriteLine("200 所在的位置在:{0}", index);

            Console.WriteLine("***测试 IndexOf 从1和3之间找:");
            index = dataList.IndexOf(200, 1, 3);
            Console.WriteLine("200 所在的位置在:{0}", index);


            Console.WriteLine("***测试 未排序的 BinarySearch :");
            index = dataList.BinarySearch(200);
            Console.WriteLine("200 所在的位置在:{0}", index);

            Console.WriteLine("***测试 已排序的 BinarySearch :");
            dataList.Sort();
            index = dataList.BinarySearch(200);
            Console.WriteLine("200 所在的位置在:{0}", index);

            // 说明:
            // 如果找不到的话:
            // IndexOf  需要遍历整个 ArrayList
            // BinarySearch 则不需要。
            // 但是 BinarySearch 执行前,需要对 ArrayList 进行排序
            // 假如数据量不大,且检索的次数很少,可以直接用 IndexOf


            Console.WriteLine("***测试 对已排序的 进行反转 :");
            dataList.Reverse();
            foreach (int val in dataList)
            {
                Console.WriteLine(val);
            }


            // 方法结束.
            Console.WriteLine();
        }
Example #31
0
 public virtual bool runTest()
 {
     int iCountErrors = 0;
     int iCountTestcases = 0;
     Console.Error.WriteLine( strName + ": " + strTest + " runTest started..." );
     ArrayList arrList = null;
     String [] strHeroes =
         {
             "Aquaman",
             "Atom",
             "Batman",
             "Black Canary",
             "Captain America",
             "Captain Atom",
             "Catwoman",
             "Cyborg",
             "Flash",
             "Green Arrow",
             "Green Lantern",
             "Hawkman",
             "Huntress",
             "Ironman",
             "Nightwing",
             "Robin",
             "SpiderMan",
             "Steel",
             "Superman",
             "Thor",
             "Wildcat",
             "Wonder Woman",
     };
     do
     {
         ++iCountTestcases;
         Console.Error.WriteLine( "[]  Construct ArrayList" );
         try
         {
             arrList = new ArrayList( (ICollection) strHeroes );
             if ( arrList == null )
             {
                 Console.WriteLine( strTest+ "E_101: Failed to construct new ArrayList1" );
                 ++iCountErrors;
                 break;
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine( strTest+ "E_10001: Unexpected Exception: " + ex.ToString() );
             ++iCountErrors;
             break;
         }
         ++iCountTestcases;
         Console.Error.WriteLine( "[]  Reverse entire array list" );
         try
         {
             arrList.Reverse( 0, arrList.Count );
             for ( int ii = 0; ii < arrList.Count; ++ii )
             {
                 if ( strHeroes[ii].CompareTo( (String)arrList[arrList.Count-ii-1] ) != 0 )
                 {
                     String strInfo = strTest + " error: ";
                     strInfo = strInfo + "Expected hero <"+ strHeroes[ii] + "> ";
                     strInfo = strInfo + "Returned hero <"+ (String)arrList[ii+arrList.Count-1] + "> ";
                     Console.WriteLine( strTest+ "E_202: " + strInfo );
                     ++iCountErrors;
                     break;
                 }
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine( strTest+ "E_10002: Unexpected Exception: " + ex.ToString() );
             ++iCountErrors;
             break;
         }
         ++iCountTestcases;
         Console.Error.WriteLine( "[]  Attempt bogus Reverse using negative index" );
         try
         {
             arrList.Reverse( -100, arrList.Count );
             Console.WriteLine( strTest+ "E_303: Expected ArgumentException" );
             ++iCountErrors;
             break;
         }
         catch (ArgumentException ex)
         {
         }
         catch (Exception ex)
         {
             Console.WriteLine( strTest+ "E_10003: Unexpected Exception: " + ex.ToString() );
             ++iCountErrors;
             break;
         }
         ++iCountTestcases;
         Console.Error.WriteLine( "[]  Attempt Reverse using out of range index" );
         try
         {
             arrList.Reverse( 1000, arrList.Count );
             Console.WriteLine( strTest+ "E_404: Expected ArgumentException" );
             ++iCountErrors;
             break;
         }
         catch (ArgumentException ex)
         {
         }
         catch (Exception ex)
         {
             Console.WriteLine( strTest+ "E_10004: Unexpected Exception: " + ex.ToString() );
             ++iCountErrors;
             break;
         }
         ++iCountTestcases;
         Console.Error.WriteLine( "[]  Attempt Reverse using negative count" );
         try
         {
             arrList.Reverse( 0, -arrList.Count );
             Console.WriteLine( strTest+ "E_505: Expected ArgumentException" );
             ++iCountErrors;
             break;
         }
         catch (ArgumentException ex)
         {
         }
         catch (Exception ex)
         {
             Console.WriteLine( strTest+ "E_10005: Unexpected Exception: " + ex.ToString() );
             ++iCountErrors;
             break;
         }
         ++iCountTestcases;
         Console.Error.WriteLine( "[]  Attempt Reverse using zero count" );
         try
         {
             arrList.Reverse( 0, 0 );
             for ( int ii = 0; ii < arrList.Count; ++ii )
             {
                 if ( strHeroes[ii].CompareTo( (String)arrList[arrList.Count-ii-1] ) != 0 )
                 {
                     String strInfo = strTest + " error: ";
                     strInfo = strInfo + "Expected hero <"+ strHeroes[ii] + "> ";
                     strInfo = strInfo + "Returned hero <"+ (String)arrList[ii+arrList.Count-1] + "> ";
                     Console.WriteLine( strTest+ "E_202: " + strInfo );
                     ++iCountErrors;
                     break;
                 }
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine( strTest+ "E_10005: Unexpected Exception: " + ex.ToString() );
             ++iCountErrors;
             break;
         }
     }
     while ( false );
     Console.Error.Write( strName );
     Console.Error.Write( ": " );
     if ( iCountErrors == 0 )
     {
         Console.Error.WriteLine( strTest + " iCountTestcases==" + iCountTestcases + " paSs" );
         return true;
     }
     else
     {
         System.String strFailMsg = null;
         Console.WriteLine( strTest+ strPath );
         Console.WriteLine( strTest+ "FAiL" );
         Console.Error.WriteLine( strTest + " iCountErrors==" + iCountErrors );
         return false;
     }
 }
        public override string Ejecutar(Entorno entorno)
        {
            System.Diagnostics.Debug.WriteLine("Ejecucion MIN select-ORDER_BYE");
            System.Diagnostics.Debug.WriteLine("Ejecucion select-ORDER_BYE");
            System.Diagnostics.Debug.WriteLine("Ejecucion select-where");
            String Tabla = this.Hijos[0].Nombre;
            String BD    = entorno.Tabla();

            entorno.Devolver2();
            System.Diagnostics.Debug.WriteLine("Ejecucion select-ORDER_BYE tabla->" + Tabla);
            System.Diagnostics.Debug.WriteLine("Ejecucion select-ORDER_BYE bd->" + BD);
            entorno.AgregarADiccionario(Tabla, BD);


            List <Simbolo> Campos = new List <Simbolo>();

            Campos = entorno.TablaBD(Tabla, BD);
            if (this.ListaID1.Count == 1 && this.ListaID1[0] == "* (Key symbol)")
            {
                //entorno.MostrarUTablas2(Tabla, BD);
                //entorno.MostrarCampos2(Tabla, BD);
                //return "SELECT SIMPLE";
            }
            else
            {
                for (int i = 0; i < this.ListaID1.Count; i++)
                {
                    Boolean Existencia = false;
                    for (int x = 0; x < Campos.Count; x++)
                    {
                        //System.Diagnostics.Debug.WriteLine(this.ListaID1[i].Replace(" (id)", "") + "->" + Campos[x].ObtenerId());
                        if (this.ListaID1[i].Replace(" (id)", "") == Campos[x].ObtenerId())
                        {
                            Existencia = true;
                        }
                    }
                    if (Existencia == false)
                    {
                        return("#ERROR PARAMETRO SELEC NO EXISTE");
                    }
                }
            }
            for (int i = 0; i < this.ListaR1.Count; i++)
            {
                string[] separadas;
                separadas = this.ListaR1[i].Split(',');
                Boolean Existencia = false;
                for (int x = 0; x < Campos.Count; x++)
                {
                    //System.Diagnostics.Debug.WriteLine(this.ListaR1[i].Replace(" (id)", "") + "->" + Campos[x].ObtenerId());
                    if (separadas[0] == Campos[x].ObtenerId())
                    {
                        Existencia = true;
                    }
                }
                if (Existencia == false)
                {
                    return("#ERROR PARAMETRO order by NO EXISTE");
                }
            }
            entorno.MostrarDiccionario();
            Dictionary <String, Simbolo> ResultadoOrdenar = new Dictionary <String, Simbolo>();
            Dictionary <String, String>  OrdenarrDiccionario;

            for (int i = 0; i < this.ListaR1.Count; i++)
            {
                entorno.Devolver2();
                System.Diagnostics.Debug.WriteLine("Ejecucion select-ORDER_BYE Campo a ordenarr->" + i + "->" + this.ListaR1[i]);
                List <String> Auxiliar = new List <String>();
                string[]      separadas;
                separadas           = this.ListaR1[i].Split(',');
                OrdenarrDiccionario = entorno.OrdenarrDiccionario(separadas[0]);

                ArrayList aKeys = new ArrayList((OrdenarrDiccionario.Values));
                aKeys.Sort();
                if (separadas[1].ToUpper().Contains("DESC"))
                {
                    aKeys.Reverse();
                }
                for (int j = 0; j < OrdenarrDiccionario.Count; j++)
                {
                }


                for (int j = 0; j < OrdenarrDiccionario.Count; j++)
                {
                    //System.Diagnostics.Debug.WriteLine("Ejecucion select-ORDER_BYE HASH ->" + aKeys[j]);

                    foreach (KeyValuePair <String, String> kvp in OrdenarrDiccionario)
                    {
                        if (kvp.Value == aKeys[j].ToString())
                        {
                            if (Auxiliar.Contains(kvp.Key) == false)
                            {
                                System.Diagnostics.Debug.WriteLine("Ejecucion select-ORDER_BYE HASH ->" + aKeys[j] + "->" + kvp.Key.ToString());
                                Auxiliar.Add(kvp.Key);
                                entorno.OrdenarDiccionarioFinal(kvp.Key.ToString());
                            }
                        }
                    }
                }

                //entorno.IgualarDic();
                entorno.MostrarDiccionario2x();

                entorno.LImpiar2();
            }

            if (this.ListaID1.Count == 1 && this.ListaID1[0] == "* (Key symbol)")
            {
                entorno.MostrarDiccionario2();
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("\n\n\n\nDICCIONARIO-Tabla->\n\n");
                String Cadena = "";
                for (int x = 0; x < this.ListaID1.Count; x++)
                {
                    Cadena = Cadena + this.ListaID1[x].Replace(" (id)", "") + "             |  ";
                }
                System.Diagnostics.Debug.WriteLine(Cadena);
                entorno.MostrarDiccionario2(this.ListaID1);
            }
            List <String> Listax = entorno.MostrarDiccionario2x(this.ListaID1);

            if (this.AutoIncrmentable2 == 2)
            {
                Listax.Reverse();
                return(Listax[0]);
            }
            if (this.AutoIncrmentable2 == 3)
            {
                int total = 0;
                for (int i = 0; i < Listax.Count; i++)
                {
                    total = total + Int32.Parse(Listax[i]);
                }

                return(total.ToString());
            }
            if (this.AutoIncrmentable2 == 4)
            {
                int total = 0;
                for (int i = 0; i < Listax.Count; i++)
                {
                    total = total + Int32.Parse(Listax[i]);
                }

                return((total / Listax.Count).ToString());
            }
            return(Listax[0]);
            //entorno.MostrarDiccionario2();



            //return "12";
        }
Example #33
0
        //function which contains the algorithm steps
        private string NaiveBayes(string[] values)
        {
            ArrayList s = new ArrayList();

            output.Clear();

            //try
            //{
            s = GetSubject();

            int    m     = 7;
            double numer = 1.0;
            double dino  = double.Parse(s.Count.ToString());
            double p     = numer / dino;

            string[] features = { "fm",      "battery", "color", "camera", "ram",
                                  "storage", "dualsim" };

            for (int i = 0; i < s.Count; i++)
            {
                mul.Clear();

                for (int j = 0; j < features.Length; j++)
                {
                    n  = 0;
                    nc = 0;

                    for (int d = 0; d < dt.Rows.Count; d++)
                    {
                        if (dt.Rows[d][j].ToString().Equals(values[j]))
                        {
                            ++n;

                            if (dt.Rows[d][m].ToString().Equals(s[i]))
                            {
                                ++nc;
                            }
                        }
                    }

                    double x = m * p;
                    double y = n + m;
                    double z = nc + x;

                    pi = z / y;
                    mul.Add(Math.Abs(pi));
                }

                double mulres = 1.0;

                for (int z = 0; z < mul.Count; z++)
                {
                    mulres *= double.Parse(mul[z].ToString());
                }

                result = mulres * p;
                output.Add(Math.Abs(result));
            }

            ArrayList list1 = new ArrayList();

            for (int x = 0; x < s.Count; x++)
            {
                list1.Add(output[x]);
            }

            list1.Sort();
            list1.Reverse();

            string _output = null;

            for (int y = 0; y < s.Count; y++)
            {
                if (output[y].Equals(list1[0]))
                {
                    _output = s[y].ToString();
                    return(_output);
                }
            }
            //}
            //catch
            //{

            //}

            return(_output);
        }
Example #34
0
        /// <summary>
        /// This method deals with the starting tags.
        /// </summary>
        /// <param name="name">the name of the tag</param>
        public void HandleEndingTags(String name)
        {
            //System.err.Println("Stop: " + name);

            if (ElementTags.IGNORE.Equals(name))
            {
                ignore = false;
                return;
            }
            if (ignore)
            {
                return;
            }
            // tags that don't have any content
            if (IsNewpage(name) || ElementTags.ANNOTATION.Equals(name) || ElementTags.IMAGE.Equals(name) || IsNewline(name))
            {
                return;
            }

            try {
                // titles of sections and chapters
                if (ElementTags.TITLE.Equals(name))
                {
                    Paragraph current = (Paragraph)stack.Pop();
                    if (currentChunk != null)
                    {
                        current.Add(currentChunk);
                        currentChunk = null;
                    }
                    Section previous = (Section)stack.Pop();
                    previous.Title = current;
                    stack.Push(previous);
                    return;
                }

                // all other endtags
                if (currentChunk != null)
                {
                    ITextElementArray current;
                    try {
                        current = (ITextElementArray)stack.Pop();
                    }
                    catch {
                        current = new Paragraph();
                    }
                    current.Add(currentChunk);
                    stack.Push(current);
                    currentChunk = null;
                }

                // chunks
                if (ElementTags.CHUNK.Equals(name))
                {
                    return;
                }

                // phrases, anchors, lists, tables
                if (ElementTags.PHRASE.Equals(name) || ElementTags.ANCHOR.Equals(name) || ElementTags.LIST.Equals(name) ||
                    ElementTags.PARAGRAPH.Equals(name))
                {
                    IElement current = (IElement)stack.Pop();
                    try {
                        ITextElementArray previous = (ITextElementArray)stack.Pop();
                        previous.Add(current);
                        stack.Push(previous);
                    }
                    catch {
                        document.Add(current);
                    }
                    return;
                }

                // listitems
                if (ElementTags.LISTITEM.Equals(name))
                {
                    ListItem listItem = (ListItem)stack.Pop();
                    List     list     = (List)stack.Pop();
                    list.Add(listItem);
                    stack.Push(list);
                }

                // tables
                if (ElementTags.TABLE.Equals(name))
                {
                    Table table = (Table)stack.Pop();
                    try {
                        ITextElementArray previous = (ITextElementArray)stack.Pop();
                        previous.Add(table);
                        stack.Push(previous);
                    }
                    catch {
                        document.Add(table);
                    }
                    return;
                }

                // rows
                if (ElementTags.ROW.Equals(name))
                {
                    ArrayList cells   = new ArrayList();
                    int       columns = 0;
                    Table     table;
                    Cell      cell;
                    while (true)
                    {
                        IElement element = (IElement)stack.Pop();
                        if (element.Type == Element.CELL)
                        {
                            cell     = (Cell)element;
                            columns += cell.Colspan;
                            cells.Add(cell);
                        }
                        else
                        {
                            table = (Table)element;
                            break;
                        }
                    }
                    if (table.Columns < columns)
                    {
                        table.AddColumns(columns - table.Columns);
                    }
                    cells.Reverse(0, cells.Count);
                    String  width;
                    float[] cellWidths = new float[columns];
                    bool[]  cellNulls  = new bool[columns];
                    for (int i = 0; i < columns; i++)
                    {
                        cellWidths[i] = 0;
                        cellNulls[i]  = true;
                    }
                    float total = 0;
                    int   j     = 0;
                    foreach (Cell c in cells)
                    {
                        cell  = c;
                        width = cell.GetWidthAsString();
                        if (cell.Width == 0)
                        {
                            if (cell.Colspan == 1 && cellWidths[j] == 0)
                            {
                                try {
                                    cellWidths[j] = 100f / columns;
                                    total        += cellWidths[j];
                                }
                                catch {
                                    // empty on purpose
                                }
                            }
                            else if (cell.Colspan == 1)
                            {
                                cellNulls[j] = false;
                            }
                        }
                        else if (cell.Colspan == 1 && width.EndsWith("%"))
                        {
                            try {
                                cellWidths[j] = float.Parse(width.Substring(0, width.Length - 1), NumberFormatInfo.InvariantInfo);
                                total        += cellWidths[j];
                            }
                            catch {
                                // empty on purpose
                            }
                        }
                        j += cell.Colspan;
                        table.AddCell(cell);
                    }
                    float[] widths = table.ProportionalWidths;
                    if (widths.Length == columns)
                    {
                        float left = 0.0f;
                        for (int i = 0; i < columns; i++)
                        {
                            if (cellNulls[i] && widths[i] != 0)
                            {
                                left         += widths[i];
                                cellWidths[i] = widths[i];
                            }
                        }
                        if (100.0 >= total)
                        {
                            for (int i = 0; i < widths.Length; i++)
                            {
                                if (cellWidths[i] == 0 && widths[i] != 0)
                                {
                                    cellWidths[i] = (widths[i] / left) * (100.0f - total);
                                }
                            }
                        }
                        table.Widths = cellWidths;
                    }
                    stack.Push(table);
                }

                // registerfont
                if (name.Equals("registerfont"))
                {
                    return;
                }

                // header
                if (ElementTags.HEADER.Equals(name))
                {
                    document.Header = (HeaderFooter)stack.Pop();
                    return;
                }

                // footer
                if (ElementTags.FOOTER.Equals(name))
                {
                    document.Footer = (HeaderFooter)stack.Pop();
                    return;
                }

                // before
                if (name.Equals("before"))
                {
                    return;
                }

                // after
                if (name.Equals("after"))
                {
                    return;
                }

                // cells
                if (ElementTags.CELL.Equals(name))
                {
                    return;
                }

                // sections
                if (ElementTags.SECTION.Equals(name))
                {
                    stack.Pop();
                    return;
                }

                // chapters
                if (ElementTags.CHAPTER.Equals(name))
                {
                    document.Add((IElement)stack.Pop());
                    return;
                }

                // the documentroot
                if (IsDocumentRoot(name))
                {
                    try {
                        while (true)
                        {
                            IElement element = (IElement)stack.Pop();
                            try {
                                ITextElementArray previous = (ITextElementArray)stack.Pop();
                                previous.Add(element);
                                stack.Push(previous);
                            }
                            catch {
                                document.Add(element);
                            }
                        }
                    }
                    catch {
                        // empty on purpose
                    }
                    if (controlOpenClose)
                    {
                        document.Close();
                    }
                    return;
                }
            }
            catch (DocumentException de) {
                throw de;
            }
        }
Example #35
0
 void LoadCasts(XmlDocument xml)
 {
     ArrayList toadd = new ArrayList ();
     XmlNodeList items = xml.SelectNodes ("//item");
     foreach (XmlNode item in items) {
         string encurl = WebUtil.GetXmlNodeText (item, "enclosure/@url");
         string type = WebUtil.GetXmlNodeText (item, "enclosure/@type");
         // HACK: if type is empty, assume it's audio/mpeg.
         if (encurl != "" && (type == null || type == "" || KnownType (type))) {
             toadd.Add (item);
         }
     }
     // add in reverse order, so the IDs go up in chronological order
     toadd.Reverse ();
     foreach (XmlNode item in toadd)
     {
         // create and store cast
         string encurl = WebUtil.GetXmlNodeText (item, "enclosure/@url");
         Cast k = Cast.CastForUrl (this, encurl);
         string title = 	StringUtils.StripHTML (WebUtil.GetXmlNodeText (item, "title").Trim());
         string desc = StringUtils.StripHTML (WebUtil.GetXmlNodeText (item, "description").Trim());
         string type = WebUtil.GetXmlNodeText (item, "enclosure/@type");
         // HACK: if type is empty, assume it's audio/mpeg.
         if (type == null || type == "") {
             type = "audio/mpeg";
         }
         string length = WebUtil.GetXmlNodeText (item, "enclosure/@length");
         if (k != null) {
             k.Update (title, desc, type, length);
         } else {
         // CreateCastIfNeeded ();
             new Cast (this,	encurl, title, desc, type, length);
         }
         System.Console.WriteLine ("{0} {1}", title, encurl);
     }
 }
Example #36
0
        //function which contains the algorithm steps
        private void NaiveBayes(string[] values)
        {
            ArrayList s = new ArrayList();

            output.Clear();

            s = GetSubject();

            int    m     = 9;
            double numer = 1.0;
            double dino  = double.Parse(s.Count.ToString());
            double p     = numer / dino;

            string[] features = { "os",      "color", "pcamera", "scamera", "ram",
                                  "storage", "speed", "dualsim", "display" };

            for (int i = 0; i < s.Count; i++)
            {
                mul.Clear();

                for (int j = 0; j < features.Length; j++)
                {
                    n  = 0;
                    nc = 0;

                    for (int d = 0; d < dt.Rows.Count; d++)
                    {
                        if (dt.Rows[d][j].ToString().Equals(values[j]))
                        {
                            ++n;

                            if (dt.Rows[d][m].ToString().Equals(s[i]))
                            {
                                ++nc;
                            }
                        }
                    }

                    double x = m * p;
                    double y = n + m;
                    double z = nc + x;

                    pi = z / y;
                    mul.Add(Math.Abs(pi));
                }

                double mulres = 1.0;

                for (int z = 0; z < mul.Count; z++)
                {
                    mulres *= double.Parse(mul[z].ToString());
                }

                result = mulres * p;
                output.Add(Math.Abs(result));
            }

            ArrayList list1 = new ArrayList();

            for (int x = 0; x < s.Count; x++)
            {
                list1.Add(output[x]);
            }

            list1.Sort();
            list1.Reverse();

            string _output = null;

            for (int y = 0; y < s.Count; y++)
            {
                if (output[y].Equals(list1[0]))
                {
                    _output = s[y].ToString();

                    string _res = null;

                    if (_output == "0")
                    {
                        _res = "Loss";
                    }
                    else if (_output == "1")
                    {
                        _res = "Less Level Profit";
                    }
                    else if (_output == "2")
                    {
                        _res = "Medium Level Profit";
                    }
                    else
                    {
                        _res = "High Level Profit";
                    }

                    lblResult.Text = txtPName.Value + " classified to " + _res;
                }
            }
        }
Example #37
0
    public virtual bool runTest()
    {
        int iCountErrors    = 0;
        int iCountTestcases = 0;

        Console.Error.WriteLine(strName + ": " + strTest + " runTest started...");
        ArrayList arrList = null;

        String [] strHeroes =
        {
            "Aquaman",
            "Atom",
            "Batman",
            "Black Canary",
            "Captain America",
            "Captain Atom",
            "Catwoman",
            "Cyborg",
            "Flash",
            "Green Arrow",
            "Green Lantern",
            "Hawkman",
            "Huntress",
            "Ironman",
            "Nightwing",
            "Robin",
            "SpiderMan",
            "Steel",
            "Superman",
            "Thor",
            "Wildcat",
            "Wonder Woman",
        };
        do
        {
            ++iCountTestcases;
            Console.Error.WriteLine("[]  Construct ArrayList");
            try
            {
                arrList = new ArrayList((ICollection)strHeroes);
                if (arrList == null)
                {
                    Console.WriteLine(strTest + "E_101: Failed to construct new ArrayList1");
                    ++iCountErrors;
                    break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(strTest + "E_10001: Unexpected Exception: " + ex.ToString());
                ++iCountErrors;
                break;
            }
            ++iCountTestcases;
            Console.Error.WriteLine("[]  Reverse entire array list");
            try
            {
                arrList.Reverse( );
                for (int ii = 0; ii < arrList.Count; ++ii)
                {
                    if (strHeroes[ii].CompareTo((String)arrList[arrList.Count - ii - 1]) != 0)
                    {
                        String strInfo = strTest + " error: ";
                        strInfo = strInfo + "Expected hero <" + strHeroes[ii] + "> ";
                        strInfo = strInfo + "Returned hero <" + (String)arrList[ii + arrList.Count - 1] + "> ";
                        Console.WriteLine(strTest + "E_202: " + strInfo);
                        ++iCountErrors;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(strTest + "E_10002: Unexpected Exception: " + ex.ToString());
                ++iCountErrors;
                break;
            }
            ++iCountTestcases;
            arrList = new ArrayList();
            try
            {
                arrList.Reverse();
            }
            catch (Exception ex)
            {
                ++iCountErrors;
                Console.WriteLine("Err_7842f! Unexpected exception thrown, " + ex);
            }
            arrList = new ArrayList();
            for (int i = 0; i < 1; i++)
            {
                arrList.Add(i);
            }
            try
            {
                arrList.Reverse();
            }
            catch (Exception ex)
            {
                ++iCountErrors;
                Console.WriteLine("Err_7842f! Unexpected exception thrown, " + ex);
            }
        }while (false);
        Console.Error.Write(strName);
        Console.Error.Write(": ");
        if (iCountErrors == 0)
        {
            Console.Error.WriteLine(strTest + " iCountTestcases==" + iCountTestcases + " paSs");
            return(true);
        }
        else
        {
            Console.WriteLine(strTest + strPath);
            Console.WriteLine(strTest + "FAiL");
            Console.Error.WriteLine(strTest + " iCountErrors==" + iCountErrors);
            return(false);
        }
    }
        protected override void ApplySortCore(PropertyDescriptor prop,
                                              ListSortDirection direction)
        {
            _sortedList = new ArrayList();

            // Check to see if the property type we are sorting by implements
            // the IComparable interface.
            Type interfaceType = prop.PropertyType.GetInterface("IComparable");

            if (interfaceType != null)
            {
                // If so, set the SortPropertyValue and SortDirectionValue.
                _sortPropertyValue  = prop;
                _sortDirectionValue = direction;

                _unsortedItems = new FilteredBindingList <T>();

                if (_sortPropertyValue != null)
                {
                    // Loop through each item, adding it the the sortedItems ArrayList.
                    foreach (Object item in this.Items)
                    {
                        _unsortedItems.Add((T)item);
                        _sortedList.Add(prop.GetValue(item));
                    }
                }
                // Call Sort on the ArrayList.
                _sortedList.Sort();
                T temp;

                // Check the sort direction and then copy the sorted items
                // back into the list.
                if (direction == ListSortDirection.Descending)
                {
                    _sortedList.Reverse();
                }

                for (int i = 0; i < this.Count; i++)
                {
                    int position = Find(prop.Name, _sortedList[i]);
                    if (position != i && position > 0)
                    {
                        temp           = this[i];
                        this[i]        = this[position];
                        this[position] = temp;
                    }
                }

                _isSortedValue = true;

                // If the list does not have a filter applied,
                // raise the ListChanged event so bound controls refresh their
                // values. Pass -1 for the index since this is a Reset.
                if (String.IsNullOrEmpty(Filter))
                {
                    OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
                }
            }
            else
            {
                // If the property type does not implement IComparable, let the user
                // know.
                throw new InvalidOperationException("Cannot sort by "
                                                    + prop.Name + ". This" + prop.PropertyType.ToString() +
                                                    " does not implement IComparable");
            }
        }
Example #39
0
 private void ReadGazetteerSettings(MemoryStore rdfStore, out CaseMatchingType caseMatchingType, out bool lemmatize, out bool enabled)
 {
     caseMatchingType = CaseMatchingType.IgnoreCase;
     lemmatize = false;
     enabled = true;
     ArrayList<string> crumbs = new ArrayList<string>(new string[] { mUri });
     Entity[] objects = rdfStore.SelectSubjects(P_IDENTIFIED_BY, new Entity(mUri));
     if (objects.Length > 0)
     {
         Resource[] objTypes = rdfStore.SelectObjects(objects[0].Uri, P_TYPE);
         if (objTypes.Length > 0)
         {
             crumbs.Add(objTypes[0].Uri);
             Resource[] superClass = rdfStore.SelectObjects((Entity)objTypes[0], P_SUBCLASS_OF);
             while (superClass.Length > 0)
             {
                 crumbs.Add(superClass[0].Uri);
                 superClass = rdfStore.SelectObjects((Entity)superClass[0], P_SUBCLASS_OF);
             }
         }
     }
     crumbs.Reverse();
     foreach (string uri in crumbs)
     {
         Resource[] settings = rdfStore.SelectObjects(uri, P_SETTINGS);
         if (settings.Length == 0) { settings = rdfStore.SelectObjects(uri, P_COMMENT); } // for compatibility with OWL-DL
         if (settings.Length > 0)
         {
             string settingsStr = ((Literal)settings[0]).Value;
             ParseGazetteerSettings(settingsStr, ref caseMatchingType, ref lemmatize, ref enabled);
         }
     }
 }
        private void timer1_Tick(object sender, EventArgs e)
        {
            saniye += 0.1;
            atIlerletme();
            atlar.Clear();
            int katedilen1 = birinciAt.Right - baslangic;

            birinciAtKatMes.Text = katedilen1.ToString();
            int katedilen2 = ikinciAt.Right - baslangic;

            ikinciAtKatMes.Text = katedilen2.ToString();
            int katedilen3 = ucuncuAt.Right - baslangic;

            ucuncuAtKatMes.Text = katedilen3.ToString();
            int katedilen4 = dorduncuAt.Right - baslangic;

            dorduncuAtKatMes.Text = katedilen4.ToString();
            atlar.Add((katedilen1) + "|" + gBirinciAt);
            atlar.Add((katedilen2) + "|" + gIkinciAt);
            atlar.Add((katedilen3) + "|" + gUcuncuAt);
            atlar.Add((katedilen4) + "|" + gDorduncuAt);
            atlar.Sort();
            atlar.Reverse();
            if (birinciAtKatMes.Text != "" && birinciAtKatMes.Text != "0" && ikinciAtKatMes.Text != "" && ikinciAtKatMes.Text != "0" && ucuncuAtKatMes.Text != "" && ucuncuAtKatMes.Text != "0" && dorduncuAtKatMes.Text != "" && dorduncuAtKatMes.Text != "0")
            {
                birinciAtKatedilen.Text  = "Saniyede katedilen mesafe: " + virgulAl((Convert.ToDouble(katedilen1) / Convert.ToDouble(saniye)).ToString());
                ikinciAtKatedilen.Text   = "Saniyede katedilen mesafe: " + virgulAl((Convert.ToDouble(katedilen2) / Convert.ToDouble(saniye)).ToString());
                ucuncuAtKatedilen.Text   = "Saniyede katedilen mesafe: " + virgulAl((Convert.ToDouble(katedilen3) / Convert.ToDouble(saniye)).ToString());
                dorduncuAtKatedilen.Text = "Saniyede katedilen mesafe: " + virgulAl((Convert.ToDouble(katedilen4) / Convert.ToDouble(saniye)).ToString());
            }
            double yuzde1 = ((double)katedilen1 / son) * 100;
            double yuzde2 = ((double)katedilen2 / son) * 100;
            double yuzde3 = ((double)katedilen3 / son) * 100;
            double yuzde4 = ((double)katedilen4 / son) * 100;

            birinciAtMesafe.Value = Convert.ToInt32(yuzde1);
            GC.SuppressFinalize(yuzde1);
            GC.SuppressFinalize(birinciAtMesafe);
            ikinciAtMesafe.Value = Convert.ToInt32(yuzde2);
            GC.SuppressFinalize(yuzde2);
            GC.SuppressFinalize(ikinciAtMesafe);
            ucuncuAtMesafe.Value = Convert.ToInt32(yuzde3);
            GC.SuppressFinalize(yuzde3);
            GC.SuppressFinalize(ucuncuAtMesafe);
            dorduncuAtMesafe.Value = Convert.ToInt32(yuzde4);
            GC.SuppressFinalize(yuzde4);
            GC.SuppressFinalize(dorduncuAtMesafe);
            label12.Text        = "%" + virgulAl(yuzde1.ToString());
            label13.Text        = "%" + virgulAl(yuzde2.ToString());
            label14.Text        = "%" + virgulAl(yuzde3.ToString());
            label15.Text        = "%" + virgulAl(yuzde4.ToString());
            siraBirinciAt.Text  = siralamaBul(gBirinciAt, atlar).ToString();
            siraIkinciAt.Text   = siralamaBul(gIkinciAt, atlar).ToString();
            siraUcuncuAt.Text   = siralamaBul(gUcuncuAt, atlar).ToString();
            siraDorduncuAt.Text = siralamaBul(gDorduncuAt, atlar).ToString();
            listBox1.Items.Clear();
            listBox1.Items.Add("1. " + atlar[0].ToString().Split('|')[1]);
            listBox1.Items.Add("2. " + atlar[1].ToString().Split('|')[1]);
            listBox1.Items.Add("3. " + atlar[2].ToString().Split('|')[1]);
            listBox1.Items.Add("4. " + atlar[3].ToString().Split('|')[1]);
            listView1.Items.Clear();
            for (int i = 0; i < bahisler.GetLength(0); i++)
            {
                int itemsCount = listView1.Items.Count;
                listView1.Items.Add(bahisler[i, 0]);                                                     // Kullanıcı Adı
                listView1.Items[itemsCount].SubItems.Add(bahisler[i, 2]);                                // Bahis
                listView1.Items[itemsCount].SubItems.Add(bahisler[i, 4]);                                // Kazanacak
                listView1.Items[itemsCount].SubItems.Add(siralamaBul(bahisler[i, 3], atlar).ToString()); // Tahmin
            }

            if (birinciAt.Right >= label1.Left)
            {
                bittimi = true;
                timer1.Stop();
                birinciAt.Location   = new Point(label1.Left - 148, birinciAt.Location.Y);
                birinciAtKatMes.Text = "994";
                birinciAt.Image      = Image.FromFile("at_normal.png");
                ikinciAt.Image       = Image.FromFile("at_normal.png");
                ucuncuAt.Image       = Image.FromFile("at_normal.png");
                dorduncuAt.Image     = Image.FromFile("at_normal.png");
                atlar.Clear();
                int aKatedilen1 = birinciAt.Right - baslangic;
                birinciAtKatMes.Text = aKatedilen1.ToString();
                GC.SuppressFinalize(aKatedilen1);
                int aKatedilen2 = ikinciAt.Right - baslangic;
                ikinciAtKatMes.Text = aKatedilen2.ToString();
                GC.SuppressFinalize(aKatedilen2);
                int aKatedilen3 = ucuncuAt.Right - baslangic;
                ucuncuAtKatMes.Text = aKatedilen3.ToString();
                GC.SuppressFinalize(aKatedilen3);
                int aKatedilen4 = dorduncuAt.Right - baslangic;
                dorduncuAtKatMes.Text = aKatedilen4.ToString();
                GC.SuppressFinalize(aKatedilen4);
                atlar.Add((katedilen1) + "|" + gBirinciAt);
                GC.SuppressFinalize(katedilen1);
                atlar.Add((katedilen2) + "|" + gIkinciAt);
                GC.SuppressFinalize(katedilen2);
                atlar.Add((katedilen3) + "|" + gUcuncuAt);
                GC.SuppressFinalize(katedilen3);
                atlar.Add((katedilen4) + "|" + gDorduncuAt);
                GC.SuppressFinalize(katedilen4);
                atlar.Sort();
                atlar.Reverse();
                siraBirinciAt.Text  = siralamaBul(gBirinciAt, atlar).ToString();
                siraIkinciAt.Text   = siralamaBul(gIkinciAt, atlar).ToString();
                siraUcuncuAt.Text   = siralamaBul(gUcuncuAt, atlar).ToString();
                siraDorduncuAt.Text = siralamaBul(gDorduncuAt, atlar).ToString();
                GC.SuppressFinalize(atlar);
                listBox1.Items.Clear();
                listBox1.Items.Add("1. " + atlar[0].ToString().Split('|')[1]);
                listBox1.Items.Add("2. " + atlar[1].ToString().Split('|')[1]);
                listBox1.Items.Add("3. " + atlar[2].ToString().Split('|')[1]);
                listBox1.Items.Add("4. " + atlar[3].ToString().Split('|')[1]);
                GC.SuppressFinalize(atlar);
                kazanan.Text = "Kazanan: " + gBirinciAt;
                kazanan.Tag  = gBirinciAt;
                MessageBox.Show("Kazanan At: " + gBirinciAt, "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (ikinciAt.Right >= label1.Left)
            {
                bittimi = true;
                timer1.Stop();
                ikinciAt.Location   = new Point(label1.Left - 148, ikinciAt.Location.Y);
                ikinciAtKatMes.Text = "994";
                birinciAt.Image     = Image.FromFile("at_normal.png");
                ikinciAt.Image      = Image.FromFile("at_normal.png");
                ucuncuAt.Image      = Image.FromFile("at_normal.png");
                dorduncuAt.Image    = Image.FromFile("at_normal.png");
                atlar.Clear();
                int bKatedilen1 = birinciAt.Right - baslangic;
                birinciAtKatMes.Text = bKatedilen1.ToString();
                GC.SuppressFinalize(bKatedilen1);
                int bKatedilen2 = ikinciAt.Right - baslangic;
                ikinciAtKatMes.Text = bKatedilen2.ToString();
                GC.SuppressFinalize(bKatedilen2);
                int bKatedilen3 = ucuncuAt.Right - baslangic;
                ucuncuAtKatMes.Text = bKatedilen3.ToString();
                GC.SuppressFinalize(bKatedilen3);
                int bKatedilen4 = dorduncuAt.Right - baslangic;
                dorduncuAtKatMes.Text = bKatedilen4.ToString();
                GC.SuppressFinalize(bKatedilen4);
                atlar.Add((katedilen1) + "|" + gBirinciAt);
                GC.SuppressFinalize(gBirinciAt);
                GC.SuppressFinalize(katedilen1);
                atlar.Add((katedilen2) + "|" + gIkinciAt);
                GC.SuppressFinalize(gIkinciAt);
                GC.SuppressFinalize(katedilen2);
                atlar.Add((katedilen3) + "|" + gUcuncuAt);
                GC.SuppressFinalize(gUcuncuAt);
                GC.SuppressFinalize(katedilen3);
                atlar.Add((katedilen4) + "|" + gDorduncuAt);
                GC.SuppressFinalize(gDorduncuAt);
                GC.SuppressFinalize(katedilen4);
                atlar.Sort();
                atlar.Reverse();
                siraBirinciAt.Text  = siralamaBul(gBirinciAt, atlar).ToString();
                siraIkinciAt.Text   = siralamaBul(gIkinciAt, atlar).ToString();
                siraUcuncuAt.Text   = siralamaBul(gUcuncuAt, atlar).ToString();
                siraDorduncuAt.Text = siralamaBul(gDorduncuAt, atlar).ToString();
                GC.SuppressFinalize(atlar);
                listBox1.Items.Clear();
                listBox1.Items.Add("1. " + atlar[0].ToString().Split('|')[1]);
                listBox1.Items.Add("2. " + atlar[1].ToString().Split('|')[1]);
                listBox1.Items.Add("3. " + atlar[2].ToString().Split('|')[1]);
                listBox1.Items.Add("4. " + atlar[3].ToString().Split('|')[1]);
                GC.SuppressFinalize(atlar);
                kazanan.Text = "Kazanan: " + gIkinciAt;
                kazanan.Tag  = gIkinciAt;
                MessageBox.Show("Kazanan At: " + gIkinciAt, "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (ucuncuAt.Right >= label1.Left)
            {
                bittimi = true;
                timer1.Stop();
                ucuncuAt.Location   = new Point(label1.Left - 148, ucuncuAt.Location.Y);
                ucuncuAtKatMes.Text = "994";
                birinciAt.Image     = Image.FromFile("at_normal.png");
                ikinciAt.Image      = Image.FromFile("at_normal.png");
                ucuncuAt.Image      = Image.FromFile("at_normal.png");
                dorduncuAt.Image    = Image.FromFile("at_normal.png");
                atlar.Clear();
                int cKatedilen1 = birinciAt.Right - baslangic;
                birinciAtKatMes.Text = cKatedilen1.ToString();
                GC.SuppressFinalize(cKatedilen1);
                int cKatedilen2 = ikinciAt.Right - baslangic;
                ikinciAtKatMes.Text = cKatedilen2.ToString();
                GC.SuppressFinalize(cKatedilen2);
                int cKatedilen3 = ucuncuAt.Right - baslangic;
                ucuncuAtKatMes.Text = cKatedilen3.ToString();
                GC.SuppressFinalize(cKatedilen3);
                int cKatedilen4 = dorduncuAt.Right - baslangic;
                dorduncuAtKatMes.Text = cKatedilen4.ToString();
                GC.SuppressFinalize(cKatedilen4);
                atlar.Add((katedilen1) + "|" + gBirinciAt);
                GC.SuppressFinalize(katedilen1);
                GC.SuppressFinalize(gBirinciAt);
                atlar.Add((katedilen2) + "|" + gIkinciAt);
                GC.SuppressFinalize(katedilen2);
                GC.SuppressFinalize(gIkinciAt);
                atlar.Add((katedilen3) + "|" + gUcuncuAt);
                GC.SuppressFinalize(katedilen3);
                GC.SuppressFinalize(gUcuncuAt);
                atlar.Add((katedilen4) + "|" + gDorduncuAt);
                GC.SuppressFinalize(katedilen4);
                GC.SuppressFinalize(gDorduncuAt);
                atlar.Sort();
                atlar.Reverse();
                siraBirinciAt.Text  = siralamaBul(gBirinciAt, atlar).ToString();
                siraIkinciAt.Text   = siralamaBul(gIkinciAt, atlar).ToString();
                siraUcuncuAt.Text   = siralamaBul(gUcuncuAt, atlar).ToString();
                siraDorduncuAt.Text = siralamaBul(gDorduncuAt, atlar).ToString();
                GC.SuppressFinalize(atlar);
                listBox1.Items.Clear();
                listBox1.Items.Add("1. " + atlar[0].ToString().Split('|')[1]);
                listBox1.Items.Add("2. " + atlar[1].ToString().Split('|')[1]);
                listBox1.Items.Add("3. " + atlar[2].ToString().Split('|')[1]);
                listBox1.Items.Add("4. " + atlar[3].ToString().Split('|')[1]);
                GC.SuppressFinalize(atlar);
                kazanan.Text = "Kazanan: " + gUcuncuAt;
                kazanan.Tag  = gUcuncuAt;
                MessageBox.Show("Kazanan At: " + gUcuncuAt, "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (dorduncuAt.Right >= label1.Left)
            {
                bittimi = true;
                timer1.Stop();
                dorduncuAt.Location   = new Point(label1.Left - 148, dorduncuAt.Location.Y);
                dorduncuAtKatMes.Text = "994";
                birinciAt.Image       = Image.FromFile("at_normal.png");
                ikinciAt.Image        = Image.FromFile("at_normal.png");
                ucuncuAt.Image        = Image.FromFile("at_normal.png");
                dorduncuAt.Image      = Image.FromFile("at_normal.png");
                atlar.Clear();
                int dKatedilen1 = birinciAt.Right - baslangic;
                birinciAtKatMes.Text = dKatedilen1.ToString();
                int dKatedilen2 = ikinciAt.Right - baslangic;
                ikinciAtKatMes.Text = dKatedilen2.ToString();
                int dKatedilen3 = ucuncuAt.Right - baslangic;
                ucuncuAtKatMes.Text = dKatedilen3.ToString();
                int dKatedilen4 = dorduncuAt.Right - baslangic;
                dorduncuAtKatMes.Text = dKatedilen4.ToString();
                atlar.Add((katedilen1) + "|" + gBirinciAt);
                atlar.Add((katedilen2) + "|" + gIkinciAt);
                atlar.Add((katedilen3) + "|" + gUcuncuAt);
                atlar.Add((katedilen4) + "|" + gDorduncuAt);
                atlar.Sort();
                atlar.Reverse();
                siraBirinciAt.Text  = siralamaBul(gBirinciAt, atlar).ToString();
                siraIkinciAt.Text   = siralamaBul(gIkinciAt, atlar).ToString();
                siraUcuncuAt.Text   = siralamaBul(gUcuncuAt, atlar).ToString();
                siraDorduncuAt.Text = siralamaBul(gDorduncuAt, atlar).ToString();
                listBox1.Items.Clear();
                listBox1.Items.Add("1. " + atlar[0].ToString().Split('|')[1]);
                listBox1.Items.Add("2. " + atlar[1].ToString().Split('|')[1]);
                listBox1.Items.Add("3. " + atlar[2].ToString().Split('|')[1]);
                listBox1.Items.Add("4. " + atlar[3].ToString().Split('|')[1]);
                kazanan.Text = "Kazanan: " + gDorduncuAt;
                kazanan.Tag  = gDorduncuAt;
                MessageBox.Show("Kazanan At: " + gDorduncuAt, "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            if (bittimi == true)
            {
                listView1.Items.Clear();
                for (int i = 0; i < bahisler.GetLength(0); i++)
                {
                    int itemsCount = listView1.Items.Count;
                    listView1.Items.Add(bahisler[i, 0]);                                                     // Kullanıcı Adı
                    listView1.Items[itemsCount].SubItems.Add(bahisler[i, 2]);                                // Bahis
                    listView1.Items[itemsCount].SubItems.Add(bahisler[i, 4]);                                // Kazanacak
                    listView1.Items[itemsCount].SubItems.Add(siralamaBul(bahisler[i, 3], atlar).ToString()); // Tahmin
                }

                int iSayi = 0;
                for (int i = 0; i < bahisler.GetLength(0); i++)
                {
                    if (siralamaBul(bahisler[i, 3], atlar) == 1)
                    {
                        iSayi = Convert.ToInt32(bahisler[i, 1]) + Convert.ToInt32(bahisler[i, 4]);
                    }
                    else
                    {
                        iSayi = Convert.ToInt32(bahisler[i, 1]) - Convert.ToInt32(bahisler[i, 2]);
                    }

                    if (iSayi == 0)
                    {
                        baglan(baglanti);
                        OleDbCommand komut = new OleDbCommand("UPDATE kisiler SET para='" + iSayi + "' AND yenilenme='7' WHERE kullanici='" + bahisler[i, 0] + "'", baglanti);
                        komut.ExecuteNonQuery();
                        komut.Dispose();
                        richTextBox1.Text = bahisler[i, 0] + " adlı kullanıcının bakiyesi " + iSayi + " olarak güncellenmiştir! Bakiyeniz 6 yarış sonra tekrar 100 olarak güncelenecektir.\n";
                    }
                    else
                    {
                        baglan(baglanti);
                        OleDbCommand komut = new OleDbCommand("UPDATE kisiler SET para='" + iSayi + "' WHERE kullanici='" + bahisler[i, 0] + "'", baglanti);
                        komut.ExecuteNonQuery();
                        komut.Dispose();
                        richTextBox1.Text = bahisler[i, 0] + " adlı kullanıcının bakiyesi " + iSayi + " olarak güncellenmiştir!\n";
                    }
                }
                baglanti.Close();
                baglan(baglanti);
                OleDbCommand    komut2  = new OleDbCommand("SELECT * FROM kisiler", baglanti);
                OleDbDataReader okuyucu = komut2.ExecuteReader();
                while (okuyucu.Read())
                {
                    if (okuyucu["para"].ToString() == "0")
                    {
                        int sayi = Convert.ToInt32(okuyucu["yenilenme"].ToString());
                        if (sayi > 1)
                        {
                            sayi--;
                            OleDbCommand duzenle = new OleDbCommand("UPDATE kisiler SET yenilenme='" + sayi + "' WHERE kullanici='" + okuyucu["kullanici"].ToString() + "'", baglanti);
                            duzenle.ExecuteNonQuery();
                            duzenle.Dispose();
                        }
                        else if (sayi <= 1)
                        {
                            OleDbCommand duzenle2 = new OleDbCommand("UPDATE kisiler SET para='100', yenilenme='7' WHERE kullanici='" + okuyucu["kullanici"].ToString() + "'", baglanti);
                            duzenle2.ExecuteNonQuery();
                            duzenle2.Dispose();
                            richTextBox1.Text += okuyucu["kullanici"].ToString() + " adlı kullanıcının bakiyesi tekrar 100 olarak güncellendi.\n";
                        }
                    }
                }
                baglanti.Close();
            }
        }
Example #41
0
        static void Main(string[] args)
        {
            #region Basics

            // Example Single-line Comment

            /* Example
             * Multiline
             * Comment
             */

            //Hello World
            Console.WriteLine("Hello World");

            //Get user input
            Console.Write("What's your name? ");
            string name = Console.ReadLine();
            Console.WriteLine("Hello " + name);

            //Data Types
            bool canVote = true;
            char fumoffu = '%';

            int     maxInt     = int.MaxValue;
            long    maxLong    = long.MaxValue;
            decimal maxDecimal = decimal.MaxValue;
            float   maxFloat   = float.MaxValue;
            double  maxDouble  = double.MaxValue;

            Console.WriteLine("Max Int: " + maxInt);

            //Implicit type variable declaration
            var sampleVar = "SampleString";

            //You can't change its type after declaration though
            //sampleVar = 2;

            Console.WriteLine("sampleVar is a {0}", sampleVar.GetTypeCode());
            Console.WriteLine("-------------------------------------------------------");

            //Arithmetics
            Console.WriteLine("5 + 3 = " + (5 + 3));
            Console.WriteLine("5 - 3 = " + (5 - 3));
            Console.WriteLine("5 * 3 = " + (5 * 3));
            Console.WriteLine("5 / 3 = " + (5 / 3));
            Console.WriteLine("5.2 % 3 = " + (5.2 % 3));

            int i = 0;

            Console.WriteLine("i++ = " + i++);
            Console.WriteLine("++i = " + ++i);
            Console.WriteLine("i-- = " + i--);
            Console.WriteLine("--i = " + --i);

            Console.WriteLine("-------------------------------------------------------");
            //Some Math Static Functions
            //acos, asin, atan, atan2, cos, cosh, exp, log, sin, sinh, tan, tanh
            double num1 = 10.5;
            double num2 = 15;

            Console.WriteLine("Abs(num1): " + Math.Abs(num1));
            Console.WriteLine("Ceiling(num1): " + Math.Ceiling(num1));
            Console.WriteLine("Floor(num1): " + Math.Floor(num1));
            Console.WriteLine("Max(num1, num2): " + Math.Max(num1, num2));
            Console.WriteLine("Min(num1, num2): " + Math.Min(num1, num2));
            Console.WriteLine("Pow(num1): " + Math.Pow(num1, num2));
            Console.WriteLine("Round(num1): " + Math.Round(num1));
            Console.WriteLine("Sqrt(num1): " + Math.Sqrt(num1));

            Console.WriteLine("-------------------------------------------------------");

            //Casting
            const double PI    = 3.14;
            int          intPI = (int)PI;

            //Generating Random Numbers
            Random rand = new Random();
            Console.WriteLine("Random number between 1 and 10: " + rand.Next(1, 11));

            #endregion

            #region Conditionals and Loops

            //Relational Operators: > < >= <= == !=
            //Logical Operators: && (AND) || (OR) ^ (XOR) ! (NOT)

            int age = rand.Next(1, 101);
            Console.WriteLine(age);

            //IF statements
            if (age >= 5 && age <= 7)
            {
                Console.WriteLine("Go to Elementary School");
            }
            else if (age > 7 && age < 13)
            {
                Console.WriteLine("Go to Middle School");
            }
            else
            {
                Console.WriteLine("Go to High School");
            }

            if (age < 14 || age > 67)
            {
                Console.WriteLine("You Shouldn't Work");
            }

            Console.WriteLine("! true: " + !true);

            //Ternary - Condition ? ifTrue : ifFalse
            bool canDrive = age >= 18 ? true : false;

            switch (age)
            {
            case 0:
                Console.WriteLine("Infant");
                break;

            case 1:
            case 2:
                Console.WriteLine("Toddler");
                //Goto jumps to the code block you specify (It's gonna kick you out of the switch statement)
                goto Checkpoint1;

            default:
                Console.WriteLine("Child");
                break;
            }

Checkpoint1:
            Console.WriteLine("I'm printed from outside the switch statement");

            Console.WriteLine("-------------------------------------------------------");

            int j = 0;

            while (j < 10)
            {
                if (j == 7)
                {
                    j++;
                    continue;
                }
                //^^^ Jump back to the while header

                if (j == 9)
                {
                    break;
                }
                //// ^^ Jump out of the loop

                if (j % 2 > 0)
                {
                    Console.WriteLine(j);
                }

                j++;
            }

            Console.WriteLine("-------------------------------------------------------");

            //DO While: The body of do is executed at least one time
            string guess;

            do
            {
                Console.WriteLine("Guess a number");
                guess = Console.ReadLine();
            } while (!guess.Equals("15"));

            Console.WriteLine("-------------------------------------------------------");

            //FOR Loop: All the conditional and counter stuff is in the heading
            for (int k = 0; k < 10; k++)
            {
                if (k % 2 != 0)
                {
                    Console.WriteLine(k);
                }
            }

            Console.WriteLine("-------------------------------------------------------");

            //FOREACH: Used to iterate over list, arrays, maps and collections
            string randString = "Example Random String";

            foreach (char c in randString)
            {
                Console.WriteLine(c);
            }

            Console.WriteLine("-------------------------------------------------------");

            #endregion

            #region Strings & Arrays

            //Strings
            //Escape Sequences: Allow you to enter special chars in strings
            //      \' \" \\ \b \n \t
            string sampleString = "Some random words";

            //Prints wether a string is empty or null
            Console.WriteLine("Is Empty: " + String.IsNullOrEmpty(sampleString));
            //Prints wether a string is null or filled with white space
            Console.WriteLine("Is Empty: " + String.IsNullOrWhiteSpace(sampleString));

            Console.WriteLine("String Length: " + sampleString.Length);
            //Returns the position of a certain string/char inside of another string | returns -1 if it doesn't find it
            Console.WriteLine("Index of 'random': " + sampleString.IndexOf("random"));
            //Returns a substring of the parent string when given the index of the first letter and the length of the word

            Console.WriteLine("2nd word: " + sampleString.Substring(5, 6));
            //Returns true if the parent string is equals to the argument string
            Console.WriteLine("Strings Equal: " + sampleString.Equals(randString));
            //Returns true if the String starts with the argument string

            Console.WriteLine("Starts with \"Example Random\": " + randString.StartsWith("Example Random"));
            //Returns true if the String ends with the argument string
            Console.WriteLine("Ends with \"Example String\": " + randString.EndsWith("Example String"));

            //Removes white space at the beginning or at the end of a string
            sampleString = sampleString.Trim(); //TrimEnd TrimStart

            //Replaces a substring of the parent string with another string
            sampleString = sampleString.Replace("words", "characters");

            //Removes a substring of length equals to the second parameter starting from the passed index (first parameter)
            sampleString = sampleString.Remove(0, 4);

            //Array of strings
            string[] words = new string[6] {
                "I", "Suck", "At", "Drawing", "Textures", ":("
            };
            //Join a string array into one single string
            Console.WriteLine("Joined String Array: " + String.Join(" ", words));

            Console.WriteLine("-------------------------------------------------------");

            //Formatting Strings
            string formatted = String.Format("{0:c} {1:00.00} {2:#.00} {3:0,0}", 4.99, 15.567, .56, 1000);
            Console.WriteLine("Formatted Strings examples: " + formatted);

            Console.WriteLine("-------------------------------------------------------");

            //String Builder
            //Used when you want to edit a string without creating a new one
            StringBuilder sb = new StringBuilder();
            //Append new strings - (AppendLine is the version that appends a \n at the end automatically)
            sb.Append("This is the first Sentence.");
            sb.AppendFormat("My Nick is {0} and I am a {1} developer", "Davoleo", "C#");
            //Empties the whole StringBuilder Buffer
            //sb.Clear();
            //Replaces a string with another one in all the occurrences in the StringBuilder
            sb.Replace("e", "E");
            //Removes chars from index 5 (included) to index 7 (excluded)
            sb.Remove(5, 7);
            //Converts the StringBuilder to a String and writes it on the console
            Console.WriteLine(sb.ToString());

            Console.WriteLine("-------------------------------------------------------");

            //Arrays
            int[] randArray;
            int[] randFixedArray = new int[5];
            int[] literalArray   = { 1, 2, 3, 4, 5 };

            //Returns the number of items in the array
            Console.WriteLine("Array Length: " + literalArray.Length);
            //Returns the first item of an array
            Console.WriteLine("First Item: " + literalArray[0]);

            //Loop through arrays

            //Classic For loop with array length
            for (int k = 0; k < literalArray.Length; k++)
            {
                Console.WriteLine("{0} : {1}", k, literalArray[k]);
            }
            //For Each
            foreach (int num in literalArray)
            {
                Console.WriteLine(num);
            }

            //Returns the index of a specific array element
            Console.WriteLine("Index of 3: " + Array.IndexOf(literalArray, 3));

            string[] names = { "Shana", "Alastor", "Wilhelmina", "Decarabia", "Fecor", "Hecate", "Sydonnay" };
            //Joins all the items of an array dividing them with a custom separator
            string nameCollectionString = string.Join(", ", names);

            names = nameCollectionString.Split(',');

            //Multidimensional Arrays
            //Two dimensional empty array of length 5*3
            int[,] multArray = new int[5, 3];

            //Literal Init
            int[,] multArray2 = { { 0, 1 }, { 2, 3 }, { 4, 5 } };

            foreach (int num in multArray2)
            {
                Console.WriteLine(num);
            }

            Console.WriteLine("-------------------------------------------------------");

            //Lists: Dynamic Arrays
            List <int> numList = new List <int>();

            //Adds a Single item to the list
            numList.Add(5);
            numList.Add(15);
            numList.Add(25);

            //Adds a range of items to the list (in some kind of collection form)
            int[] numArray = { 1, 2, 3, 4 };
            numList.AddRange(numArray);

            //Removes All the items in the list
            //numList.Clear();

            //Init a list with an array (aka create a list from an array)
            List <int> numList2 = new List <int>(numArray);

            //Insert an item in a specific index
            numList.Insert(1, 10);

            //Removes the first occurance of the argument in the list, from the list
            numList.Remove(5);
            //Removes the item at the index 2
            numList.RemoveAt(2);

            for (var l = 0; l < numList.Count; l++)
            {
                Console.WriteLine(numList[l]);
            }

            //Returns the index of the first occurance of the passed item (returns -1 if it doesn't find any)
            Console.WriteLine("4 is in index " + numList2.IndexOf(4));

            Console.WriteLine("is 5 in the list " + numList.Contains(5));

            List <string> stringList = new List <string>(new string[] { "Davoleo", "Matpac", "Pierknight" });
            //case insensitive String comparison
            Console.WriteLine("Davoleo in list " + stringList.Contains("davoleo", StringComparer.OrdinalIgnoreCase));

            //Sorts the list alphabetically or numerically depending on the contents
            numList.Sort();

            Console.WriteLine("-------------------------------------------------------");

            #endregion

            #region Exceptions

            //Exception Handling
            //Try and Catch Structure
            try
            {
                Console.Write("Divide 10 by ");
                int num = int.Parse(Console.ReadLine());
                Console.WriteLine("10/{0} = {1}", num, 10 / num);
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Can't divide by 0");
                //Prints the name of the exception
                Console.WriteLine(e.GetType().Name);
                //Prints a small description of the exception
                Console.WriteLine(e.Message);
                //Throws the same exception again
                //throw e;
                //Throws another new Exception
                throw new InvalidOperationException("Operation Failed", e);
            }
            catch (Exception e)
            {
                //This Catches all the exceptions
                Console.WriteLine(e.GetType().Name);
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("-------------------------------------------------------");

            #endregion

            #region OOP

            //Classes and Objects
            Animal botolo = new Animal(0.5, 6, "Meeer", "Botolo");

            Console.WriteLine("{0} says {1}", botolo.Name, botolo.Sound);
            Console.WriteLine(botolo.ToString());
            Console.WriteLine(Animal.GetCount());

            Console.WriteLine("-------------------------------------------------------");

            //Method Overloading test
            //This Calls the int version
            Console.WriteLine("1 + 25 = " + GetSum(1, 25));
            //This Calls the double version
            //Passing parameters in another order
            Console.WriteLine("7.64 + 9.24 = " + GetSum(num2: 7.64, num1: 9.24));

            Console.WriteLine("-------------------------------------------------------");

            //Object Initializer - Assigning values to the fields manually
            Animal epicAnimal = new Animal()
            {
                Name   = "Grover",
                Height = 13,
                Weight = 11,
                Sound  = "GRRR"
            };
            Console.WriteLine(epicAnimal.ToString());

            Console.WriteLine("-------------------------------------------------------");
            //Polymorphism
            Shape rect   = new Rectangle(5, 8);
            Shape tri    = new Triangle(8, 3);
            Shape circle = new Circle(5);

            //Array of different kinds of shapes
            Shape[] shapeArray = { rect, tri, circle };

            foreach (var shape in shapeArray)
            {
                shape.LogShapeInfo();
            }
            Console.WriteLine("***");

            Console.WriteLine("Rect Area: " + rect.Area());
            Console.WriteLine("Tri Area: " + tri.Area());
            Console.WriteLine("Circle Area: " + circle.Area());
            Console.WriteLine("tri is a Triangle: " + (tri is Triangle));
            Console.WriteLine("rect is a Rectangle: " + ((rect as Rectangle) != null));
            Console.WriteLine("-------------------------------------------------------");

            //Operator Overloading for objects
            Rectangle combinedRectangle = new Rectangle(6, 10) + (Rectangle)rect;
            Console.WriteLine("combinedRectangle Area: " + combinedRectangle.Area());

            Console.WriteLine("-------------------------------------------------------");

            //Interfaces
            IElettronicDevice TV          = TVRemote.GetDevice();
            PowerButton       powerButton = new PowerButton(TV);
            powerButton.Execute();
            powerButton.Undo();

            Console.WriteLine("-------------------------------------------------------");

            //Generics - Classes that can be used with any kind of object
            SimpleMapEntry <int, string> davPass = new SimpleMapEntry <int, string>(333, "Davoleo");

            davPass.ShowData();

            //Generics work with multiple data types
            int firstInt = 5, secondInt = 4;
            GetSum(ref firstInt, ref secondInt);
            string firstString  = firstInt.ToString();
            string secondString = secondInt.ToString();
            GetSum(ref firstString, ref secondString);

            Rectangle <int> rect1 = new Rectangle <int>(20, 50);
            Console.WriteLine(rect1.GetArea());
            Rectangle <string> rect2 = new Rectangle <string>("20", "50");
            Console.WriteLine(rect2.GetArea());

            Console.WriteLine("-------------------------------------------------------");

            Temperature waveTemp = Temperature.WARM;

            switch (waveTemp)
            {
            case Temperature.FREEZE:
                Console.WriteLine("Freezing Temperature");
                break;

            case Temperature.LOW:
                Console.WriteLine("Low Temperature");
                break;

            case Temperature.WARM:
                Console.WriteLine("Warm Temperature");
                break;

            case Temperature.HOT:
                Console.WriteLine("Hot Temperature");
                break;

            case Temperature.SEARING:
                Console.WriteLine("EPIC Temperature, everything Sublimates");
                break;

            default:
                Console.WriteLine("Invalid Temperature");
                break;
            }

            Console.WriteLine("-------------------------------------------------------");

            //STRUCTS
            Customer davoleo = new Customer();
            davoleo.createCustomer("Davoleo", 55.80, 111);
            davoleo.printInfo();

            Console.WriteLine("-------------------------------------------------------");
            //DELEGATES - Passing methods to other methods as parameters

            //Anonymous method of type EvaluateExpression
            EvaluateExpression add = delegate(double n1, double n2) { return(n1 + n2); };
            //Direct Delegate Assignment
            EvaluateExpression substract = (n1, n2) => { return(n1 + n2); };
            EvaluateExpression multiply  = delegate(double n1, double n2) { return(n1 * n2); };

            //Calls both the delegates
            EvaluateExpression subtractMultuply = substract + multiply;

            Console.WriteLine("5 + 10 = " + add(5, 10));
            Console.WriteLine("5 * 10 = " + multiply(5, 10));
            Console.WriteLine("Subtract & Multiply 10 & 4: " + subtractMultuply(10, 4));

            //Lamda expressions - Anonymous functions
            Func <int, int, int> subtract = (x, y) => x - y;
            Console.WriteLine("5 - 10 = " + subtract.Invoke(5, 10));

            List <int> nums = new List <int> {
                3, 6, 9, 12, 15, 18, 21, 24, 27, 30
            };
            List <int> oddNumbers = nums.Where((n) => n % 2 == 1).ToList();

            foreach (var oddNumber in oddNumbers)
            {
                Console.Write(oddNumber + ", ");
            }
            Console.WriteLine();
            Console.WriteLine("-------------------------------------------------------");

            #endregion


            #region File IO

            //File I/O
            //Access the current directory
            DirectoryInfo dir    = new DirectoryInfo(".");
            DirectoryInfo davDir = new DirectoryInfo(@"C:\Users\Davoleo");

            Console.WriteLine("Davoleo path: " + davDir.FullName);
            Console.WriteLine("Davoleo dir name " + davDir.Name);
            Console.WriteLine(davDir.Parent);
            Console.WriteLine(davDir.Attributes);
            Console.WriteLine(davDir.CreationTime);

            //Creates a directory
            Directory.CreateDirectory(@"D:\C#Data");
            DirectoryInfo dataDir = new DirectoryInfo(@"D:\C#Data");
            //Directory.Delete(@"D:\C#Data");
            string dataPath = @"D:\C#Data";
            Console.WriteLine("-------------------------------------------------------");

            string[] nicks = { "Davoleo", "Matpac", "Pierknight", "gesudio" };

            using (StreamWriter writer = new StreamWriter("nicknames.txt"))
            {
                foreach (var nick in nicks)
                {
                    writer.WriteLine(nick);
                }
            }

            using (StreamReader reader = new StreamReader("nicknames.txt"))
            {
                string user;
                while ((user = reader.ReadLine()) != null)
                {
                    Console.WriteLine(user);
                }
            }

            //Another Way of writing and reading
            File.WriteAllLines(dataPath + "\\nicknames.txt", nicks);
            Console.WriteLine(File.ReadAllBytes(dataPath + "\\nicknames.txt").ToString());

            FileInfo[] textFiles = dataDir.GetFiles("*.txt", SearchOption.AllDirectories);
            Console.WriteLine("Matches: {0}" + textFiles.Length);

            Console.WriteLine(textFiles[0].Name + ", " + textFiles[0].Length);

            string     fileStreamPath   = @"D:\C#Data\streamtest.txt";
            FileStream stream           = File.Open(fileStreamPath, FileMode.Create);
            string     randomString     = "This is a random String";
            byte[]     randomStringByte = Encoding.Default.GetBytes(randString);
            stream.Write(randomStringByte, 0, randomStringByte.Length);
            stream.Position = 0;
            stream.Close();

            string       binaryPath   = @"D:\C#Data\file.dat";
            FileInfo     datFile      = new FileInfo(binaryPath);
            BinaryWriter binaryWriter = new BinaryWriter(datFile.OpenWrite());
            string       text         = "Random Text";
            age = 18;
            double height = 12398;

            binaryWriter.Write(text);
            binaryWriter.Write(age);
            binaryWriter.Write(height);

            binaryWriter.Close();

            BinaryReader binaryReader = new BinaryReader(datFile.OpenRead());
            Console.WriteLine(binaryReader.ReadString());
            Console.WriteLine(binaryReader.ReadInt32());
            Console.WriteLine(binaryReader.ReadDouble());

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            //OOP Game test
            Warrior maximus = new Warrior("Maximus", 1000, 120, 40);
            Warrior bob     = new Warrior("Bob", 1000, 120, 40);

            Console.WriteLine("Disabled");
            //Battle.StartFight(maximus, bob);

            Console.WriteLine("-------------------------------------------------------");

            //Collections ----

            #region ArrayList

            //You can add different kind of objects ArrayLists
            ArrayList arrayList = new ArrayList();
            arrayList.Add("Bob");
            arrayList.Add(43);

            //Number of items in the arraylist
            Console.WriteLine("ArrayList Count: " + arrayList.Count);
            //Capacity is always double the count (?)
            Console.WriteLine("ArrayList Capacity: " + arrayList.Capacity);

            ArrayList arrayList2 = new ArrayList();
            //Add an array to the ArrayList
            arrayList2.AddRange(new object[] { "Jeff", "Dave", "Egg", "Edge" });

            arrayList.AddRange(arrayList2);

            //Sort items in natural order
            arrayList2.Sort();
            //Reverse the order of items
            arrayList2.Reverse();

            //Insert some item at a specific index
            arrayList2.Insert(1, "PI");

            //Sub-Arraylist made of some of the items in the original arraylist
            ArrayList range = arrayList2.GetRange(0, 2);

            Console.WriteLine("arrayList object ---");
            foreach (object o in arrayList)
            {
                Console.Write(o + "\t");
            }
            Console.WriteLine();

            Console.WriteLine("arrayList2 object ---");
            foreach (object o in arrayList2)
            {
                Console.Write(o + "\t");
            }
            Console.WriteLine();

            Console.WriteLine("range object ----");
            foreach (object o in range)
            {
                Console.Write(o + "\t");
            }
            Console.WriteLine();

            //Remove the item at the 0 index
            //arrayList2.RemoveAt(0);

            //Removes the first 2 items starting from index 0
            //arrayList2.RemoveRange(0, 2);

            //Return the index of a specific object - if it doesn't find any it returns -1
            Console.WriteLine("Index of Edge: " + arrayList2.IndexOf("Edge"));

            //Converting ArrayLists to arrays
            string[] array = (string[])arrayList2.ToArray(typeof(string));

            //Converting back to Arraylist
            ArrayList listFromArray = new ArrayList(array);

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            #region Dictionary

            //Stores a list of key-value pairs
            Dictionary <string, string> langsProjs = new Dictionary <string, string>();

            //Add A Key-Value Pair
            langsProjs.Add("C#", "CSharp-Test");
            langsProjs.Add("Java", "Metallurgy 4: Reforged");
            langsProjs.Add("Dart", "sample_flutter_app");

            //Removes a Pair from a given key
            langsProjs.Remove("Dart");

            //Number of pairs in the list
            Console.WriteLine("Count: " + langsProjs.Count);

            //Returns wether a key is present
            Console.WriteLine("C# is present: " + langsProjs.ContainsKey("C#"));

            //Gets the value of Java and outputs into a new string called test
            langsProjs.TryGetValue("Java", out string test);
            Console.WriteLine("Java: " + test);

            //Loop over all the pairs in the list
            Console.WriteLine("LOOP:");
            foreach (KeyValuePair <string, string> pair in langsProjs)
            {
                Console.WriteLine($"{pair.Key} - {pair.Value}");
            }

            //Empties the dictionary Completely
            langsProjs.Clear();

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            #region Queue

            //Creates a new Empty Queue
            Queue queue = new Queue();

            //Adds an item to the queue
            queue.Enqueue(1);
            queue.Enqueue(2);
            queue.Enqueue(3);

            //Loop over a queue
            foreach (object num in queue)
            {
                Console.Write(num + "\t");
            }
            Console.WriteLine();

            Console.WriteLine("is 3 in the queue: " + queue.Contains(3));

            //Removes the first item and return it to you
            Console.WriteLine("Removes 1: " + queue.Dequeue());

            //Returns the first item in the queue without removing it
            Console.WriteLine("Peek the firs num: " + queue.Peek());

            //Empties the queue
            queue.Clear();

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            #region Stack

            Stack stack = new Stack();

            //Adds an item to the stack
            stack.Push(1);
            stack.Push(2);
            stack.Push(3);
            stack.Push(4);

            //Loop over a stack - items are returned in the opposite order
            foreach (var item in stack)
            {
                Console.WriteLine($"Item: {item}");
            }

            //Returns the last item in the stack without removing it
            Console.WriteLine(stack.Peek());

            //Returns the last item in the stack removing it
            Console.WriteLine(stack.Pop());

            //Returns wether the stack contains an item or not
            Console.WriteLine(stack.Contains(3));

            //Convert to an array and print it with the Join function
            Console.WriteLine(string.Join(", ", stack.ToArray()));

            //Empties the stack
            stack.Clear();

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            #region LINQ EXTENSION METHODS
            //LINQ EXTENSION METHODS

            //Lamdas with Delegates
            Console.WriteLine("-- Lambda Expressions --");
            doubleIt doubleIt = x => x * 2;
            Console.WriteLine($"5 * 2 = {doubleIt(5)}");

            List <int> numberList = new List <int> {
                1, 9, 2, 6, 3
            };

            //.Where() METHOD
            var evenList = numberList.Where(a => a % 2 == 0).ToList();
            foreach (var k in evenList)
            {
                Console.Write(k + ", ");
            }
            Console.WriteLine();

            //2nd Example of .Where()
            var rangeList = numberList.Where(x => x > 2 && x < 9).ToList();
            foreach (var k in rangeList)
            {
                Console.Write(k + ", ");
            }
            Console.WriteLine();

            //Coin flips (T = 0 or C = 1)
            List <int> coinFlips = new List <int>();
            int        flips     = 0;
            while (flips < 100)
            {
                coinFlips.Add(rand.Next(0, 2));
                flips++;
            }
            //Count method with predicate
            Console.WriteLine($"Testa Count: {coinFlips.Count(a => a == 0)}");
            Console.WriteLine($"Croce Count: {coinFlips.Count(a => a == 1)}");

            //.Select() METHOD
            var oneToTen = new List <int>();
            oneToTen.AddRange(Enumerable.Range(1, 10));
            var squares = oneToTen.Select(x => x * x);

            foreach (var k in squares)
            {
                Console.Write(k + ", ");
            }
            Console.WriteLine();

            //.Zip() METHOD
            var listOne = new List <int> {
                1, 3, 4
            };
            var listTwo = new List <int> {
                4, 6, 8
            };
            var sumList = listOne.Zip(listTwo, (l1Value, l2Value) => l1Value + l2Value);
            foreach (var k in sumList)
            {
                Console.Write(k + ", ");
            }
            Console.WriteLine();

            //.Aggregate() METHOD
            var nums1to5 = new List <int> {
                1, 2, 3, 4, 5
            };
            Console.WriteLine("Sum of elements {0}", nums1to5.Aggregate((a, b) => a + b));

            //.AsQueryable.Average() Method
            Console.WriteLine($"Average: {nums1to5.AsQueryable().Average()}");
            //.All()
            Console.WriteLine($"All > 3 nums? {nums1to5.All(x => x > 3)}");
            //.Any()
            Console.WriteLine($"Any num > 3? {nums1to5.Any(x => x > 3)}");

            //.Distinct()
            var listWithDupes = new List <int> {
                1, 2, 3, 2, 3
            };
            Console.WriteLine($"Distinct: {string.Join(", ", listWithDupes.Distinct())}");

            //.Except() - Prints all the values that don't exist in the second list
            Console.WriteLine($"Except: {string.Join(", ", nums1to5.Except(listWithDupes))}");

            //.Intersect() - Returns a list with common values between two lists
            Console.WriteLine($"Intersect: {string.Join(", ", nums1to5.Intersect(listWithDupes))}");

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            #region Custom Collection Class

            AnimalFarm animals = new AnimalFarm();
            animals[0] = new Animal("Wilbur");
            animals[1] = new Animal("Templeton");
            animals[2] = new Animal("Wally");
            animals[3] = new Animal("ooooooooooooooooooooooooeuf");

            foreach (Animal animal in animals)
            {
                Console.WriteLine(animal.Name);
            }

            Box box1 = new Box(2, 3, 4);
            Box box2 = new Box(5, 6, 7);


            Box boxSum = box1 + box2;
            Console.WriteLine($"Box Sum: {boxSum}");

            Console.WriteLine($"Box -> Int: {(int) box1}");
            Console.WriteLine($"Int -> Box: {(Box) 4}");

            //Anonymous type object
            var anonymous = new
            {
                Name   = "Mr Unknown",
                Status = 312
            };

            Console.WriteLine("{0} status is {1}", anonymous.Name, anonymous.Status);

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            #region LINQ

            //Stands for Launguage Integrated Query - Provides tools to work with data
            QueryStringArray();

            QueryIntArray();

            QueryArrayList();

            QueryCollection();

            QueryAnimalData();

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            #region Threads

            //Threading allows to execute operation on a different workflow instead of the Main one
            //The workflow continuously and quickly changes thread to

            Thread thread = new Thread(Print1);
            thread.Start();

            for (int k = 0; k < 1000; k++)
            {
                Console.Write(0);
            }
            Console.WriteLine();

            int counter = 1;
            for (int k = 0; k < 10; k++)
            {
                Console.WriteLine(counter);
                //Slow down the current thread of some time in ms
                Thread.Sleep(500);
                counter++;
            }
            Console.WriteLine("Thread Ended");

            BankAccount account = new BankAccount(10);
            Thread[]    threads = new Thread[15];

            Thread.CurrentThread.Name = "main";

            for (int k = 0; k < threads.Length; k++)
            {
                Thread smolThread = new Thread(account.IssueWidthDraw);
                smolThread.Name = k.ToString();
                threads[k]      = smolThread;
            }

            foreach (var smolThread in threads)
            {
                Console.WriteLine("Thread {0} Alive: {1}", smolThread.Name, smolThread.IsAlive);
                smolThread.Start();
                Console.WriteLine("Thread {0} Alive: {1}", smolThread.Name, smolThread.IsAlive);
            }

            Console.WriteLine("Current Priority: " + Thread.CurrentThread.Priority);
            Console.WriteLine($"Thread {Thread.CurrentThread.Name} Ending");

            // Passing data to threads through lambda expressions
            new Thread(() =>
            {
                countTo(5);
                countTo(8);
            }).Start();

            #endregion

            Console.WriteLine("-------------------------------------------------------");

            #region Serialization

            Animal dummyDum    = new Animal(45, 25, "Roar", "Dum");
            Stream dummyStream = File.Open("AnimalData.dat", FileMode.Create);

            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(dummyStream, dummyDum);
            dummyStream.Close();

            dummyDum = null;

            dummyStream     = File.Open("AnimalData.dat", FileMode.Open);
            binaryFormatter = new BinaryFormatter();

            dummyDum = (Animal)binaryFormatter.Deserialize(dummyStream);
            dummyStream.Close();

            Console.WriteLine("Dummy Dum from binary: " + dummyDum.ToString());

            dummyDum.Weight = 33;
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(Animal));

            using (TextWriter tw = new StreamWriter(@"D:\C#Data\dummy-dum.xml"))
            {
                xmlSerializer.Serialize(tw, dummyDum);
            }

            dummyDum = null;

            XmlSerializer xmlDeserializer = new XmlSerializer(typeof(Animal));
            TextReader    txtReader       = new StreamReader(@"D:\C#Data\dummy-dum.xml");
            object        obj             = xmlDeserializer.Deserialize(txtReader);
            dummyDum = (Animal)obj;
            txtReader.Close();

            Console.WriteLine("Dummy Dum from XML: " + dummyDum.ToString());

            #endregion
        }
        public virtual void Visit(IHTMLDocument3 document)
        {
            if (Application.MessageLoop)
            {
                Application.DoEvents();
            }

            //			while (((IHTMLDocument2)document).readyState != "interactive")
            //			{
            //				Application.DoEvents();
            //				Thread.Sleep(50);
            //			}

            //Trace.WriteLine("Begin visit: " + ((IHTMLDocument2)document).readyState + "\r\n" + document.documentElement.innerHTML);

            Stack stack = new Stack();

            stack.Push(new StackItem(document.documentElement));

            while (stack.Count > 0)
            {
                StackItem stackItem = (StackItem)stack.Pop();

                if (stackItem.element == null)
                {
                    continue;
                }
                else if (stackItem.element is IHTMLTextElement)
                {
                    OnText((IHTMLTextElement)stackItem.element);
                }
                else if (stackItem.element is IHTMLCommentElement)
                {
                    OnComment((IHTMLCommentElement)stackItem.element);
                }
                else if (stackItem.element is IHTMLElement)
                {
                    IHTMLElement el = (IHTMLElement)stackItem.element;

                    if (stackItem.begin)
                    {
                        if (!OnElementBegin(el))
                        {
                            //							Trace.WriteLine(Indent + "<" + el + "/> (skipping)");
                            continue;
                        }

                        //						Trace.WriteLine(Indent + "<" + el + "> (children: " + ((IHTMLElementCollection)el.children).length);
                        IncreaseIndent();

                        stackItem.begin = false;
                        // return item to the stack, so we can call OnElementEnd on the way out
                        stack.Push(stackItem);

                        // DO NOT iterate over the DOM this way.  We miss a lot of nodes in Release mode.
                        //						IHTMLElementCollection children = (IHTMLElementCollection)el.children;
                        //						StackItem[] items = new StackItem[children.length];
                        //						int i = 0;
                        //						foreach (IHTMLElement child in children)
                        //							items[i++] = new StackItem(child);
                        //						Array.Reverse(items);

                        ArrayList items = new ArrayList();
                        for (IHTMLDOMNode child = ((IHTMLDOMNode)el).firstChild; child != null; child = child.nextSibling)
                        {
                            IHTMLElement childElement = child as IHTMLElement;
                            if (childElement != null)
                            {
                                items.Add(new StackItem(childElement));
                            }
                        }
                        items.Reverse();

                        foreach (StackItem si in items)
                        {
                            stack.Push(si);
                        }
                    }
                    else
                    {
                        DecreaseIndent();
                        //						Trace.WriteLine(Indent + "</" + el.tagName + ">");
                        OnElementEnd(el);
                    }
                }
            }

            //Trace.WriteLine("End visit");
        }
Example #43
0
        public void Test02()
        {
            //--------------------------------------------------------------------------
            // Variable definitions.
            //--------------------------------------------------------------------------
            ArrayList arrList = null;

            string[] strHeroes =
            {
                "Aquaman",
                "Atom",
                "Batman",
                "Black Canary",
                "Captain America",
                "Captain Atom",
                "Catwoman",
                "Cyborg",
                "Flash",
                "Green Arrow",
                "Green Lantern",
                "Hawkman",
                "Huntress",
                "Ironman",
                "Nightwing",
                "Robin",
                "SpiderMan",
                "Steel",
                "Superman",
                "Thor",
                "Wildcat",
                "Wonder Woman",
            };

            //
            // Construct array list.
            //
            arrList = new ArrayList((ICollection)strHeroes);

            //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of 
            //BinarySearch, Following variable cotains each one of these types of array lists

            ArrayList[] arrayListTypes = {
                                        (ArrayList)arrList.Clone(),
                                        (ArrayList)ArrayList.Adapter(arrList).Clone(),
                                        (ArrayList)ArrayList.FixedSize(arrList).Clone(),
                                        (ArrayList)arrList.GetRange(0, arrList.Count).Clone(),
                                        (ArrayList)ArrayList.Synchronized(arrList).Clone()};

            foreach (ArrayList arrayListType in arrayListTypes)
            {
                arrList = arrayListType;

                //
                // []  Reverse entire array list.
                //
                // Reverse entire array list.
                arrList.Reverse();

                // Verify items have been reversed.
                for (int ii = 0; ii < arrList.Count; ++ii)
                {
                    Assert.Equal(0, strHeroes[ii].CompareTo((String)arrList[arrList.Count - ii - 1]));
                }

                //[]Team review feedback - Reversing lists of varying sizes inclusing 0
                arrList = new ArrayList();
                arrList.Reverse();

                arrList = new ArrayList();
                for (int i = 0; i < 1; i++)
                    arrList.Add(i);

                arrList.Reverse();
            }
        }
 public void Reverse()
 {
     _list.Reverse();
 }
Example #45
0
    private void CompareObjects(ArrayList good, ArrayList bad, Hashtable hsh1)
    {
        //IList, this includes ICollection tests as well!!
        DoIListTests(good, bad, hsh1);

        //we will now test ArrayList specific methods
        good.Clear();
        for (int i = 0; i < 100; i++)
            good.Add(i);

        //AL's CopyTo methods
        int[] iArr1 = null;
        int[] iArr2 = null;
        iArr1 = new int[100];
        iArr2 = new int[100];
        good.CopyTo(iArr1);
        bad.CopyTo(iArr2);
        for (int i = 0; i < 100; i++)
        {
            if (iArr1[i] != iArr2[i])
                hsh1["CopyTo"] = "()";
        }

        iArr1 = new int[100];
        iArr2 = new int[100];
        good.CopyTo(0, iArr1, 0, 100);
        try
        {
            bad.CopyTo(0, iArr2, 0, 100);
            for (int i = 0; i < 100; i++)
            {
                if (iArr1[i] != iArr2[i])
                    hsh1["CopyTo"] = "()";
            }
        }
        catch
        {
            hsh1["CopyTo"] = "(int, Array, int, int)";
        }

        iArr1 = new int[200];
        iArr2 = new int[200];
        for (int i = 0; i < 200; i++)
        {
            iArr1[i] = 50;
            iArr2[i] = 50;
        }

        good.CopyTo(50, iArr1, 100, 20);
        try
        {
            bad.CopyTo(50, iArr2, 100, 20);
            for (int i = 0; i < 200; i++)
            {
                if (iArr1[i] != iArr2[i])
                    hsh1["CopyTo"] = "(Array, int, int)";
            }
        }
        catch
        {
            hsh1["CopyTo"] = "(int, Array, int, int)";
        }

        //Clone()
        ArrayList alstClone = (ArrayList)bad.Clone();
        //lets make sure that the clone is what it says it is
        if (alstClone.Count != bad.Count)
            hsh1["Clone"] = "Count";
        for (int i = 0; i < bad.Count; i++)
        {
            if (alstClone[i] != bad[i])
                hsh1["Clone"] = "[]";
        }

        //GerEnumerator()
        IEnumerator ienm1 = null;
        IEnumerator ienm2 = null;

        ienm1 = good.GetEnumerator(0, 100);
        try
        {
            ienm2 = bad.GetEnumerator(0, 100);
            DoIEnumerableTest(ienm1, ienm2, good, bad, hsh1, false);
        }
        catch
        {
            hsh1["GetEnumerator"] = "(int, int)";
        }

        ienm1 = good.GetEnumerator(50, 50);
        try
        {
            ienm2 = bad.GetEnumerator(50, 50);
            DoIEnumerableTest(ienm1, ienm2, good, bad, hsh1, false);
        }
        catch
        {
            hsh1["GetEnumerator"] = "(int, int)";
        }

        try
        {
            bad.GetEnumerator(50, 150);
            hsh1["GetEnumerator"] = "(int, int)";
        }
        catch (Exception)
        {
        }

        ienm1 = good.GetEnumerator(0, 100);
        try
        {
            ienm2 = bad.GetEnumerator(0, 100);
            good.RemoveAt(0);
            DoIEnumerableTest(ienm1, ienm2, good, bad, hsh1, true);
        }
        catch
        {
            hsh1["GetEnumerator"] = "(int, int)";
        }

        //GetRange
        good.Clear();
        for (int i = 0; i < 100; i++)
            good.Add(i);

        ArrayList alst1 = good.GetRange(0, good.Count);
        try
        {
            ArrayList alst2 = bad.GetRange(0, good.Count);
            for (int i = 0; i < good.Count; i++)
            {
                if (alst1[i] != alst2[i])
                    hsh1["GetRange"] = i;
            }
        }
        catch
        {
            hsh1["Range"] = "(int, int)";
        }

        //IndexOf(Object, int)

        if (bad.Count > 0)
        {
            for (int i = 0; i < good.Count; i++)
            {
                if (good.IndexOf(good[i], 0) != bad.IndexOf(good[i], 0))
                {
                    hsh1["IndexOf"] = "(Object, int)";
                }
                if (good.IndexOf(good[i], i) != bad.IndexOf(good[i], i))
                {
                    hsh1["IndexOf"] = "(Object, int)";
                }
                if (i < (good.Count - 1))
                {
                    if (good.IndexOf(good[i], i + 1) != bad.IndexOf(good[i], i + 1))
                    {
                        hsh1["IndexOf"] = "(Object, int)";
                    }
                }
            }

            try
            {
                bad.IndexOf(1, -1);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["IndexOf"] = ex;
            }

            try
            {
                bad.IndexOf(1, bad.Count);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["IndexOf"] = ex;
            }

            // IndexOf(Object, int, int)
            // The semantics of this method has changed, the 3rd parameter now refers to count instead of length
            for (int i = 0; i < good.Count; i++)
            {
                if (good.IndexOf(good[i], 0, good.Count - 1) != bad.IndexOf(good[i], 0, good.Count - 1))
                {
                    hsh1["IndexOf"] = "(Object, int, int)";
                }
                if (good.IndexOf(good[i], i, good.Count - i) != bad.IndexOf(good[i], i, good.Count - i))
                {
                    hsh1["IndexOf"] = "(Object, int)";
                }
                if (good.IndexOf(good[i], i, 0) != bad.IndexOf(good[i], i, 0))
                {
                    hsh1["IndexOf"] = "(Object, int)";
                }
                if (i < (good.Count - 1))
                {
                    if (good.IndexOf(good[i], i + 1, good.Count - (i + 1)) != bad.IndexOf(good[i], i + 1, good.Count - (i + 1)))
                    {
                        hsh1["IndexOf"] = "(Object, int)";
                    }
                }
            }

            try
            {
                bad.IndexOf(1, 0, -1);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["IndexOf"] = ex;
            }

            try
            {
                bad.IndexOf(1, 0, bad.Count);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["IndexOf"] = ex;
            }

            try
            {
                bad.IndexOf(1, bad.Count - 1, bad.Count - 2);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["IndexOf"] = ex;
            }

            //LastIndexOf(Object)
            for (int i = 0; i < good.Count; i++)
            {
                if (good.LastIndexOf(good[i]) != bad.LastIndexOf(good[i]))
                {
                    hsh1["LastIndexOf"] = "(Object)";
                }
                if (good.LastIndexOf(i + 1000) != bad.LastIndexOf(i + 1000))
                {
                    hsh1["LastIndexOf"] = "(Object)";
                }
            }

            try
            {
                bad.LastIndexOf(null);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["LastIndexOf"] = ex;
            }

            //LastIndexOf(Object, int)
            for (int i = 0; i < good.Count; i++)
            {
                if (good.LastIndexOf(good[i], good.Count - 1) != bad.LastIndexOf(good[i], good.Count - 1))
                {
                    hsh1["LastIndexOf"] = "(Object, int)";
                }
                if (good.LastIndexOf(good[i], 0) != bad.LastIndexOf(good[i], 0))
                {
                    hsh1["LastIndexOf"] = "(Object, int)";
                }
                if (good.LastIndexOf(good[i], i) != bad.LastIndexOf(good[i], i))
                {
                    hsh1["LastIndexOf"] = "(Object, int)";
                }
                if (i < (good.Count - 1))
                {
                    if (good.LastIndexOf(good[i], i + 1) != bad.LastIndexOf(good[i], i + 1))
                    {
                        hsh1["LastIndexOf"] = "(Object, int)";
                    }
                }
            }

            try
            {
                bad.LastIndexOf(1, -1);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["LastIndexOf"] = ex;
            }

            try
            {
                bad.LastIndexOf(1, bad.Count);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["LastIndexOf"] = ex;
            }

            //LastIndexOf(Object, int, int)
            for (int i = 0; i < good.Count; i++)
            {
                if (good.LastIndexOf(good[i], good.Count - 1, 0) != bad.LastIndexOf(good[i], good.Count - 1, 0))
                {
                    hsh1["LastIndexOf"] = "(Object, int, int)";
                }
                if (good.LastIndexOf(good[i], good.Count - 1, i) != bad.LastIndexOf(good[i], good.Count - 1, i))
                {
                    hsh1["LastIndexOf"] = "(Object, int)";
                }
                if (good.LastIndexOf(good[i], i, i) != bad.LastIndexOf(good[i], i, i))
                {
                    hsh1["LastIndexOf"] = "(Object, int)";
                }
                if (i < (good.Count - 1))
                {
                    if (good.LastIndexOf(good[i], good.Count - 1, i + 1) != bad.LastIndexOf(good[i], good.Count - 1, i + 1))
                    {
                        hsh1["LastIndexOf"] = "(Object, int)";
                    }
                }
            }

            try
            {
                bad.LastIndexOf(1, 1, -1);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["LastIndexOf"] = ex;
            }

            try
            {
                bad.LastIndexOf(1, bad.Count - 2, bad.Count - 1);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["LastIndexOf"] = ex;
            }
        }

        //ReadOnly()
        ArrayList alst3 = ArrayList.ReadOnly(bad);
        if (!alst3.IsReadOnly)
            hsh1["ReadOnly"] = "Not";

        IList ilst1 = ArrayList.ReadOnly((IList)bad);
        if (!ilst1.IsReadOnly)
            hsh1["ReadOnly"] = "Not";

        //Synchronized()
        alst3 = ArrayList.Synchronized(bad);
        if (!alst3.IsSynchronized)
            hsh1["Synchronized"] = "Not";

        ilst1 = ArrayList.Synchronized((IList)bad);
        if (!ilst1.IsSynchronized)
            hsh1["Synchronized"] = "Not";

        //ToArray()
        if (good.Count == bad.Count)
        {
            object[] oArr1 = good.ToArray();
            object[] oArr2 = bad.ToArray();
            for (int i = 0; i < good.Count; i++)
            {
                if ((int)oArr1[i] != (int)oArr2[i])
                    hsh1["ToArray"] = "()";
            }

            //ToArray(type)
            iArr1 = (int[])good.ToArray(typeof(int));
            iArr2 = (int[])bad.ToArray(typeof(int));
            for (int i = 0; i < good.Count; i++)
            {
                if (iArr1[i] != iArr2[i])
                    hsh1["ToArray"] = "(Type)";
            }
        }

        //Capacity - get
        if (good.Capacity != bad.Capacity)
        {
            hsh1["Capacity"] = "get";
        }

        //Fixed size methods
        if (!hsh1.ContainsKey("IsReadOnly"))
        {
            good.Clear();
            for (int i = 100; i > 0; i--)
                good.Add(i);
            //Sort() & BinarySearch(Object)
            bad.Sort();
            for (int i = 0; i < bad.Count - 1; i++)
            {
                if ((int)bad[i] > (int)bad[i + 1])
                    hsh1["Sort"] = "()";
            }

            for (int i = 0; i < bad.Count; i++)
            {
                if (bad.BinarySearch(bad[i]) != i)
                    hsh1["BinarySearch"] = "(Object)";
            }

            //Reverse()
            bad.Reverse();
            if (bad.Count > 0)
            {
                for (int i = 0; i < 99; i++)
                {
                    if ((int)bad[i] < (int)bad[i + 1])
                        hsh1["Reverse"] = "()";
                }

                good.Clear();
                for (int i = 100; i > 0; i--)
                    good.Add(i.ToString());
            }

            good.Clear();
            for (int i = 90; i > 64; i--)
                good.Add(((Char)i).ToString());

            try
            {
                bad.Sort(new CaseInsensitiveComparer());
                if (bad.Count > 0)
                {
                    for (int i = 0; i < (bad.Count - 1); i++)
                    {
                        if (((String)bad[i]).CompareTo(((String)bad[i + 1])) >= 0)
                            hsh1["Sort"] = "(IComparer)";
                    }
                    for (int i = 0; i < bad.Count; i++)
                    {
                        if (bad.BinarySearch(bad[i], new CaseInsensitiveComparer()) != i)
                            hsh1["BinarySearch"] = "(Object, IComparer)";
                    }
                }
                bad.Reverse();

                good.Clear();
                for (int i = 65; i < 91; i++)
                    good.Add(((Char)i).ToString());

                if (bad.Count > 0)
                {
                    for (int i = 0; i < good.Count; i++)
                    {
                        if (bad.BinarySearch(0, bad.Count, bad[i], new CaseInsensitiveComparer()) != i)
                            hsh1["BinarySearch"] = "(int, int, Object, IComparer)";
                    }
                }
            }
            catch (Exception)
            {
            }

            good.Clear();
            for (int i = 0; i < 100; i++)
                good.Add(i);

            Queue que = new Queue();
            for (int i = 0; i < 100; i++)
                que.Enqueue(i + 5000);

            try
            {
                bad.SetRange(0, que);
            }
            catch (Exception ex)
            {
                hsh1["SetRange"] = "Copy_ExceptionType, " + ex.GetType().Name;
            }
            for (int i = bad.Count; i < bad.Count; i++)
            {
                if ((int)bad[i] != (i + 5000))
                {
                    hsh1["SetRange"] = i;
                }
            }
        }
        else
        {
            //we make sure that the above methods throw here
            good.Clear();
            for (int i = 100; i > 0; i--)
                good.Add(i);

            try
            {
                bad.Sort();
                hsh1["Sort"] = "Copy";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception)
            {
                hsh1["Sort"] = "Copy_ExceptionType";
            }

            try
            {
                bad.Reverse();
                hsh1["Reverse"] = "Copy";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception ex)
            {
                hsh1["Reverse"] = "Copy_ExceptionType, " + ex.GetType().Name;
            }

            try
            {
                bad.Sort(new CaseInsensitiveComparer());
                hsh1["Sort"] = "Copy - Icomparer";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception)
            {
                hsh1["Sort"] = "Copy_ExceptionType";
            }

            try
            {
                bad.Sort(0, 0, new CaseInsensitiveComparer());
                hsh1["Sort"] = "Copy - int, int, IComparer";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception)
            {
                hsh1["Sort"] = "Copy_ExceptionType";
            }

            //BinarySearch
            try
            {
                for (int i = 0; i < bad.Count; i++)
                {
                    if (bad.BinarySearch(bad[i]) != i)
                        hsh1["BinarySearch"] = "(Object)";
                }
                hsh1["BinarySearch"] = "(Object)";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception ex)
            {
                hsh1["BinarySearch"] = ex.GetType().Name;
            }

            try
            {
                for (int i = 0; i < bad.Count; i++)
                {
                    if (bad.BinarySearch(bad[i], new CaseInsensitiveComparer()) != i)
                        hsh1["BinarySearch"] = "(Object)";
                }

                hsh1["BinarySearch"] = "Exception not thrown, (Object, IComparer)";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception ex)
            {
                hsh1["BinarySearch"] = ex.GetType().Name;
            }

            try
            {
                for (int i = 0; i < bad.Count; i++)
                {
                    if (bad.BinarySearch(0, bad.Count, bad[i], new CaseInsensitiveComparer()) != i)
                        hsh1["BinarySearch"] = "(Object)";
                }

                hsh1["BinarySearch"] = "Exception not thrown, (Object, IComparer)";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception ex)
            {
                hsh1["BinarySearch"] = ex.GetType().Name;
            }

            good.Clear();
            for (int i = 0; i < 100; i++)
                good.Add(i);

            Queue que = new Queue();
            for (int i = 0; i < 100; i++)
                que.Enqueue(i + 5000);

            try
            {
                bad.SetRange(0, que);
                hsh1["Sort"] = "Copy - int, int, IComparer";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception)
            {
                hsh1["Sort"] = "Copy_ExceptionType";
            }
        }

        //Modifiable methods
        if (!hsh1.ContainsKey("IsReadOnly") && !hsh1.ContainsKey("Fixed"))
        {
            good.Clear();
            for (int i = 0; i < 100; i++)
                good.Add(i);

            Queue que = new Queue();
            for (int i = 0; i < 100; i++)
                que.Enqueue(i + 5000);
            bad.InsertRange(0, que);
            for (int i = 0; i < 100; i++)
            {
                if ((int)bad[i] != i + 5000)
                {
                    hsh1["InsertRange"] = i;
                }
            }

            //AddRange()
            que = new Queue();
            for (int i = 0; i < 100; i++)
                que.Enqueue(i + 2222);
            bad.AddRange(que);
            for (int i = bad.Count - 100; i < bad.Count; i++)
            {
                if ((int)bad[i] != (i - (bad.Count - 100)) + 2222)
                {
                    hsh1["AddRange"] = i + " " + (int)bad[i];
                }
            }

            bad.RemoveRange(0, que.Count);
            for (int i = 0; i < 100; i++)
            {
                if ((int)bad[i] != i)
                {
                    hsh1["RemoveRange"] = i + " " + (int)bad[i];
                }
            }

            //Capacity
            try
            {
                bad.Capacity = bad.Capacity * 2;
            }
            catch (Exception ex)
            {
                hsh1["Capacity"] = ex.GetType().Name;
            }

            try
            {
                bad.Capacity = -1;
                hsh1["Capacity"] = "No_Exception_Thrown, -1";
            }
            catch (ArgumentException)
            {
            }
            catch (Exception ex)
            {
                hsh1["Capacity"] = ex.GetType().Name;
            }

            int iMakeSureThisDoesNotCause = 0;
            while (bad.Capacity == bad.Count)
            {
                if (iMakeSureThisDoesNotCause++ > 100)
                    break;
                bad.Add(bad.Count);
            }
            if (iMakeSureThisDoesNotCause > 100)
                hsh1["TrimToSize"] = "Monekeyed, " + bad.Count + " " + bad.Capacity;

            //TrimToSize()
            try
            {
                bad.TrimToSize();
                if (bad.Capacity != bad.Count)
                {
                    hsh1["TrimToSize"] = "Problems baby";
                }
            }
            catch (Exception ex)
            {
                hsh1["TrimToSize"] = ex.GetType().Name;
            }
        }
        else
        {
            Queue que = new Queue();
            for (int i = 0; i < 100; i++)
                que.Enqueue(i + 5000);
            try
            {
                bad.AddRange(que);
                hsh1["AddRange"] = "Copy";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception)
            {
                hsh1["AddRange"] = "Copy_ExceptionType";
            }

            try
            {
                bad.InsertRange(0, que);
                hsh1["InsertRange"] = "Copy";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception)
            {
                hsh1["InsertRange"] = "Copy_ExceptionType";
            }

            good.Clear();
            for (int i = 0; i < 10; i++)
                good.Add(i);
            try
            {
                bad.RemoveRange(0, 10);
                hsh1["RemoveRange"] = "Copy";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception ex)
            {
                hsh1["RemoveRange"] = "Copy_ExceptionType, " + ex.GetType().Name;
            }

            try
            {
                bad.Capacity = bad.Capacity * 2;
                hsh1["Capacity"] = "No_Exception_Thrown, bad.Capacity*2";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception ex)
            {
                hsh1["Capacity"] = ex.GetType().Name;
            }

            try
            {
                bad.TrimToSize();
                hsh1["TrimToSize"] = "No_Exception_Thrown";
            }
            catch (NotSupportedException)
            {
            }
            catch (Exception ex)
            {
                hsh1["TrimToSize"] = ex.GetType().Name;
            }
        }
    }
Example #46
0
 /// <summary>
 ///
 /// </summary>
 public void Reverse()
 {
     innerlist.Reverse();
 }
Example #47
0
    private void CalculatePath()
    {
        //Debug.Log("Calculating...");

        navmesh = GameObject.Find("NavmeshGenerator").GetComponent<NavmeshSpawner>().GetNavmesh();
        path = new ArrayList();

        // cast rays up, down, left, right and if its longer than it should be, ignore the impact
        float expectedDist = navmesh.gameUnitStep + fudge;

        // Start the calculation by finding the closest node to the player (or GameObject to which we are attached)
        GameObject startPoint = FindClosestNavmeshPointTo(this.gameObject);
        Debug.Log ("Starting from: (" + startPoint.transform.position.x + ", " + startPoint.transform.position.y + ")");

        SearchElement startElement = new SearchElement(startPoint, 0.0f);

        // Then find the closest GameObject to the target
        endPoint = FindClosestNavmeshPointTo(target.gameObject);
        //Debug.Log ("Ending at: (" + endPoint.transform.position.x + ", " + endPoint.transform.position.y + ")");

        // Keep a priority queue of points on the frontier, sorted in increasing order by F = G + H
        // The CompareTo() function of each SearchElement takes into account the H value
        SortedList openSet = new SortedList();
        // Keep a list of NavmeshPoints we have already found in the SPT
        ArrayList closedSet = new ArrayList();

        openSet.Add(startElement, null);

        SearchElement finalSearchElement = null;

        while (openSet.Count > 0) {

            // Dequeue the element in the openSet with the smallest distance
            SearchElement current = openSet.GetKey(0) as SearchElement;

            // Is this what we are looking for?
            if (current.point == endPoint) {
                closedSet.Add(current.point);
                finalSearchElement = current;
                break;

            }

            // Remove this NavmeshPoint from the openSet and add it to the closedSet
            openSet.Remove(current);
            closedSet.Add(current.point);
            current.point.layer = 9;

            //Debug.Log ("Processing point at (" + current.point.transform.position.x
            //           + ", " + current.point.transform.position.y + ")");

            // Get all NavmeshPoints adjacent to this point in the form of SearchElements whose dists are current.dist
            // plus however long the edge from current to the adjacent point is (measured in terms of game space dist)
            ArrayList adj = GetAdjacentPoints(current, expectedDist);

            // Find out if any points adjacent to current are already in the openSet
            // If they are, find out if the distance through the current path is shorter than the distance
            // they are currently at through other paths. If the distance through current is shorter, update the dist
            // to be the dist through current, and update the from field to be current.

            // Note: We do not explicitly handle the heuristic estimate at this time, as it is taken care of for us
            // behind the scenes in the openSet.Add() function by the IComparable interface implemented by SearchElement
            foreach (SearchElement newFrontierElement in adj) {

                bool elementInOpenSet = false;
                bool replaceExistingElement = false;
                SearchElement existingElementIndex = null;

                foreach (SearchElement establishedFrontierElement in openSet.Keys) {
                    if (newFrontierElement.point == establishedFrontierElement.point) {

                        // This NavmeshPoint exists in the openSet
                        elementInOpenSet = true;

                        if (newFrontierElement.dist < establishedFrontierElement.dist) {

                            // The new path is a better path than the current path
                            replaceExistingElement = true;
                            existingElementIndex = establishedFrontierElement;
                        }

                        // Break out of the openSet for-loop; we are done here since we found a match
                        break;
                    }
                }

                if (!elementInOpenSet) {
                    openSet.Add(newFrontierElement, null);
                }
                else if (elementInOpenSet && replaceExistingElement) {
                    openSet.Remove(existingElementIndex);
                    openSet.Add(newFrontierElement, null);
                }

                foreach (SearchElement e in openSet.Keys) {
                    //Debug.Log("(" + e.point.transform.position.x + ", " + e.point.transform.position.y + "): "
                    //          + (e.dist + Vector2.Distance(e.point.transform.position, endPoint.transform.position)).ToString()
                    //          + "   ");
                }
            }

        }

        // We either ran out of elements in the navmesh and should throw an error, or we arrived at the target
        if (finalSearchElement == null) {
            throw new Exception("Target element not found by A* algorithm");
        }
        else {

            // We shouldn't show the close navpoints any longer
            this.gameObject.GetComponent<ShowNearbyNavpoints>().SendMessage("Cleanup");

            // Reconstruct the path that won
            path = new ArrayList();
            pathDist = 0.0f;

            SearchElement pathPoint = finalSearchElement;
            while (pathPoint != null) {
                path.Add(pathPoint.point);
                pathDist += pathPoint.dist;
                pathPoint = (SearchElement)pathPoint.from;
            }

            // Finally, reverse the path, since we added elements to it in reverse order (i.e. starting from target)
            path.Reverse();
            foreach (GameObject navmeshPoint in path) {
                SpriteRenderer sr = navmeshPoint.GetComponent<SpriteRenderer>();
                sr.enabled = true;
                sr.color = Color.red;
            }

            this.gameObject.GetComponent<FollowPath>().StartFollowing(path);

            //Debug.Log ("Final path distance: " + pathDist);

        }
    }
Example #48
0
        public static void CreateArreyList()
        {
            //http://vpaste.net/dzDWZ
            //http://vpaste.net/VhLjw // main method

            ArrayList arrayList = new ArrayList()
            {
                100, "Two", 12.5, 200
            };                                                               //any type !


            #region ADD & AddRange & Insert & InsertRange

            ArrayList arryList1 = new ArrayList();
            arryList1.Add(1);
            arryList1.Add("Two");
            arryList1.Add(3);
            arryList1.Add(4.5);

            ArrayList arryList22 = new ArrayList();
            arryList22.Add(100);
            arryList22.Add(200);

            //adding entire arryList2 into arryList1
            arryList1.AddRange(arryList22);

            // Specific index
            arryList1.Insert(1, "Second Item");
            arryList1.Insert(2, 100);

            arryList22.InsertRange(2, arryList1);

            #endregion

            #region  AccessToArray

            ArrayList arryList2 = new ArrayList();
            arryList2.Add(1);
            arryList2.Add("Two");
            arryList2.Add(3);
            arryList2.Add(4.5f);

            //Access individual item using indexer
            int    firstElement  = (int)arryList2[0];    //returns 1
            string secondElement = (string)arryList2[1]; //returns "Two"
            int    thirdElement  = (int)arryList2[2];    //returns 3
            float  fourthElement = (float)arryList2[3];  //returns 4.5

            //use var keyword
            var firstelementbyvar = arryList2[0]; //returns 1

            #endregion

            #region Navigate

            ArrayList arryList3 = new ArrayList();
            arryList3.Add(1);
            arryList3.Add("Two");
            arryList3.Add(3);
            arryList3.Add(4.5);

            foreach (var val in arryList3)
            {
                Console.WriteLine(val);
            }

            //Or
            for (int i = 0; i < arryList3.Count; i++)
            {
                Console.WriteLine(arryList3[i]);
            }

            #endregion

            #region Remove & RemoveAt & RemoveRange

            #region Remove
            ArrayList arryList4 = new ArrayList();
            arryList4.Add(100);
            arryList4.Add(200);
            arryList4.Add(300);
            arryList4.Remove(100); //Removes 1 from ArrayList
            foreach (var item in arryList4)
            {
                Console.WriteLine(item);
            }
            #endregion

            #region RemoveAt
            ArrayList arryList5 = new ArrayList();
            arryList5.Add(100);
            arryList5.Add(200);
            arryList5.Add(300);
            arryList5.RemoveAt(1);  // Specific index
            foreach (var item in arryList5)
            {
                Console.WriteLine(item);
            }
            #endregion

            #region RemoveRange
            ArrayList arryList6 = new ArrayList();
            arryList6.Add(100);
            arryList6.Add(200);
            arryList6.Add(300);
            arryList6.RemoveRange(0, 2);//Removes two elements starting from 1st item (0 index)
            foreach (var item in arryList6)
            {
                Console.WriteLine(item);
            }
            #endregion

            #endregion

            #region Sort & Reverse
            ArrayList arryList7 = new ArrayList();
            arryList7.Add(300);
            arryList7.Add(200);
            arryList7.Add(100);
            arryList7.Add(500);
            arryList7.Add(400);

            Console.WriteLine("Original Order:");

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

            arryList7.Reverse();
            Console.WriteLine("Reverse Order:");

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

            arryList7.Sort();
            Console.WriteLine("Ascending Order:");

            foreach (var item in arryList7)
            {
                Console.WriteLine(item);
            }
            #endregion

            #region Contains
            ArrayList myArryList = new ArrayList();
            myArryList.Add(100);
            myArryList.Add("Hello World");
            myArryList.Add(300);
            Console.WriteLine(myArryList.Contains(100));
            #endregion
        }
Example #49
0
 public ArrayList reconstructPath(cell start, cell goal)
 {
     ArrayList result = new ArrayList();
         bool fl = false;
         int k = 0;
         cell current = (cell)allset[allset.Count-1];
         while(!(fl) && k<allset.Count)
         {
             /*result.Add(current);
             if(current.parent == null){
                 fl = true;
             }else{
                 current = current.parent;
             }*/
             current = (cell)allset[k];
             result.Add(allset[k]);
             k++;
         }
         result.Reverse();
         return result;
 }
Example #50
0
        //this is f*****g awesome 2020
        //this is f*****g awesome 2020
        //This is f*****g awesome 2020-3
        //This is f*****g awesome 2020-4

        static void Main(string[] args)
        {
            Shape[] shapes = { new Circle(5),
                               new Rectangle(4, 5) };

            foreach (Shape s in shapes)
            {
                s.GetInfo();
                Console.WriteLine("{0} Area : {1:f2}",
                                  s.Name, s.Area());

                Circle testCirc = s as Circle;
                if (testCirc == null)
                {
                    Console.WriteLine("this is not circle");
                }

                if (s is Circle)
                {
                    Console.WriteLine("this isn't a Rectangle");
                }
            }

            Vehicle buick = new Vehicle("Buick",
                                        4, 160);

            if (buick is IDrivable)
            {
                buick.Move();
                buick.Stop();
            }
            else
            {
                Console.WriteLine($"The {0} can't be driver",
                                  buick.Brand);
            }

            IElectronicDevice TV = TVRemote.GetDevice();

            PowerButton powBut = new PowerButton(TV);

            powBut.Execute();
            powBut.Undo();

            Console.WriteLine("*************************************************");

            ArrayList aList = new ArrayList();

            aList.Add("Bob");
            aList.Add(40);

            Console.WriteLine(aList.Count);

            Console.WriteLine(aList.Capacity);
            ArrayList aList2 = new ArrayList();

            aList2.AddRange(new Object[] { "mike",
                                           "Sally", "Egg" });

            foreach (Object obj in aList2)
            {
                Console.WriteLine(obj);
            }

            aList.AddRange(aList2);

            foreach (Object obj in aList)
            {
                Console.WriteLine(obj);
            }

            Console.WriteLine("*************************");
            aList2.Sort();
            aList2.Reverse();

            foreach (Object obj in aList2)
            {
                Console.WriteLine(obj);
            }

            aList2.Insert(1, "suraj");
            Console.WriteLine("*************************");
            foreach (Object obj in aList2)
            {
                Console.WriteLine(obj);
            }
            ArrayList range = aList2.GetRange(0, 2);

            Console.WriteLine("*************************");
            foreach (Object obj in range)
            {
                Console.WriteLine(obj);
            }

            Console.WriteLine(range.IndexOf("suraj"));
            string[]  customers     = { "Bob", "Sally", "Sue" };
            ArrayList custArrayList = new ArrayList();

            custArrayList.AddRange(customers);

            foreach (string s in custArrayList)
            {
                Console.WriteLine(s);
            }


            //Dictionary
            Dictionary <string, string> superheroes =
                new Dictionary <string, string>();

            superheroes.Add("pitam bahadur gurung", "surperman");
            superheroes.Add("laxmi prajapati", "wonder women");
            superheroes.Add("suraj gurung", "gas man");

            Console.WriteLine("***********************");

            Console.WriteLine(" Count: {0}", superheroes.Count);

            Console.WriteLine("pitam bahadur gurung: {0}",
                              superheroes.ContainsKey("pitam bahadur gurung"));

            foreach (KeyValuePair <string, string> item in superheroes)
            {
                Console.WriteLine("{0}:{1}",
                                  item.Key,
                                  item.Value);
            }

            //Queue: first in firs out
            Queue queue = new Queue();

            queue.Enqueue(1);
            queue.Enqueue(2);
            queue.Enqueue(3);
            queue.Dequeue();

            foreach (object o in queue)
            {
                Console.WriteLine(o);
            }

            object[] numArray = queue.ToArray();

            foreach (object o in numArray)
            {
                Console.WriteLine(o);
            }

            //stack , first in, last out

            Stack stack = new Stack();

            stack.Push(1);
            stack.Push(2);
            stack.Push(3);
            Console.WriteLine("Peek 1 : {0}",
                              stack.Peek());
            Console.WriteLine("Contain 1: {0}",
                              stack.Contains(1));

            object[] numArray2 = stack.ToArray();

            Console.WriteLine("****************");

            foreach (Object o in stack)
            {
                Console.WriteLine(o);
            }
            Console.WriteLine("****************");
            foreach (object o in numArray2)
            {
                Console.WriteLine(o);
            }
        }
    private static void GoalPathesI(GBSearchModule module,
		ArrayList goalpathes, DBNode node, Stack path)
    {
        if (node == null)
            return;

        if (module.IsGoal (node.State)) {
            ArrayList newGoalPath = new ArrayList ();

            foreach (DBNode pNode in path)
                newGoalPath.Add (pNode);

            newGoalPath.Reverse ();

            newGoalPath.Add (node);
            goalpathes.Add (newGoalPath);

            return;
        }

        foreach (DBNode child in node.Children) {
            path.Push (node);
            GoalPathesI (module, goalpathes, child, path);
            path.Pop ();
        }
    }
Example #52
0
    void CheckColor()
    {
        if (insertionQueue.Count == 0 && checkColorTable.Count > 0 && Time.time > checkColorRegisterTime + checkColorDelay)
        {
            foreach (KeyValuePair <GameObject, CheckColorTableEntry> kvpair in checkColorTable)
            {
                if (kvpair.Value.covered == false)
                {
                    int idx = balls.IndexOf(kvpair.Key);
                    if (idx < 0)
                    {
                        Debug.LogWarning("Ball not in Chain " + kvpair.Key.name + "ID: " + kvpair.Key.GetInstanceID());
                        // continue seems to avoid the bug
                        // value.cover not work well
                        continue;
                    }
                    int prevCount         = 0;
                    int nextCount         = 0;
                    int counterMagicCount = 0;

                    if (!brokenChainNodeSet.Contains(kvpair.Key))
                    {
                        foreach (GameObject ball in balls.GetRange(idx + 1, balls.Count - (idx + 1)))
                        {
                            if (ball.tag == kvpair.Key.tag || ball.tag == "CounterMagic")
                            {
                                nextCount++;
                                if (checkColorTable.ContainsKey(kvpair.Key))
                                {
                                    kvpair.Value.covered = true;
                                }
                                if (brokenChainNodeSet.Contains(ball))
                                {
                                    break;
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                    }

                    ArrayList reverseBalls = new ArrayList(balls.GetRange(0, idx));
                    reverseBalls.Reverse();
                    foreach (GameObject ball in reverseBalls)
                    {
                        if ((ball.tag == kvpair.Key.tag || ball.tag == "CounterMagic") &&
                            (!brokenChainNodeSet.Contains(ball)))
                        {
                            prevCount++;
                            if (checkColorTable.ContainsKey(kvpair.Key))
                            {
                                Debug.Log(kvpair.Key.name + " ID: " + kvpair.Key.GetInstanceID() + " is covered in combo");
                                kvpair.Value.covered = true;
                            }
                            if (ball.tag == "CounterMagic")
                            {
                                counterMagicCount++;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (prevCount + nextCount + 1 > 2)
                    {
                        GameObject head, tail;
                        head = (GameObject)balls[idx - prevCount];
                        tail = (GameObject)balls[idx + nextCount];
                        combo++;
                        health.GetDamage(prevCount + nextCount + 1 - counterMagicCount, counterMagicCount, combo);
                        soundManager.PlayComboAudio();

                        if (brokenChainNodeSet.Contains(head))
                        {
                            Debug.LogError("Chain with same color crosses gap");
                        }
                        if (brokenChainNodeSet.Contains(tail))
                        {
                            brokenChainNodeSet.Remove(tail);
                        }
                        if (idx - prevCount > 0)
                        {
                            GameObject headHead = (GameObject)balls[idx - prevCount - 1];
                            if (!brokenChainNodeSet.Contains(headHead))
                            {
                                brokenChainNodeSet.Add(headHead);
                                brokenChainNodeDirty = true;
                            }
                        }

                        foreach (GameObject ball in balls.GetRange(idx - prevCount, prevCount + nextCount + 1))
                        {
                            explosion.CreateExplosion(ball.transform.position);
                            Destroy(ball);
                        }
                        balls.RemoveRange(idx - prevCount, prevCount + nextCount + 1);
                    }
                }
            }
            checkColorTable.Clear();
        }
    }
Example #53
0
 private void CompareObjects(ArrayList good, ArrayList bad, Hashtable hsh1)
 {
     DoIListTests(good, bad, hsh1);
     good.Clear();
     for(int i=0; i<100; i++)
         good.Add(i);
     if(fVerbose)
         Console.WriteLine("CopyTo()");
     Int32[] iArr1 = null;
     Int32[] iArr2 = null;
     iArr1 = new Int32[100];
     iArr2 = new Int32[100];
     good.CopyTo(iArr1);
     bad.CopyTo(iArr2);
     for(int i=0; i<100; i++)
     {
         if(iArr1[i] != iArr2[i])
             hsh1["CopyTo"] = "()";
     }
     iArr1 = new Int32[100];
     iArr2 = new Int32[100];
     good.CopyTo(0, iArr1, 0, 100);
     try
     {
         bad.CopyTo(0, iArr2, 0, 100);
         for(int i=0; i<100; i++)
         {
             if(iArr1[i] != iArr2[i])
                 hsh1["CopyTo"] = "()";
         }
     }
     catch
     {
         hsh1["CopyTo"] = "(Int32, Array, Int32, Int32)";
     }
     iArr1 = new Int32[200];
     iArr2 = new Int32[200];
     for(int i=0; i<200; i++)
     {
         iArr1[i]=50;
         iArr2[i]=50;
     }
     good.CopyTo(50, iArr1, 100, 20);
     try
     {
         bad.CopyTo(50, iArr2, 100, 20);
         for(int i=0; i<200; i++)
         {
             if(iArr1[i] != iArr2[i])
                 hsh1["CopyTo"] = "(Array, Int32, Int32)";
         }
     }
     catch
     {
         hsh1["CopyTo"] = "(Int32, Array, Int32, Int32)";
     }
     if(fVerbose)
         Console.WriteLine("Clone()");
     ArrayList alstClone = (ArrayList)bad.Clone();
     if(alstClone.Count != bad.Count)
         hsh1["Clone"] = "Count";
     for(int i=0; i<bad.Count; i++)
     {
         if(alstClone[i] != bad[i])
             hsh1["Clone"] = "[]";
     }
     if(fVerbose)
         Console.WriteLine("GetEnumerator()");
     IEnumerator ienm1 = null;
     IEnumerator ienm2 = null;
     ienm1 = good.GetEnumerator(0, 100);
     try
     {
         ienm2 = bad.GetEnumerator(0, 100);
         DoIEnumerableTest(ienm1, ienm2, hsh1, false);
     }
     catch
     {
         hsh1["GetEnumerator"] = "(Int32, Int32)";
     }
     ienm1 = good.GetEnumerator(50, 50);
     try
     {
         ienm2 = bad.GetEnumerator(50, 50);
         DoIEnumerableTest(ienm1, ienm2, hsh1, false);
     }
     catch
     {
         hsh1["GetEnumerator"] = "(Int32, Int32)";
     }
     try
     {
         bad.GetEnumerator(50, 150);
         hsh1["GetEnumerator"] = "(Int32, Int32)";
     }
     catch(Exception)
     {
     }
     ienm1 = good.GetEnumerator(0, 100);
     try
     {
         ienm2 = bad.GetEnumerator(0, 100);
         good.RemoveAt(0);
         DoIEnumerableTest(ienm1, ienm2, hsh1, true);
     }
     catch
     {
         hsh1["GetEnumerator"] = "(Int32, Int32)";
     }
     good.Clear();
     for(int i=0; i<100; i++)
         good.Add(i);
     if(fVerbose)
         Console.WriteLine("GetRange()");
     ArrayList alst1 = good.GetRange(0, good.Count);
     try
     {
         ArrayList alst2 = bad.GetRange(0, good.Count);
         for(int i=0; i<good.Count; i++)
         {
             if(alst1[i] != alst2[i])
                 hsh1["GetRange"] = i;
         }
     }
     catch
     {
         hsh1["Range"] = "(Int32, Int32)";
     }
     if(bad.Count>0)
     {
         if(fVerbose)
             Console.WriteLine("IndexOf()");
         for(int i=0; i<good.Count; i++)
         {
             if(good.IndexOf(good[i], 0) != bad.IndexOf(good[i], 0))
             {
                 Console.WriteLine(good .Count + " " + bad.Count + " " + good[i] + " " + bad[i] + " " + good.IndexOf(good[i], 0) + " " + bad.IndexOf(good[i], 0));
                 hsh1["IndexOf"] = "(Object, Int32)";
             }
             if(good.IndexOf(good[i], i) != bad.IndexOf(good[i], i))
             {
                 Console.WriteLine("2" + good.IndexOf(good[i], i) + " " + bad.IndexOf(good[i], i));
                 hsh1["IndexOf"] = "(Object, Int32)";
             }
             if(i<(good.Count-1))
             {
                 if(good.IndexOf(good[i], i+1) != bad.IndexOf(good[i], i+1))
                 {
                     Console.WriteLine("3" + good.IndexOf(good[i], i+1) + " " + bad.IndexOf(good[i], i+1));
                     hsh1["IndexOf"] = "(Object, Int32)";
                 }
             }			
         }
         try
         {
             bad.IndexOf(1, -1);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["IndexOf"] = ex;
         }
         try
         {
             bad.IndexOf(1, bad.Count);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["IndexOf"] = ex;
         }
         for(int i=0; i<good.Count; i++)
         {
             if(good.IndexOf(good[i], 0, good.Count-1) != bad.IndexOf(good[i], 0, good.Count-1))
             {
                 hsh1["IndexOf"] = "(Object, Int32, Int32)";
             }
             if(good.IndexOf(good[i], i, good.Count-i) != bad.IndexOf(good[i], i, good.Count-i))
             {
                 hsh1["IndexOf"] = "(Object, Int32)";
             }
             if(good.IndexOf(good[i], i, 0) != bad.IndexOf(good[i], i, 0))
             {
                 hsh1["IndexOf"] = "(Object, Int32)";
             }
             if(i<(good.Count-1))
             {
                 if(good.IndexOf(good[i], i+1, good.Count-(i+1)) != bad.IndexOf(good[i], i+1, good.Count-(i+1)))
                 {
                     hsh1["IndexOf"] = "(Object, Int32)";
                 }
             }
         }
         try
         {
             bad.IndexOf(1, 0, -1);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["IndexOf"] = ex;
         }
         try
         {
             bad.IndexOf(1, 0, bad.Count);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["IndexOf"] = ex;
         }
         try
         {
             bad.IndexOf(1, bad.Count-1, bad.Count-2);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["IndexOf"] = ex;
         }
         if(fVerbose)
             Console.WriteLine("LastIndexOf(), " + good.Count + " " + bad.Count);
         for(int i=0; i<good.Count; i++)
         {
             if(good.LastIndexOf(good[i]) != bad.LastIndexOf(good[i]))
             {
                 hsh1["LastIndexOf"] = "(Object)";
             }
             if(good.LastIndexOf(i+1000) != bad.LastIndexOf(i+1000))
             {
                 hsh1["LastIndexOf"] = "(Object)";
             }
         }
         try
         {
             bad.LastIndexOf(null);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["LastIndexOf"] = ex;
         }
         if(fVerbose)
             Console.WriteLine("LastIndexOf(Object, Int32)");
         for(int i=0; i<good.Count; i++)
         {
             if(good.LastIndexOf(good[i], good.Count-1) != bad.LastIndexOf(good[i], good.Count-1))
             {
                 hsh1["LastIndexOf"] = "(Object, Int32)";
             }
             if(good.LastIndexOf(good[i], 0) != bad.LastIndexOf(good[i], 0))
             {
                 hsh1["LastIndexOf"] = "(Object, Int32)";
             }
             if(good.LastIndexOf(good[i], i) != bad.LastIndexOf(good[i], i))
             {
                 hsh1["LastIndexOf"] = "(Object, Int32)";
             }
             if(i<(good.Count-1))
             {
                 if(good.LastIndexOf(good[i], i+1) != bad.LastIndexOf(good[i], i+1))
                 {
                     hsh1["LastIndexOf"] = "(Object, Int32)";
                 }
             }			
         }
         try
         {
             bad.LastIndexOf(1, -1);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["LastIndexOf"] = ex;
         }
         try
         {
             bad.LastIndexOf(1, bad.Count);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["LastIndexOf"] = ex;
         }
         for(int i=0; i<good.Count; i++)
         {
             if(good.LastIndexOf(good[i], good.Count-1, 0) != bad.LastIndexOf(good[i], good.Count-1, 0))
             {
                 hsh1["LastIndexOf"] = "(Object, Int32, Int32)";
             }
             if(good.LastIndexOf(good[i], good.Count-1, i) != bad.LastIndexOf(good[i], good.Count-1, i))
             {
                 hsh1["LastIndexOf"] = "(Object, Int32)";
             }
             if(good.LastIndexOf(good[i], i, i) != bad.LastIndexOf(good[i], i, i))
             {
                 hsh1["LastIndexOf"] = "(Object, Int32)";
             }
             if(i<(good.Count-1))
             {
                 if(good.LastIndexOf(good[i], good.Count-1, i+1) != bad.LastIndexOf(good[i], good.Count-1, i+1))
                 {
                     hsh1["LastIndexOf"] = "(Object, Int32)";
                 }
             }
         }
         try
         {
             bad.LastIndexOf(1, 1, -1);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["LastIndexOf"] = ex;
         }
         try
         {
             bad.LastIndexOf(1, bad.Count-2, bad.Count-1);
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["LastIndexOf"] = ex;
         }
     }
     if(fVerbose)
         Console.WriteLine("ReadOnly()");
     ArrayList alst3 = ArrayList.ReadOnly(bad);
     if(!alst3.IsReadOnly)
         hsh1["ReadOnly"] = "Not";
     IList ilst1 = ArrayList.ReadOnly((IList)bad);
     if(!ilst1.IsReadOnly)
         hsh1["ReadOnly"] = "Not";
     if(fVerbose)
         Console.WriteLine("Synchronized()");
     alst3 = ArrayList.Synchronized(bad);
     if(!alst3.IsSynchronized)
         hsh1["Synchronized"] = "Not";
     ilst1 = ArrayList.Synchronized((IList)bad);
     if(!ilst1.IsSynchronized)
         hsh1["Synchronized"] = "Not";
     if(good.Count == bad.Count)
     {
         if(fVerbose)
             Console.WriteLine("ToArray()");
         Object[] oArr1 = good.ToArray();
         Object[] oArr2 = bad.ToArray();
         for(int i=0; i<good.Count; i++)
         {
             if((Int32)oArr1[i] != (Int32)oArr2[i])
                 hsh1["ToArray"] = "()";
         }
         iArr1 = (Int32[])good.ToArray(typeof(Int32));
         iArr2 = (Int32[])bad.ToArray(typeof(Int32));
         for(int i=0; i<good.Count; i++)
         {
             if(iArr1[i] != iArr2[i])
                 hsh1["ToArray"] = "(Type)";
         }
     }
     if(fVerbose)
         Console.WriteLine("Capacity()");
     if(good.Capacity != bad.Capacity)
     {
         hsh1["Capacity"] = "get";
     }
     if(!hsh1.ContainsKey("IsReadOnly"))
     {
         good.Clear();
         for(int i=100; i>0; i--)
             good.Add(i);
         if(fVerbose)
             Console.WriteLine("Sort() & BinarySearch()");
         bad.Sort();
         for(int i=0; i<bad.Count-1; i++)
         {
             if((Int32)bad[i] > (Int32)bad[i+1])
                 hsh1["Sort"] = "()";
         }			
         for(int i=0; i<bad.Count; i++)
         {
             if(bad.BinarySearch(bad[i]) != i)
                 hsh1["BinarySearch"] = "(Object)";
         }
         bad.Reverse();
         if(bad.Count>0)
         {
             for(int i=0; i<99; i++)
             {
                 if((Int32)bad[i] < (Int32)bad[i+1])
                     hsh1["Reverse"] = "()";
             }
             good.Clear();
             for(int i=100; i>0; i--)
                 good.Add(i.ToString());
         }
         good.Clear();
         for(int i=90; i>64; i--)
             good.Add(((Char)i).ToString());
         try
         {
             bad.Sort(new CaseInsensitiveComparer());
             if(bad.Count>0)
             {
                 for(int i=0; i<(bad.Count-1); i++)
                 {
                     if(((String)bad[i]).CompareTo(((String)bad[i+1])) >= 0)
                         hsh1["Sort"] = "(IComparer)";
                 }			
                 for(int i=0; i<bad.Count; i++)
                 {
                     if(bad.BinarySearch(bad[i], new CaseInsensitiveComparer()) != i)
                         hsh1["BinarySearch"] = "(Object, IComparer)";
                 }
             }
             bad.Reverse();			
             good.Clear();
             for(int i=65; i<91; i++)
                 good.Add(((Char)i).ToString());
             if(bad.Count>0)
             {
                 for(int i=0; i<good.Count; i++)
                 {
                     if(bad.BinarySearch(0, bad.Count, bad[i], new CaseInsensitiveComparer()) != i)
                         hsh1["BinarySearch"] = "(Int32, Int32, Object, IComparer)";
                 }
             }
         }
         catch(Exception)
         {
         }
         good.Clear();
         for(int i=0; i<100; i++)
             good.Add(i);
         if(fVerbose)
             Console.WriteLine("SetRange()");
         Queue que = new Queue();
         for(int i=0; i<100; i++)
             que.Enqueue(i+5000);
         try
         {
             bad.SetRange(0, que);
         }
         catch(Exception ex)
         {
             hsh1["SetRange"] = "Copy_ExceptionType, " + ex.GetType().Name;
         }
         for(int i=bad.Count; i<bad.Count; i++)
         {
             if((Int32)bad[i] != (i + 5000))
             {
                 hsh1["SetRange"] = i;
             }
         }
     }
     else
     {
         good.Clear();
         for(int i=100; i>0; i--)
             good.Add(i);
         try
         {
             bad.Sort();
             hsh1["Sort"] = "Copy";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception)
         {
             hsh1["Sort"] = "Copy_ExceptionType";
         }
         try
         {
             bad.Reverse();
             hsh1["Reverse"] = "Copy";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception ex)
         {
             hsh1["Reverse"] = "Copy_ExceptionType, " + ex.GetType().Name;
         }
         try
         {
             bad.Sort(new CaseInsensitiveComparer());
             hsh1["Sort"] = "Copy - Icomparer";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception)
         {
             hsh1["Sort"] = "Copy_ExceptionType";
         }
         try
         {
             bad.Sort(0, 0, new CaseInsensitiveComparer());
             hsh1["Sort"] = "Copy - Int32, Int32, IComparer";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception)
         {
             hsh1["Sort"] = "Copy_ExceptionType";
         }
         try
         {
             for(int i=0; i<bad.Count; i++)
             {
                 if(bad.BinarySearch(bad[i]) != i)
                     hsh1["BinarySearch"] = "(Object)";
             }
             hsh1["BinarySearch"] = "(Object)";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception ex)
         {
             hsh1["BinarySearch"] = ex.GetType().Name;
         }
         try
         {
             for(int i=0; i<bad.Count; i++)
             {
                 if(bad.BinarySearch(bad[i], new CaseInsensitiveComparer()) != i)
                     hsh1["BinarySearch"] = "(Object)";
             }
             hsh1["BinarySearch"] = "Exception not thrown, (Object, IComparer)";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception ex)
         {
             hsh1["BinarySearch"] = ex.GetType().Name;
         }
         try
         {
             for(int i=0; i<bad.Count; i++)
             {
                 if(bad.BinarySearch(0, bad.Count, bad[i], new CaseInsensitiveComparer()) != i)
                     hsh1["BinarySearch"] = "(Object)";
             }
             hsh1["BinarySearch"] = "Exception not thrown, (Object, IComparer)";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception ex)
         {
             hsh1["BinarySearch"] = ex.GetType().Name;
         }
         good.Clear();
         for(int i=0; i<100; i++)
             good.Add(i);
         Queue que = new Queue();
         for(int i=0; i<100; i++)
             que.Enqueue(i+5000);
         try
         {
             bad.SetRange(0, que);
             hsh1["Sort"] = "Copy - Int32, Int32, IComparer";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception)
         {
             hsh1["Sort"] = "Copy_ExceptionType";
         }
     }
     if(!hsh1.ContainsKey("IsReadOnly") && !hsh1.ContainsKey("Fixed"))
     {
         good.Clear();
         for(int i=0; i<100; i++)
             good.Add(i);
         if(fVerbose)
             Console.WriteLine("InsertRange()");
         Queue que = new Queue();
         for(int i=0; i<100; i++)
             que.Enqueue(i+5000);
         bad.InsertRange(0, que);
         for(int i=0; i<100; i++)
         {
             if((Int32)bad[i] != i + 5000)
             {
                 hsh1["InsertRange"] = i;
             }
         }
         if(fVerbose)
             Console.WriteLine("AddRange()");
         que = new Queue();
         for(int i=0; i<100; i++)
             que.Enqueue(i+2222);
         bad.AddRange(que);
         for(int i=bad.Count-100; i<bad.Count; i++)
         {
             if((Int32)bad[i] != (i-(bad.Count-100)) + 2222)
             {
                 hsh1["AddRange"] = i + " " + (Int32)bad[i];
             }
         }
         if(fVerbose)
             Console.WriteLine("RemoveRange()");
         bad.RemoveRange(0, que.Count);
         for(int i=0; i<100; i++)
         {
             if((Int32)bad[i] != i)
             {
                 hsh1["RemoveRange"] = i + " " + (Int32)bad[i];
             }
         }
         try
         {
             bad.Capacity = bad.Capacity*2;
         }
         catch(Exception ex)
         {
             hsh1["Capacity"] = ex.GetType().Name;
         }
         try
         {
             bad.Capacity = -1;
             hsh1["Capacity"] = "No_Exception_Thrown, -1";
         }
         catch(ArgumentException)
         {
         }
         catch(Exception ex)
         {
             hsh1["Capacity"] = ex.GetType().Name;
         }
         Int32 iMakeSureThisDoesNotCause = 0;
         while(bad.Capacity == bad.Count)
         {
             if(iMakeSureThisDoesNotCause++>100)
                 break;
             bad.Add(bad.Count);
         }
         if(iMakeSureThisDoesNotCause>100)
             hsh1["TrimToSize"] = "Monekeyed, " + bad.Count + " " + bad.Capacity;
         try
         {
             bad.TrimToSize();
             if(bad.Capacity != bad.Count)
             {
                 hsh1["TrimToSize"] = "Problems baby";
             }
         }
         catch(Exception ex)
         {
             hsh1["TrimToSize"] = ex.GetType().Name;
         }
     }
     else
     {
         Queue que = new Queue();
         for(int i=0; i<100; i++)
             que.Enqueue(i+5000);
         try
         {
             bad.AddRange(que);
             hsh1["AddRange"] = "Copy";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception)
         {
             hsh1["AddRange"] = "Copy_ExceptionType";
         }
         try
         {
             bad.InsertRange(0, que);
             hsh1["InsertRange"] = "Copy";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception)
         {
             hsh1["InsertRange"] = "Copy_ExceptionType";
         }
         good.Clear();
         for(int i=0; i<10; i++)
             good.Add(i);
         try
         {
             bad.RemoveRange(0, 10);
             hsh1["RemoveRange"] = "Copy";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception ex)
         {
             hsh1["RemoveRange"] = "Copy_ExceptionType, " + ex.GetType().Name;
         }
         try
         {
             bad.Capacity = bad.Capacity*2;
             hsh1["Capacity"] = "No_Exception_Thrown, bad.Capacity*2";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception ex)
         {
             hsh1["Capacity"] = ex.GetType().Name;
         }
         try
         {
             bad.TrimToSize();
             hsh1["TrimToSize"] = "No_Exception_Thrown";
         }
         catch(NotSupportedException)
         {
         }
         catch(Exception ex)
         {
             hsh1["TrimToSize"] = ex.GetType().Name;
         }
     }
 }
        public static void Main(string[] args)
        {
            Console.WriteLine();
            Console.WriteLine("---------------ARRAY LIST-------------------------");
            Console.WriteLine();

            #region Arraylist
            ArrayList listaDeArrays = new ArrayList();

            listaDeArrays.Add("Alguém");
            listaDeArrays.Add(50);

            Console.WriteLine("Contar : {0}", listaDeArrays.Count);
            Console.WriteLine("Capacidade : {0}", listaDeArrays.Capacity);

            ArrayList listaDeArrays2 = new ArrayList();

            listaDeArrays2.AddRange(new object [] { "Mike", "Sally", "Egg" });

            listaDeArrays.AddRange(listaDeArrays2);

            listaDeArrays2.Sort();
            listaDeArrays2.Reverse();

/*
 *          // Remove the first item
 *          aList2.RemoveAt(0);
 *
 *          // Remove the 1st 2 items
 *          aList2.RemoveRange(0, 2);
 */

            listaDeArrays2.Insert(1, "Turkey");

            ArrayList Range = listaDeArrays2.GetRange(0, 2);

            Console.WriteLine("Turkey Index: {0}", listaDeArrays2.IndexOf("Turkey", 0));

            foreach (object o in Range)
            {
                Console.WriteLine(o);
            }

            string [] myArray = (string[])listaDeArrays2.ToArray(typeof(string));

            string[]  customers = { "Bob", "Sally", "Sue" };
            ArrayList custArray = new ArrayList();
            custArray.AddRange(customers);

            #endregion

            Console.WriteLine();
            Console.WriteLine("---------------DICIONÁRIO-------------------------");
            Console.WriteLine();

            #region Dicionario

            Dictionary <string, string> superHerois = new Dictionary <string, string>();

            superHerois.Add("Clark Kent", "Superman");
            superHerois.Add("Bruce Wayne", "Batman");
            superHerois.Add("Barry West", "Flash");

            superHerois.Remove("Barry West");

            Console.WriteLine("Contar : {0}", superHerois.Count);
            Console.WriteLine("Clark Kent : {0}", superHerois.ContainsKey("Clark Kent"));

            string test;

            superHerois.TryGetValue("Clark Kent", out test);

            Console.WriteLine("Clark Kent Teste: {0}", test);

            foreach (KeyValuePair <string, string> item in superHerois)
            {
                Console.WriteLine("{0} : {1}", item.Key, item.Value);
            }

            superHerois.Clear();

            #endregion

            Console.WriteLine();
            Console.WriteLine("---------------Queue (fila)-----------------------");
            Console.WriteLine();

            #region Queue (fila)

            Queue fila = new Queue();

            fila.Enqueue(1);
            fila.Enqueue(2);
            fila.Enqueue(3);

            Console.WriteLine("1 na fila: {0}", fila.Contains(1));
            Console.WriteLine("Remove 1: {0}", fila.Dequeue());
            Console.WriteLine("Peek: {0}", fila.Peek());

            object[] numArray = fila.ToArray();

            Console.WriteLine(string.Join(", ", numArray));

            foreach (object o in fila)
            {
                Console.WriteLine("Queue : {0}", o);
            }

            fila.Clear();

            #endregion

            Console.WriteLine();
            Console.WriteLine("---------------Queue (pilha)-----------------------");
            Console.WriteLine();

            #region Queue (pilha)

            Stack pilha = new Stack();

            pilha.Push(1);
            pilha.Push(2);
            pilha.Push(3);

            Console.WriteLine("Peek 1: {0}", pilha.Peek());
            Console.WriteLine("Pop 1: {0}", pilha.Pop());
            Console.WriteLine("Contain 1: {0}", pilha.Contains(1));

            object [] numArray2 = pilha.ToArray();

            Console.WriteLine(string.Join(", ", numArray2));

            foreach (object o in pilha)
            {
                Console.WriteLine("Stack: {0}", o);
            }

            #endregion

            // TODO: Implement Functionality Here

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
Example #55
0
	void CheckColor () {
		if (insertionQueue.Count == 0 && checkColorTable.Count > 0 && Time.time > checkColorRegisterTime + checkColorDelay) {
			foreach (KeyValuePair<GameObject, CheckColorTableEntry> kvpair in checkColorTable) {
				if (kvpair.Value.covered == false) {
					int idx = balls.IndexOf(kvpair.Key);
					if (idx < 0) {
						Debug.LogWarning ("Ball not in Chain " + kvpair.Key.name + "ID: " + kvpair.Key.GetInstanceID());
						// continue seems to avoid the bug
						// value.cover not work well
						continue;
					}
					int prevCount = 0;
					int nextCount = 0;
					int counterMagicCount = 0;

					if (!brokenChainNodeSet.Contains(kvpair.Key)) {
						foreach (GameObject ball in balls.GetRange(idx + 1, balls.Count - (idx + 1))) {
							if (ball.tag == kvpair.Key.tag || ball.tag == "CounterMagic") {
								nextCount++;
								if (checkColorTable.ContainsKey(kvpair.Key)) {
									kvpair.Value.covered = true;
								}
								if (brokenChainNodeSet.Contains(ball)) {
									break;
								}
							}
							else {
								break;
							}
						}
					}

					ArrayList reverseBalls = new ArrayList(balls.GetRange(0, idx));
					reverseBalls.Reverse();
					foreach (GameObject ball in reverseBalls) {
						if ((ball.tag == kvpair.Key.tag || ball.tag == "CounterMagic")
						    && (!brokenChainNodeSet.Contains(ball))) {
							prevCount++;
							if (checkColorTable.ContainsKey(kvpair.Key)) {
								Debug.Log (kvpair.Key.name + " ID: " + kvpair.Key.GetInstanceID() + " is covered in combo");
								kvpair.Value.covered = true;
							}
							if (ball.tag == "CounterMagic") {
								counterMagicCount++;
							}
						}
						else {
							break;
						}
					}

					if (prevCount + nextCount + 1 > 2) {
						GameObject head, tail;
						head = (GameObject)balls[idx - prevCount];
						tail = (GameObject)balls[idx + nextCount];
						combo++;
						health.GetDamage (prevCount + nextCount + 1 - counterMagicCount, counterMagicCount, combo);
						soundManager.PlayComboAudio();

						if (brokenChainNodeSet.Contains(head)) {
							Debug.LogError ("Chain with same color crosses gap");
						}
						if (brokenChainNodeSet.Contains(tail)) {
							brokenChainNodeSet.Remove(tail);
						}
						if (idx - prevCount > 0) {
							GameObject headHead = (GameObject)balls[idx - prevCount - 1];
							if (!brokenChainNodeSet.Contains(headHead)) {
								brokenChainNodeSet.Add (headHead);
								brokenChainNodeDirty = true;
							}
						}

						foreach (GameObject ball in balls.GetRange(idx - prevCount, prevCount + nextCount + 1)){
							explosion.CreateExplosion(ball.transform.position);
							Destroy (ball);
						}
						balls.RemoveRange(idx - prevCount, prevCount + nextCount + 1);

					}

				}
			}
			checkColorTable.Clear();
		}
	}
Example #56
0
        static void Main(string[] args)
        {
            //Add Elements in an Array.
            ArrayList arryList1 = new ArrayList();

            arryList1.Add(1);
            arryList1.Add("Two");
            arryList1.Add(3);
            arryList1.Add(4.5);


            IList arryList2 = new ArrayList()
            {
                100, 200
            };

            //Add Elements using AddRange Function
            arryList1.AddRange(arryList2);
            for (int i = 0; i < arryList1.Count; i++)
            {
                Console.WriteLine(arryList1[i]);
            }
            Console.ReadLine();

            //Remove from particular index.
            arryList1.RemoveAt(1);
            for (int i = 0; i < arryList1.Count; i++)
            {
                Console.WriteLine(arryList1[i]);
            }
            Console.ReadLine();

            // Remove a particular element
            arryList1.Remove(100);
            for (int i = 0; i < arryList1.Count; i++)
            {
                Console.WriteLine(arryList1[i]);
            }
            Console.ReadLine();

            // Remove element (0,4)--> 0 defines the starting point and 4 defines the no. of elements from that stating point to be removed.
            arryList1.RemoveRange(0, 4);
            for (int i = 0; i < arryList1.Count; i++)
            {
                Console.WriteLine(arryList1[i]);
            }
            Console.ReadLine();



            arryList1.Add(300);
            arryList1.Add(200);
            arryList1.Add(100);
            arryList1.Add(500);
            arryList1.Add(400);

            Console.WriteLine("Original Order:");
            for (int i = 0; i < arryList1.Count; i++)
            {
                Console.WriteLine(arryList1[i]);
            }
            Console.ReadLine();

            //Reverse a given ArrayList
            arryList1.Reverse();
            Console.WriteLine("Reverse Order:");
            for (int i = 0; i < arryList1.Count; i++)
            {
                Console.WriteLine(arryList1[i]);
            }
            Console.ReadLine();

            //Sorting on a given arrayList
            arryList1.Sort();
            Console.WriteLine("Ascending Order:");
            for (int i = 0; i < arryList1.Count; i++)
            {
                Console.WriteLine(arryList1[i]);
            }
            Console.ReadLine();

            //Checks if ArrayList contains the particular element.
            Console.WriteLine(arrayList1.Contains(100));
            Console.ReadLine();
        }
Example #57
0
	void FindPathTo(GameObject dest) {
		ArrayList open_list = new ArrayList ();
		ArrayList closed_list = new ArrayList ();
		IComparer compare = new ItemComparer ();
		open_list.Add (new AStarItem (standingFloor, FloorFunc (standingFloor.transform.position), 0, 0, Vector3.zero));

		Vector3 dest_floor = FloorFunc (dest.transform.position);
		AStarItem dest_item = null;

		while (open_list.Count > 0) {
			open_list.Sort(compare);
			AStarItem item = (AStarItem) open_list[0];
			open_list.RemoveAt(0);
			closed_list.Add (item);

			if (item.Obj == dest) {
				dest_item = item;
				break;
			}

			AStarItem[] near_items = FindNearFloors(item.Obj);
			for (int i = 0; i < near_items.Length; i++) {
				if (near_items[i] == null) continue;
				AStarItem near_item = near_items[i];
				bool ok = true;
				foreach (AStarItem it in closed_list) {
					if (it.Obj == near_item.Obj) {
						ok = false;
						break;
					}
				}
				if (!ok) continue;

				near_item.G = item.G + 1;
				near_item.H = (int) (Mathf.Abs(dest_floor.x - near_item.FloorValue.x) + Mathf.Abs(dest_floor.y - near_item.FloorValue.y));
				near_item.parent = item;

				for (int j = 0; j < open_list.Count; j++) {
					AStarItem it = (AStarItem) open_list[j];
					if (it.Obj == near_item.Obj) {
						ok = false;
						it.G = Mathf.Max (it.G, near_item.G);
						break;
					}
				}
				if (!ok) continue;

				open_list.Add(near_item);
			}
		}

		if (dest_item != null) {
			ArrayList move_list = new ArrayList();
			AStarItem item = dest_item;
			while (item.Weight > 0) {
				move_list.Add (new MoveData(item.dir, item.Obj));
				item = item.parent;
			}
			move_list.Reverse();

			if (moving > 0){
				StopMoving ();
				RecalcPlayerPos ();
			}

			moveList = new MoveData[move_list.Count];
			for (int i = 0; i < move_list.Count; i++) {
				moveList[i] = (MoveData)move_list[i];
			}

			MoveTo(moveList[0].destFloor, moveList[0].dir);
		}
	}
Example #58
0
        public override string Ejecutar(Entorno entorno)
        {
            System.Diagnostics.Debug.WriteLine("Ejecucion SELECT_ORDER_BY_LIMIT");
            System.Diagnostics.Debug.WriteLine("Ejecucion SELECT_ORDER_BY_LIMIT");
            System.Diagnostics.Debug.WriteLine("Ejecucion SELECT_ORDER_BY_LIMIT");
            String Tabla = this.Hijos[0].Nombre;
            String BD    = entorno.Tabla();

            entorno.Devolver2();
            System.Diagnostics.Debug.WriteLine("Ejecucion SELECT_ORDER_BY_LIMIT tabla->" + Tabla);
            System.Diagnostics.Debug.WriteLine("Ejecucion SELECT_ORDER_BY_LIMIT bd->" + BD);
            entorno.AgregarADiccionario(Tabla, BD);


            List <Simbolo> Campos = new List <Simbolo>();

            Campos = entorno.TablaBD(Tabla, BD);
            if (this.ListaID1.Count == 1 && this.ListaID1[0] == "* (Key symbol)")
            {
                //entorno.MostrarUTablas2(Tabla, BD);
                //entorno.MostrarCampos2(Tabla, BD);
                //return "SELECT SIMPLE";
            }
            else
            {
                for (int i = 0; i < this.ListaID1.Count; i++)
                {
                    Boolean Existencia = false;
                    for (int x = 0; x < Campos.Count; x++)
                    {
                        //System.Diagnostics.Debug.WriteLine(this.ListaID1[i].Replace(" (id)", "") + "->" + Campos[x].ObtenerId());
                        if (this.ListaID1[i].Replace(" (id)", "") == Campos[x].ObtenerId())
                        {
                            Existencia = true;
                        }
                    }
                    if (Existencia == false)
                    {
                        return("#ERROR PARAMETRO SELEC NO EXISTE");
                    }
                }
            }
            for (int i = 0; i < this.ListaR1.Count; i++)
            {
                string[] separadas;
                separadas = this.ListaR1[i].Split(',');
                Boolean Existencia = false;
                for (int x = 0; x < Campos.Count; x++)
                {
                    //System.Diagnostics.Debug.WriteLine(this.ListaR1[i].Replace(" (id)", "") + "->" + Campos[x].ObtenerId());
                    if (separadas[0] == Campos[x].ObtenerId())
                    {
                        Existencia = true;
                    }
                }
                if (Existencia == false)
                {
                    return("#ERROR PARAMETRO order by NO EXISTE");
                }
            }
            entorno.MostrarDiccionario();
            Dictionary <String, Simbolo> ResultadoOrdenar = new Dictionary <String, Simbolo>();
            Dictionary <String, String>  OrdenarrDiccionario;

            for (int i = 0; i < this.ListaR1.Count; i++)
            {
                entorno.Devolver2();
                System.Diagnostics.Debug.WriteLine("Ejecucion select-ORDER_BYE Campo a ordenarr->" + i + "->" + this.ListaR1[i]);
                List <String> Auxiliar = new List <String>();
                string[]      separadas;
                separadas           = this.ListaR1[i].Split(',');
                OrdenarrDiccionario = entorno.OrdenarrDiccionario(separadas[0]);

                ArrayList aKeys = new ArrayList(OrdenarrDiccionario.Values);
                aKeys.Sort();
                if (separadas[1].ToUpper().Contains("DESC"))
                {
                    aKeys.Reverse();
                }



                for (int j = 0; j < OrdenarrDiccionario.Count; j++)
                {
                    //System.Diagnostics.Debug.WriteLine("Ejecucion select-ORDER_BYE HASH ->" + aKeys[j]);

                    foreach (KeyValuePair <String, String> kvp in OrdenarrDiccionario)
                    {
                        if (kvp.Value == aKeys[j].ToString())
                        {
                            if (Auxiliar.Contains(kvp.Key) == false)
                            {
                                System.Diagnostics.Debug.WriteLine("Ejecucion select-ORDER_BYE HASH ->" + aKeys[j] + "->" + kvp.Key.ToString());
                                Auxiliar.Add(kvp.Key);
                                entorno.OrdenarDiccionarioFinal(kvp.Key.ToString());
                            }
                        }
                    }
                }

                //entorno.IgualarDic();
                entorno.MostrarDiccionario2x();

                entorno.LImpiar2();
            }
            String Limite   = this.Hijos[1].Ejecutar(entorno);
            int    ellimite = Int32.Parse(Limite.Replace(" (id)", "").Replace(" (id2)", "").Replace(" (numero)", "").Replace(" (hora)", "").Replace(" (numdecimal)", "").Replace(" (fechas)", ""));

            if (ellimite > entorno.Counter(Tabla, BD))
            {
                return("#ERROR EL LIMITE SOBREPASA LOS CAMPOS");
            }

            if (this.ListaID1.Count == 1 && this.ListaID1[0] == "* (Key symbol)")
            {
                entorno.MostrarDiccionario2(ellimite);
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("\n\n\n\nDICCIONARIO-Tabla->\n\n");
                String Cadena = "";
                for (int x = 0; x < this.ListaID1.Count; x++)
                {
                    Cadena = Cadena + this.ListaID1[x].Replace(" (id)", "") + "             |  ";
                }
                System.Diagnostics.Debug.WriteLine(Cadena);
                entorno.MostrarDiccionario2(this.ListaID1, ellimite);
            }

            return("SELECT_ORDER_BY_LIMIT");
        }
Example #59
0
        internal bool LoadAddin(IProgressStatus statusMonitor, string id, bool throwExceptions)
        {
            try {
                lock (LocalLock) {
                    if (IsAddinLoaded(id))
                    {
                        return(true);
                    }

                    if (!Registry.IsAddinEnabled(id))
                    {
                        string msg = GettextCatalog.GetString("Disabled add-ins can't be loaded.");
                        ReportError(msg, id, null, false);
                        if (throwExceptions)
                        {
                            throw new InvalidOperationException(msg);
                        }
                        return(false);
                    }

                    ArrayList addins   = new ArrayList();
                    Stack     depCheck = new Stack();
                    ResolveLoadDependencies(addins, depCheck, id, false);
                    addins.Reverse();

                    if (statusMonitor != null)
                    {
                        statusMonitor.SetMessage("Loading Addins");
                    }

                    for (int n = 0; n < addins.Count; n++)
                    {
                        if (statusMonitor != null)
                        {
                            statusMonitor.SetProgress((double)n / (double)addins.Count);
                        }

                        Addin iad = (Addin)addins [n];
                        if (IsAddinLoaded(iad.Id))
                        {
                            continue;
                        }

                        if (statusMonitor != null)
                        {
                            statusMonitor.SetMessage(string.Format(GettextCatalog.GetString("Loading {0} add-in"), iad.Id));
                        }

                        if (!InsertAddin(statusMonitor, iad))
                        {
                            return(false);
                        }
                    }
                    return(true);
                }
            }
            catch (Exception ex) {
                ReportError("Add-in could not be loaded: " + ex.Message, id, ex, false);
                if (statusMonitor != null)
                {
                    statusMonitor.ReportError("Add-in '" + id + "' could not be loaded.", ex);
                }
                if (throwExceptions)
                {
                    throw;
                }
                return(false);
            }
        }
Example #60
0
        /// <summary>
        /// Gets the specified tail data.
        /// </summary>
        /// <param name="web">iFolderAdmin object</param>
        /// <param name="fileName">The name of the file to tail.</param>
        /// <param name="fileLength">The current length of the file.</param>
        /// <param name="ti">The tail information saved on the session.</param>
        /// <param name="length">Receives the total length of the data in the ArrayList.</param>
        /// <returns>An array of byte arrays containing file data.</returns>
        private ArrayList GetTailData(iFolderAdmin web, string fileName, long fileLength, TailInfo ti, out int length)
        {
            ArrayList tailLines = new ArrayList(ti.Lines);

            length = 0;

            // Build the path to the log handler.
            UriBuilder uri = new UriBuilder(web.Url);

            uri.Path = String.Format("/simias10/admindata/{0}", fileName);

            // Is this a first request?
            if (ti.Offset == -1)
            {
                // Have to guess how much data to request.
                byte[] buffer = new byte[ti.Lines * 256];

                // Read one buffer size from the end of the file.
                long readLength = (fileLength > buffer.Length) ? buffer.Length : fileLength;

                // Calculate the offset to read from.
                ti.Offset = fileLength - readLength;

                // Add the query string part.
                uri.Query = String.Format("offset={0}&length={1}", ti.Offset, readLength);

                // Build the web request to get the data.
                HttpWebRequest webRequest = WebRequest.Create(uri.Uri) as HttpWebRequest;
                webRequest.Method          = "GET";
                webRequest.PreAuthenticate = true;
                webRequest.Credentials     = web.Credentials;
                webRequest.CookieContainer = web.CookieContainer;

                HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
                try
                {
                    Stream sr        = webResponse.GetResponseStream();
                    int    bytesRead = sr.Read(buffer, 0, ( int )readLength);
                    if (bytesRead > 0)
                    {
                        // Get the specified number of lines until the data is all read.
                        for (int lines = 0, eob = bytesRead - 1;
                             (lines < ti.Lines) && (eob >= 0);
                             ++lines)
                        {
                            byte[] line = GetLineData(buffer, eob, true);
                            if (line.Length > 0)
                            {
                                tailLines.Add(line);
                                eob    -= line.Length;
                                length += line.Length;
                            }
                            else
                            {
                                // No lines exist in the buffer. Return no data.
                                eob = -1;
                            }
                        }

                        // If any data was returned, update the offset.
                        if (tailLines.Count > 0)
                        {
                            ti.Offset += bytesRead;
                            tailLines.Reverse();
                        }
                    }
                }
                finally
                {
                    webResponse.Close();
                }
            }
            else
            {
                // See if there is data to read.
                long readLength = fileLength - ti.Offset;
                if (readLength > 0)
                {
                    // Make sure the read request is not too large.
                    if (readLength > BufferSize)
                    {
                        readLength = BufferSize;
                    }

                    // Read to the end of the file.
                    byte[] buffer = new byte[readLength];

                    // Add the query string part.
                    uri.Query = String.Format("offset={0}&length={1}", ti.Offset, readLength);

                    // Build the web request to get the data.
                    HttpWebRequest webRequest = WebRequest.Create(uri.Uri) as HttpWebRequest;
                    webRequest.Method          = "GET";
                    webRequest.PreAuthenticate = true;
                    webRequest.Credentials     = web.Credentials;
                    webRequest.CookieContainer = web.CookieContainer;

                    HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
                    try
                    {
                        Stream sr        = webResponse.GetResponseStream();
                        int    bytesRead = sr.Read(buffer, 0, ( int )readLength);
                        if (bytesRead > 0)
                        {
                            // Get the specified number of lines until the data is all read.
                            for (int eob = bytesRead - 1; eob >= 0;)
                            {
                                byte[] line = GetLineData(buffer, eob, false);
                                if (line.Length > 0)
                                {
                                    tailLines.Add(line);
                                    eob    -= line.Length;
                                    length += line.Length;
                                }
                                else
                                {
                                    // No lines exist in the buffer. Return no data.
                                    eob = -1;
                                }
                            }

                            // If any data was returned, update the offset.
                            if (tailLines.Count > 0)
                            {
                                ti.Offset += length;
                                tailLines.Reverse();
                            }
                        }
                    }
                    finally
                    {
                        webResponse.Close();
                    }
                }
            }

            return(tailLines);
        }