Example #1
0
 public int makePalindrome(int[] seq)
 {
     ArrayList pal = new ArrayList();
     for (int i = 0; i < seq.Length; i++)
     {
         pal.Add(seq[i]);
     }
     int left = 0;
     int right = pal.Count - 1;
     int moves = 0;
     while (left < right)
     {
         if ((int)pal[left] < (int)pal[right])
         {
             pal[left] = (int)pal[left] + (int)pal[left + 1];
             pal.RemoveAt(left + 1);
             right--;
             moves++;
         }
         else if ((int)pal[left] > (int)pal[right])
         {
             pal[right] = (int)pal[right] + (int)pal[right - 1];
             pal.RemoveAt(right - 1);
             right--;
             moves++;
         }
         else
         {
             left++;
             right--;
         }
     }
     return moves;
 }
Example #2
0
    public void initialize(int numCharacters)
    {
        spawnPoints = new ArrayList ();

        for (int i = 1; i <= 40; i++) {
            GameObject tempObject = GameObject.Find("SpawnPoint" + i);

            if(tempObject)
                spawnPoints.Add(tempObject);
        }

        ArrayList initialSpawnPoints = new ArrayList();
        initialSpawnPoints.AddRange (spawnPoints);

        characterList = new ArrayList ();

        int randomSpawnIndex = Random.Range (0, initialSpawnPoints.Count - 1);
        makeCharacter("Player", "Materials/Player1Color", "Player", ((GameObject)initialSpawnPoints[randomSpawnIndex]).transform.position, new Color (0, 1, 0));
        initialSpawnPoints.RemoveAt (randomSpawnIndex);

        for(int j = 1; j < numCharacters; j++) {
            randomSpawnIndex = Random.Range (0, initialSpawnPoints.Count - 1);
            makeCharacter ("Player", "Materials/EnemyColor", "MediumAI", ((GameObject)initialSpawnPoints[randomSpawnIndex]).transform.position, new Color (1, 0, 0));
            initialSpawnPoints.RemoveAt (randomSpawnIndex);
        }
    }
Example #3
0
    public static string[] getFilesFromBaseDir()
    {
        string baseDir = "~/";

        List<string> fileResults = new List<string>();
        ArrayList directories = new ArrayList();

        // Add inital Directory to our ArrayList
        directories.Add(baseDir);

        // Loop while there is something in our ArrayList
        while (directories.Count > 0)
        {
            // Get directory from ArrayList
            string currentDir = directories[0].ToString();

            // Remove element from ArrayList
            directories.RemoveAt(0);

            // Add all files in this directory
         //   foreach (string fileName in Directory.GetFiles(currentDir, "*.*"))
         //   {
         //       fileResults.Add(fileName);
         //   }

            // Add all directories in currentDir
            foreach (string dirName in Directory.GetDirectories(currentDir))
            {
                directories.Add(dirName);
            }
        }
        return fileResults.ToArray();
    }
    void CreateOperation()
    {
        ArrayList indexArray = new ArrayList ();
        ArrayList selectedIndex = new ArrayList ();
        firstOperator = (int)(1 + Random.value * 9);
        secondOperator = (int)(1 + Random.value * 9);
        for (int i = 0; i < 5; i++) {
            indexArray.Add (i);
        }
        for (int i = 0; i < 5; i++) {
            int selected = (int)(Random.value * (indexArray.Count - 1));
            selectedIndex.Add (indexArray[selected]);
            indexArray.RemoveAt(selected);
        }
        answers [0] = firstOperator * secondOperator;
        answers [1] = firstOperator + secondOperator;
        answers [2] = (firstOperator * 10) + secondOperator;
        answers [3] = (int)(1 + Random.value * 99);
        answers [4] = (int)(1 + Random.value * 99);
        correctAnswer = answers [0].ToString ();

        for (int i = 0; i < 5; i++) {
            balls [i].text = answers [(int)selectedIndex[i]].ToString();
        }

        operationText.text = firstOperator.ToString() + " X " + secondOperator.ToString();
    }
Example #5
0
 private void Permute(int[] dig, ArrayList chosen)
 {
     if (chosen.Count == dig.Length) {
         int num = 0;
         int baseNum = 1;
         for (int i=0; i < chosen.Count; i++) {
             num += dig[(int)chosen[i]]*baseNum;
             baseNum *= 10;
         }
         if (!res.ContainsKey(num))
             res.Add(num, true);
         return;
     }
     for (int i = 0; i < dig.Length; i++)
     {
         bool found = false;
         for (int j = 0; j < chosen.Count; j++)
         {
             if ((int)chosen[j] == i)
                 found = true;
         }
         if (found)
             continue;
         chosen.Add(i);
         Permute(dig, chosen);
         chosen.RemoveAt(chosen.Count - 1);
     }
 }
Example #6
0
    public void fill4(int x, int y, Color32 oldColor, Color32 newColor)
    {
        ArrayList stack = new ArrayList();

        stack.Add(new Vec2i(x,y));

        int emergency = 10000;

        while(stack.Count > 0 && emergency >= 0) {

            Vec2i pixel = (Vec2i)stack[stack.Count - 1];
            stack.RemoveAt(stack.Count - 1);

            if(canvas.GetPixel(pixel.x, pixel.y) == oldColor) {

                canvas.SetPixel(pixel.x, pixel.y, newColor);

                if(pixel.x + 1 < 96 && canvas.GetPixel(pixel.x + 1, pixel.y) == oldColor)
                    stack.Add(new Vec2i(pixel.x + 1, pixel.y));

                if(pixel.x - 1 >= 0 && canvas.GetPixel(pixel.x - 1, pixel.y) == oldColor)
                    stack.Add(new Vec2i(pixel.x - 1, pixel.y));

                if(pixel.y + 1 < 64 && canvas.GetPixel(pixel.x, pixel.y + 1) == oldColor)
                    stack.Add(new Vec2i(pixel.x, pixel.y + 1));

                if(pixel.y - 1 >= 0 && canvas.GetPixel(pixel.x, pixel.y - 1) == oldColor)
                    stack.Add(new Vec2i(pixel.x, pixel.y - 1));

            }

            emergency--;

        }
    }
	// Use this for initialization
	void Start()
	{
		this.playerCanClick = true;

		this.aCards = new ArrayList();
		this.aGrid = new Card[rows][];

		this.aCardsFlipped = new ArrayList();

		BuildDeck();

		for (int i = 0; i < rows; i++)
		{
			aGrid[i] = new Card[cols];

			for (int j = 0; j < cols; j++)
			{
				int someNum = UnityEngine.Random.Range(0, aCards.Count);
				aGrid[i][j] = (Card)aCards[someNum];
				aCards.RemoveAt(someNum);
			}
		}


	}
Example #8
0
    public void calculateCheckpoints()
    {
        LevelPropertiesScript properties = LevelPropertiesScript.sharedInstance();
        this.checkpoints = new ArrayList(properties.powerups.Count);

        ArrayList placesToGo = new ArrayList(properties.powerups.Count);
        foreach (GameObject powerup in properties.powerups)
        {
            placesToGo.Add(powerup.transform.position);
        }

        Vector3 nextPos = (Vector3)placesToGo[0];
        this.checkpoints.Add(nextPos);
        placesToGo.RemoveAt(0);
        while (placesToGo.Count > 0)
        {
            float minDistance = float.MaxValue;
            Vector3 closestPosition = nextPos;
            foreach (Vector3 position in placesToGo)
            {
                float dist = Vector3.SqrMagnitude(position - nextPos);
                if (dist < minDistance)
                {
                    closestPosition = position;
                    minDistance = dist;
                }
            }

            nextPos = closestPosition;
            this.checkpoints.Add(closestPosition);
            placesToGo.Remove(closestPosition);
        }
    }
Example #9
0
        static void playWithArrayList()
        {
            ArrayList lst = new ArrayList() {1,2,3};
            Debug.WriteLine("capacity {0}", lst.Capacity);
            Debug.WriteLine("count {0}", lst.Count);
            int a = 0;
            lst.Add(a = 15);
            lst.Add(null);
            lst.Add(new Car("diesel", 150, 200));
            lst.Add(10.25f);
            Debug.WriteLine("capacity {0}", lst.Capacity);
            Debug.WriteLine("count {0}", lst.Count);
            lst.Insert(2, "insert");
            lst.Add(15);
            Debug.WriteLine("capacity {0}", lst.Capacity);
            Debug.WriteLine("count {0}", lst.Count);
            lst.RemoveAt(1);
            lst.Add(a);
            lst.Remove(a);
            lst.Remove(15);
            Debug.WriteLine("capacity {0}", lst.Capacity);
            Debug.WriteLine("count {0}", lst.Count);
            Console.WriteLine(lst.IndexOf(15));

            foreach (Object obj in lst)
                Console.WriteLine(obj);
        }
Example #10
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 #11
0
    void Search(ArrayList array, float effectDist)
    {
        if (array == null) return;

        int i = 0;
        while (i < array.Count)
        {
            GameObject target = array[i] as GameObject;
            if (target == null)
            {
                i++;
                continue;
            }

            float dist = Vector3.Distance(target.transform.position, player.transform.position);
            if (dist < effectDist)
            {
                // 指定距離以内だったらアクティブソナーがヒット
                target.BroadcastMessage("OnActiveSonar");
                // ソナー対象リストから外す
                array.RemoveAt(i);
            }
            else i++;
        }
    }
    public void DeleteNode(int i)
    {
        if (i < 0 || i >= nodes.Length) Debug.LogError("You are  trying to DELETE a node which does not exist. Max node index : " +  (nodes.Length - 1) + " . Index wanted : " + i);

        ArrayList n = new ArrayList(nodes);
        ArrayList ha = new ArrayList(handlesA);
        ArrayList hb = new ArrayList(handlesB);
        //ArrayList a = new ArrayList(A);
        //ArrayList b = new ArrayList(B);
        //ArrayList c = new ArrayList(C);

        n.RemoveAt(i);
        ha.RemoveAt(i);
        hb.RemoveAt(i);
        //a.RemoveAt(i);
        //b.RemoveAt(i);
        //c.RemoveAt(i);

        nodes =     (Vector3 []) n.ToArray(typeof(Vector3));
        handlesA =     (Vector3 []) ha.ToArray(typeof(Vector3));
        handlesB =     (Vector3 []) hb.ToArray(typeof(Vector3));
        //A =         (Vector3 []) a.ToArray(typeof(Vector3));
        //B =         (Vector3 []) b.ToArray(typeof(Vector3));
        //C =         (Vector3 []) c.ToArray(typeof(Vector3));
    }
Example #13
0
File: News.cs Project: okeyka/LD33
 public static void AddNewsToCur(ArrayList allNews, ArrayList curNews)
 {
     if (allNews.Count > 0) {
         int i = UnityEngine.Random.Range(0, allNews.Count);
         curNews.Add(allNews[i]);
         allNews.RemoveAt(i);
     }
 }
Example #14
0
 public int calculate(string[] cards)
 {
     ArrayList c = new ArrayList(cards);
     int removed = 0;
     bool moved = true;
     while (moved)
     {
         moved = false;
         int bestRem = -1;
         int bestRemScore = 0;
         for (int i = 1; i < c.Count-1; i++)
         {
             int common = comp((string)c[i - 1], (string)c[i + 1]);
             if (common >= 2)
             {
                 int score = 3;
                 if (i > 1)
                 {
                     int comB = comp((string)c[i - 2], (string)c[i]);
                     int comC = comp((string)c[i - 2], (string)c[i + 1]);
                     if (comB >= 2 && comC < 2)
                     {
                         score--;
                     }
                     else if (comB < 2 && comC >= 2)
                     {
                         score++;
                     }
                 }
                 if (i < c.Count - 2)
                 {
                     int comB = comp((string)c[i + 2], (string)c[i]);
                     int comC = comp((string)c[i - 1], (string)c[i + 2]);
                     if (comB >= 2 && comC < 2)
                     {
                         score--;
                     }
                     else if (comB < 2 && comC >= 2)
                     {
                         score++;
                     }
                 }
                 if (score > bestRemScore)
                 {
                     bestRemScore = score;
                     bestRem = i;
                 }
             }
         }
         if (bestRem != -1)
         {
             c.RemoveAt(bestRem);
             moved = true;
             removed++;
         }
     }
     return removed;
 }
Example #15
0
	// Use this for initialization
	void Start () 
	{
		// Grab the tree array from the terrain
		treeArray = new ArrayList(Terrain.activeTerrain.terrainData.treeInstances);
		int originalCount = treeArray.Count -1;
		//Debug.Log("Tree instances: " + originalCount);
		
		// Substitute all the trees for game objects
		for(int i = 0; i <= originalCount; i++)
		{
			GameObject newTree = null;
			
			switch(((TreeInstance)treeArray[0]).prototypeIndex)
			{
				case 0 : 
				{
					newTree = GameObject.Instantiate(Resources.Load("PoC Prefabs/OakTree")) as GameObject;
				}; break; 
				
				case 1 : 
				{
					newTree = GameObject.Instantiate(Resources.Load("PoC Prefabs/PalmTree")) as GameObject;
				}; break; 
				
				default : 
				{
					return;
				}
			}
			
			// Set the properties
			newTree.transform.position = new Vector3(
				Terrain.activeTerrain.terrainData.size.x * ((TreeInstance)treeArray[0]).position.x, 
				Terrain.activeTerrain.terrainData.size.y * ((TreeInstance)treeArray[0]).position.y, 
				Terrain.activeTerrain.terrainData.size.z * ((TreeInstance)treeArray[0]).position.z
			);
			
			newTree.transform.localScale = new Vector3(
				((TreeInstance)treeArray[0]).widthScale, 
				((TreeInstance)treeArray[0]).heightScale, 
				((TreeInstance)treeArray[0]).widthScale
			);
			
			// Remove this tree
			treeArray.RemoveAt(0);
		}
		
		// Remove the built-in trees from the terrain
		TreeInstance[] tmpArray = new TreeInstance[0];
		treeArray.CopyTo(tmpArray);
		Terrain.activeTerrain.terrainData.treeInstances = tmpArray;
		
		// Refresh the terrain
		float[,] heights = Terrain.activeTerrain.terrainData.GetHeights(0, 0, 0, 0);
		Terrain.activeTerrain.terrainData.SetHeights(0, 0, heights);
		
		//Debug.Log("Done");
	}
Example #16
0
        public void TestAddAndRemove()
        {
            StringBuilder sbl3 = new StringBuilder(99);
            StringBuilder sbl4 = new StringBuilder(99);

            int[] in4a = new int[9];

            // Construct, and verify small capacity
            ArrayList al2 = new ArrayList(1);
            in4a[0] = al2.Capacity;
            Assert.Equal(1, in4a[0]);

            // Add the first obj
            sbl3.Length = 0;
            sbl3.Append("hi mom");

            al2.Add(sbl3);
            sbl4 = (StringBuilder)al2[0];

            Assert.Equal(sbl4.ToString(), sbl3.ToString());

            // Add another obj, verify that Add auto increases Capacity when needed.
            sbl3.Length = 0;
            sbl3.Append("low dad");

            al2.Add(sbl3);
            in4a[1] = al2.Capacity;
            Assert.True(in4a[1] > 1);
            Assert.True(in4a[1] > 1);

            sbl3 = (StringBuilder)al2[1];
            Assert.Equal(sbl4.ToString(), sbl3.ToString());

            // 
            int p_inLoops0 = 2; 
            int p_inLoops1 = 2;
 
            al2 = new ArrayList();

            for (int aa = 0; aa < p_inLoops0; aa++)
            {
                al2.Capacity = 1;

                for (int bb = 0; bb < p_inLoops1; bb++)
                {
                    al2.Add("aa==" + aa + " ,bb==" + bb);
                }

                while (al2.Count > 0)
                {
                    al2.RemoveAt(0);
                }
            }

            Assert.Equal(0, al2.Count);
        }
Example #17
0
 public static ArrayList ShuffleList(ArrayList _list)
 {
     ArrayList randomizedList = new ArrayList();
     while (_list.Count > 0) {
         int index = Random.Range(0, _list.Count);
         randomizedList.Add(_list[index]);
         _list.RemoveAt(index);
     }
     return randomizedList;
 }
Example #18
0
 public string[] edit(string[] entry)
 {
     ArrayList hashtables = new ArrayList();
     for (int i=0; i<entry.Length;i++) {
         string[] splits = entry[i].Split(' ');
         Hashtable hashtable = new Hashtable();
         for (int j=0; j<splits.Length;j++) {
             hashtable.Add(splits[j], splits[j]);
         }
         hashtables.Add(hashtable);
     }
     while (true){
         bool changed=false;
         for (int i=hashtables.Count-1;i>=0;i--) {
             Hashtable table = (Hashtable) hashtables[i];
             for (int j=0; j<i;j++) {
                 Hashtable otherTable = (Hashtable) hashtables[j];
                 int count =0;
                 foreach (DictionaryEntry word in table) {
                     if (otherTable.Contains((string)word.Value))
                         count++;
                 }
                 if (count >= 2) {
                     // merge
                     foreach (DictionaryEntry word in table) {
                         otherTable[(string)word.Value] = (string)word.Value;
                     }
                     hashtables.RemoveAt(i);
                     changed = true;
                     break;
                 }
             }
         }
         if (!changed)
             break;
     }
     string[] results = new string[hashtables.Count];
     for (int i=0; i<hashtables.Count;i++) {
         Hashtable table = (Hashtable) hashtables[i];
         string[] words = new string[table.Count];
         int index=0;
         foreach (DictionaryEntry word in table) {
             words[index] = (string)word.Value;
             index++;
         }
         Array.Sort(words);
         results[i] = "";
         for (int j=0; j<words.Length;j++) {
             results[i] += words[j] + " ";
         }
         results[i] = results[i].Substring(0, results[i].Length-1);
     }
     Array.Sort(results);
     return results;
 }
Example #19
0
    public void RecomputeCityTravelCosts(int step, Player player)
    {
        //if player has no cities, just current step value of city
        //if city is not available at step, return failure
        //if player has city, it is the cheapest combined edge + step value of city

        //clear cities
        foreach(City c in cities)
            c.effectiveTravelCost = -1;

        //if player has no cities, they are at face value
        if (player.cities.Count == 0) {
            foreach(City c in cities)
                c.effectiveTravelCost = 0;
            return;
        }

        //player has cities, so let's start with these cities.
        //and cover the graph

        ArrayList queuedCities = new ArrayList ();
        foreach (City c in player.cities) {
            c.effectiveTravelCost = 0;
            queuedCities.Add(c);
        }

        //for each city in the queue
        //look at the edges, and see if we can get to the neighorbing city cheaper
        //if so, adjust the neighboring city's effective cost
        //if the city is occupied, we can add that city to the queue.
        while (queuedCities.Count > 0) {
            City c = (City)queuedCities[0];
            queuedCities.RemoveAt(0);

            foreach (Edge e in c.edges) {
                City otherCity;
                if(e.start == c)
                    otherCity = e.end;
                else
                    otherCity = e.start;

                if((otherCity.effectiveTravelCost == -1)||(otherCity.effectiveTravelCost > (e.cost + c.effectiveTravelCost))){

        //					print ("other city cost: " + otherCity.effectiveTravelCost + " new: " + e.cost + " "  +  c.effectiveTravelCost);
                    otherCity.effectiveTravelCost = e.cost + c.effectiveTravelCost;
                    if(otherCity.Occupancy() > 0) {//depends on what the level city being bought?
                        //only cascade search if other city is occupied, then we can pass through
                        queuedCities.Add(otherCity);
                    }
                }
            }
        }
    }
Example #20
0
    private ArrayList aStar(GameObject startTile, GameObject endTile)
    {
        if (!startTile || !endTile)
            return null;

        ArrayList openList;
        ArrayList closedList;
        GameObject currentTile = null;

        closedList = new ArrayList();
        openList = new ArrayList();
        openList.Add(startTile);

        Dictionary<GameObject, float> g = new Dictionary<GameObject, float>();
        g.Add(startTile, 0);
        Dictionary<GameObject, float> f = new Dictionary<GameObject, float>();
        f.Add(startTile, (startTile.transform.position - endTile.transform.position).magnitude);

        Dictionary<GameObject, GameObject> cameFrom = new Dictionary<GameObject, GameObject>();
        fScoreComparer fc = new fScoreComparer();
        fc.fList = f;

        do {
            openList.Sort(fc);
            currentTile = (GameObject)openList[0];
            if (currentTile == endTile)
                return reconstructPath(cameFrom, currentTile);

            openList.RemoveAt(0);
            closedList.Add(currentTile);

            foreach (GameObject item in currentTile.GetComponent<NeighboringTile>().getNeighbors()) {
                if (item == null || closedList.Contains(item))
                    continue;

                float currentScore = g[currentTile];
                float approx = currentScore + (currentTile.transform.position - endTile.transform.position).magnitude;

                if (!openList.Contains(item))
                    openList.Add(item);
                else if (approx >= g[item])
                    continue;

                cameFrom[item] = currentTile;
                g[item] = approx;
                f[item] = approx + 0; // 0 = heuristic cost. Not implemented yet.
            }

        } while (openList.Count > 0);

        return null;
    }
    /// <summary>
    /// Destroies the extra instances.
    /// this functtion ensure that just one instance of class existed.
    /// first add instance to instances array then call this function.
    /// you must call this function on top most in the Awake() function.
    /// this class work 
    /// </summary>
    /// 
    public static void DestroyExtraInstances(ArrayList instances )
    {
        if( instances.Count > 1){
            for(int i = 1; i < instances.Count; i++ ){
               if(instances[i] is MonoBehaviour)
                    MonoBehaviour.Destroy((MonoBehaviour)instances[i]);
                else if (instances[i] is ScriptableObject)
                    ScriptableObject.Destroy((ScriptableObject)instances[i]);

                instances.RemoveAt(i);
            }
        }
    }
Example #22
0
        public void RemoveAt()
        {
            var list = new ArrayList<int>(4);
              list.Add(0);
              list.Add(1);
              list.Add(2);
              list.Add(3);
              list.Add(4);

              Assert.That(() => list.RemoveAt(-1), Throws.Exception);
              Assert.That(() => list.RemoveAt(6), Throws.Exception);

              // Remove from start.
              list.RemoveAt(0);
              Assert.AreEqual(4, list.Count);
              Assert.AreEqual(1, list.Array[0]);
              Assert.AreEqual(2, list.Array[1]);
              Assert.AreEqual(3, list.Array[2]);
              Assert.AreEqual(4, list.Array[3]);
              Assert.AreEqual(0, list.Array[4]);

              // Remove from middle.
              list.RemoveAt(2);
              Assert.AreEqual(3, list.Count);
              Assert.AreEqual(1, list.Array[0]);
              Assert.AreEqual(2, list.Array[1]);
              Assert.AreEqual(4, list.Array[2]);
              Assert.AreEqual(0, list.Array[3]);
              Assert.AreEqual(0, list.Array[4]);

              // Remove from end.
              list.RemoveAt(2);
              Assert.AreEqual(2, list.Count);
              Assert.AreEqual(1, list.Array[0]);
              Assert.AreEqual(2, list.Array[1]);
              Assert.AreEqual(0, list.Array[2]);
              Assert.AreEqual(0, list.Array[3]);
              Assert.AreEqual(0, list.Array[4]);
        }
        private void ButtonAddItem_OnClick(object sender, RoutedEventArgs e)
        {
            if (ListBoxLeft.SelectedValue == null)
            {
                return;
            }

            _currentItemText  = ListBoxLeft.SelectedValue.ToString();
            _currentItemIndex = ListBoxLeft.SelectedIndex;

            ListBoxRight.Items.Add(_currentItemText);
            _dataList?.RemoveAt(_currentItemIndex);

            ApplyDataBinding();
        }
Example #24
0
    public static ArrayList getBlob(int [,,] mapData, int stopCode, IntVector3 point)
    {
        /*
        returns a list of IntVector3 voxels that are all connected to i,j,k

        returns an empty list if it finds a voxelCode=hullBase

        prioritize search on neighbors going down, then neighbors at same level, then up
        */
        ArrayList visitedVoxels = new ArrayList ();
        allVisitedVoxels.Add (point);
        visitedVoxels.Add (point);

        frontier = new ArrayList ();
        frontier.Add (point);

        //print ("getBlob " + i + " " + j + " " + k);

        while (frontier.Count>0) {
            IntVector3 seedPoint = (IntVector3)frontier [0];
            frontier.RemoveAt (0);

            foreach (IntVector3 neighbor in MDView.getNeighbors(mapData,seedPoint)) {
                if (! visitedVoxels.Contains (neighbor)) {
                    allVisitedVoxels.Add (neighbor);
                    visitedVoxels.Add (neighbor);

                    //print ("adding to visitedVoxels " + neighbor.i + " " + neighbor.j + " " + neighbor.k);

                    if (neighbor.y < point.y) {
                        frontier.Insert (0, neighbor);
                    } else if (neighbor.y == point.y) {
                        frontier.Insert (frontier.Count / 2, neighbor);
                    } else if (neighbor.y > point.y) {
                        frontier.Insert (frontier.Count, neighbor);
                    }

                    if (mapData [neighbor.x, neighbor.y, neighbor.z] == stopCode) {
                        return new ArrayList ();
                    }
                }
            }
        }

        return visitedVoxels;
    }
Example #25
0
 private ArrayList genUniqueSpawns(int numSpawns)
 {
     ArrayList indexList = new ArrayList();
     for(int i = 0; i < spawnPoints.Count; i++)
     {
         indexList.Add(i);
     }
     ArrayList spawnList = new ArrayList();
     for(int i = 0; i < numEnemiesSpawning; i++)
     {
         int uniqueIndex = Random.Range (0, indexList.Count);
         spawnList.Add (indexList[uniqueIndex]);
         indexList.RemoveAt (uniqueIndex);
     }
     indexList = null;
     return spawnList;
 }
Example #26
0
 IEnumerator SpawnMonster(System.Action callback)
 {
     while (fieldState == FIELD_STATE_START) {
         int oneTimeSpawnCount = Random.Range (1, monsterSpawnPosList.Count);
         ArrayList tempMonsterSpawnPosList = new ArrayList(monsterSpawnPosList);
         for (int i = 0; i < oneTimeSpawnCount; i++) {
             int spawnRowIndex = Random.Range (0, monsterSpawnPosList.Count - 1);
             Vector3 spawnPos = (Vector3) tempMonsterSpawnPosList[spawnRowIndex];
             tempMonsterSpawnPosList.RemoveAt (spawnRowIndex);
             GameObject monsterObj = (GameObject)Instantiate (monsterPrefab, spawnPos, Quaternion.identity);
             Monster monster = monsterObj.GetComponent<Monster> ();
             monsterList.Add (monster);
         }
         yield return new WaitForSeconds (FIELD_MONSTER_SPAWN_INTERVAL);
     }
     callback ();
 }
Example #27
0
 static void BlackDot(string line)
 {
     int pos = line.IndexOf('|');
     string[] playersStr = line.Substring(0,pos).Trim().Split(' ');
     int dot = Convert.ToInt32(line.Substring(pos + 1).Trim());
     ArrayList players = new ArrayList();
     players.AddRange(playersStr);
     while(players.Count>1){
         int dotCounter = 1;
         int index = 0;
         while(true){
             if(dot!=dotCounter){
                 index++;
                 dotCounter++;
                 if(index==players.Count)index=0;
             }else {
                 players.RemoveAt(index);
                 break;
             }
         }
     }
     Console.WriteLine(players[0]);
 }
Example #28
0
        //function second- hien thi item sua
        public static void SuaHH(ref ArrayList ArrayHH, ref ArrayList ArrayLH, string ChucNang, int index, int selected)
        {
            Struct.HOANGHOA item = (Struct.HOANGHOA)ArrayHH[index];
            Form.FormHangHoa("SỬA HÀNG HÓA");
            Console.ForegroundColor = ConsoleColor.White;
            Console.BackgroundColor = ConsoleColor.DarkYellow;
            Console.CursorTop       = 0;
            Console.CursorLeft      = 18;
            Console.WriteLine(" Lựa chọn [UP/DOWN] ");
            Console.CursorTop  = 0;
            Console.CursorLeft = 40;
            Console.WriteLine(" Select [ENTER] ");
            Console.CursorTop  = 0;
            Console.CursorLeft = 58;
            Console.WriteLine(" Home [ESC] ");
            Console.CursorTop       = 27;
            Console.CursorLeft      = 0;
            Console.ForegroundColor = ConsoleColor.White;
            Console.BackgroundColor = ConsoleColor.Blue;
            Console.WriteLine(" Crt + S để lưu lại.");
            FormEditItem(selected, item);
            bool loop = true;

            while (loop)
            {
                ConsoleKeyInfo input;
                input = Console.ReadKey(true);
                if ((input.Modifiers & ConsoleModifiers.Control) != 0 && input.Key == ConsoleKey.S)
                {
                    bool flagSave;
                    flagSave = Form.FormXacNhan(10, 40, 5, 40, ChucNang);
                    if (flagSave)
                    {
                        loop = false;
                        ArrayHH.RemoveAt(index);
                        ArrayHH.Insert(index, item);
                        Console.Clear();
                        Edit.SuaHangHoa(ref ArrayHH, ref ArrayLH);
                        return;
                    }
                    else
                    {
                        loop = false;
                        Console.ForegroundColor = ConsoleColor.Black;
                        Console.BackgroundColor = ConsoleColor.Gray;
                        Console.Clear();
                        SuaHH(ref ArrayHH, ref ArrayLH, ChucNang, index, selected);
                    }
                }
                switch (input.Key)
                {
                case ConsoleKey.UpArrow:
                    if (selected == 1)
                    {
                        selected = 8;
                    }
                    else
                    {
                        selected--;
                    }
                    BgSelectedItem(selected, ref item);
                    break;

                case ConsoleKey.DownArrow:
                    if (selected == 8)
                    {
                        selected = 1;
                    }
                    else
                    {
                        selected++;
                    }
                    BgSelectedItem(selected, ref item);
                    break;

                case ConsoleKey.Enter:
                    Console.CursorVisible = true;
                    item = EditItem(selected, ref item);
                    selected++;
                    BgSelectedItem(selected, ref item);
                    break;

                case ConsoleKey.Escape:
                    loop = false;
                    Console.CursorVisible = false;
                    Tittle.TieuDe();
                    Select.LuaChonChinh(ref ArrayHH, ref ArrayLH, 0);
                    break;

                default:
                    break;
                }
            }
        }
        protected override void OnClicked(int controlId, GUIControl control, Action.ActionType actionType)
        {
            // Enable
            if (control == btnEnableDynamicRefreshRate)
            {
                EnableControls();
                SettingsChanged(true);
            }
            if (_name.ToLower().IndexOf("tv") < 1)
            {
                // Remove
                if (control == btnRemove)
                {
                    int sIndex = lcRefreshRatesList.SelectedListItemIndex;
                    lcRefreshRatesList.RemoveItem(sIndex);
                    _defaultHz.RemoveAt(sIndex);

                    if (sIndex > 0)
                    {
                        sIndex--;
                        lcRefreshRatesList.SelectedListItemIndex = sIndex;
                    }
                    SettingsChanged(true);
                }

                // Default
                if (control == btnDefault)
                {
                    InsertDefaultValues();
                    SettingsChanged(true);
                }

                if (control == btnUseDefaultRefreshRate)
                {
                    if (btnUseDefaultRefreshRate.Selected)
                    {
                        btnSelectDefaultRefreshRate.IsEnabled = true;
                    }
                    else
                    {
                        btnSelectDefaultRefreshRate.IsEnabled = false;
                    }
                    SettingsChanged(true);
                }

                // Add
                if (control == btnAdd)
                {
                    _newRefreshRateListItem = new GUIListItem();
                    _newRateDataInfo        = new RefreshRateData("", "", "", "");
                    OnAddItem();

                    if (_newRateDataInfo.Name != string.Empty)
                    {
                        if (_newRateDataInfo.FrameRate != string.Empty)
                        {
                            if (_newRateDataInfo.Refreshrate != string.Empty)
                            {
                                _newRefreshRateListItem.Label           = _newRateDataInfo.Name;
                                _newRefreshRateListItem.AlbumInfoTag    = _newRateDataInfo;
                                _newRefreshRateListItem.OnItemSelected += OnItemSelected;
                                lcRefreshRatesList.Add(_newRefreshRateListItem);
                                _defaultHz.Add(_name);
                                UpdateRefreshRateDataFields();
                                SetProperties();
                            }
                        }
                    }
                    SettingsChanged(true);
                }
                // Edit
                if (control == btnEdit)
                {
                    OnEditItem();

                    if (_name != string.Empty)
                    {
                        if (_framerate != string.Empty)
                        {
                            if (_refreshrate != string.Empty)
                            {
                                lcRefreshRatesList.SelectedListItem.Label = _name;
                                _newRateDataInfo = new RefreshRateData(_name, _framerate, _refreshrate, _action);
                                lcRefreshRatesList.SelectedListItem.AlbumInfoTag = _newRateDataInfo;
                                _defaultHz[_defaultHzIndex] = _name;
                                UpdateRefreshRateDataFields();
                                SetProperties();
                                SettingsChanged(true);
                            }
                        }
                    }
                }
            }

            // Use default
            if (control == btnUseDefaultRefreshRate)
            {
                EnableControls();
                SettingsChanged(true);
            }

            // Select default refreshrate
            if (control == btnSelectDefaultRefreshRate)
            {
                OnSelectDefaultRefreshRate();
                SettingsChanged(true);
            }

            base.OnClicked(controlId, control, actionType);
        }
Example #30
0
 public void SetNumber(int row, int column, int index, int number)
 {
     _workingSudokuBoard[row - 1][column - 1] = number;
     _cellsRemainToSet.RemoveAt(index);
 }
        public static void Load()
        {
            ArrayList ClassList = new ArrayList();

            if (!File.Exists("Scriptsave.bin") && !File.Exists("Scriptsave.idx"))
            {
                return;
            }

            Console.Write("Scriptsave: Loading...");

            using (FileStream idx = new FileStream("Scriptsave.idx", FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                BinaryFileReader idxReader = new BinaryFileReader(new BinaryReader(idx));

                int Count = idxReader.ReadInt();

                for (int i = 0; i < Count; i++)
                {
                    string ClassName = idxReader.ReadString();

                    ConstructorInfo info = Utility.FindConstructor(ClassName);

                    if (info == null)
                    {
                        Console.WriteLine("failed");
                        Console.WriteLine("Error: Type '{0}' was not found. Delete this type? (y/n)", ClassName);

                        if (Console.ReadLine() == "y")
                        {
                            Console.Write("Scriptsave: Loading...");
                            idxReader.ReadLong();
                            idxReader.ReadInt();
                        }
                        else
                        {
                            Console.WriteLine("Type will not be deleted. An exception will be thrown when you press return");
                            Console.ReadLine();
                            throw new Exception(String.Format("Bad type '{0}'", ClassName));
                        }
                    }
                    else
                    {
                        long pos    = idxReader.ReadLong();
                        int  length = idxReader.ReadInt();
                        if (info.Invoke(null) is ISerialize)
                        {
                            ClassList.Add(new ClassEntry(ClassName, pos, length));
                        }
                        else
                        {
                            Console.WriteLine("failed");
                            Console.WriteLine("Error: Type '{0}' is not ISerialize. Delete this type? (y/n)", ClassName);
                            if (Console.ReadLine() == "y")
                            {
                                Console.Write("Scriptsave: Loading...");
                            }
                            else
                            {
                                Console.WriteLine("Type will not be deleted. An exception will be thrown when you press return");
                                Console.ReadLine();
                                throw new Exception(String.Format("Bad type '{0}'", ClassName));
                            }
                        }
                    }
                }
            }

            if (File.Exists("Scriptsave.bin"))
            {
                using (FileStream bin = new FileStream("Scriptsave.bin", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin));

                    for (int i = 0; i < ClassList.Count; ++i)
                    {
                        ClassEntry entry = (ClassEntry)ClassList[i];
                        ISerialize ser   = entry.Class;

                        reader.Seek(entry.Position, SeekOrigin.Begin);

                        ser.Deserialize(reader);
                        if (reader.Position != (entry.Position + entry.Length))
                        {
                            Console.WriteLine("failed");
                            Console.WriteLine(String.Format("***** Bad serialize on '{0}' type *****", entry.ClassName));
                            Console.WriteLine("Do you want to remove this serialize? (y/n)");
                            string FailName = entry.ClassName;
                            if (Console.ReadLine() == "y")
                            {
                                ClassList.RemoveAt(i);
                                BinaryFileWriter idx = new BinaryFileWriter("Scriptsave.idx");
                                idx.Write(ClassList.Count);
                                foreach (ClassEntry classentry in ClassList)
                                {
                                    idx.Write(classentry.ClassName);
                                    idx.Write(classentry.Position);
                                    idx.Write(classentry.Length);
                                }
                                idx.Close();
                                Console.WriteLine("Serialization of '" + FailName + "' removed.");
                                Console.WriteLine("An exception will be thrown when you press return");
                                Console.ReadLine();
                                throw new Exception(String.Format("Bad serialize"));
                            }
                            else
                            {
                                Console.WriteLine("Serialization of '" + FailName + "' don't removed.");
                                Console.WriteLine("An exception will be thrown when you press return");
                                Console.ReadLine();
                                throw new Exception(String.Format("Bad serialize"));
                            }
                        }
                    }
                    reader.Close();
                    Console.WriteLine("done");
                }
            }
        }
Example #32
0
 public void RemoveIntervalAt(int index)
 {
     _durations.RemoveAt(index);
 }
Example #33
0
 public override void removeChild(int at)
 {
     dataset_.RemoveAt(at);
 }
Example #34
0
 /// <summary>
 /// Removes a MenuItem from a particular ordinal position in the collection.
 /// </summary>
 /// <param name="index">The ordinal position of the MenuItem to remove.</param>
 public void RemoveAt(int index)
 {
     menuItems.RemoveAt(index);
 }
    /*
     *
     *
     */
    public ArrayList AvailableCount(Vector2 _start, Vector2 _direction)
    {
        ArrayList toclaim = new ArrayList ();
        ArrayList jumppoint = new ArrayList ();
        Vector2[] cardir = new Vector2[4];
        cardir [0] = Vector2.up;
        cardir [1] = -Vector2.up;
        cardir [2] = Vector2.right;
        cardir [3] = -Vector2.right;
        Vector2 currentpoint = _start;
        Vector2 checkpoint;

        while (true) {
            toclaim.Add (currentpoint);
            for (int i = 0; i < cardir.Length; i++) {
                if (_direction != cardir[i]) {
                    if (map [(int)(currentpoint.x + cardir[i].x), (int)(currentpoint.y + cardir[i].y)] == 0) {
                        checkpoint = (currentpoint + cardir[i]);
                        if (!toclaim.Contains(checkpoint) && !jumppoint.Contains(checkpoint)) {
                            jumppoint.Add(checkpoint);
                        }
                    }
                }
            }

            if (map [(int)(currentpoint.x + _direction.x), (int)(currentpoint.y + _direction.y)] != 0) {
                if (jumppoint.Count > 0) {
                    currentpoint = (Vector2)jumppoint [0];
                    jumppoint.RemoveAt (0);
                } else {
                    return toclaim;
                }
            } else {
                currentpoint += _direction;
            }
        }

        return toclaim;
    }
Example #36
0
    // Update is called once per frame
    void Update()
    {
        if (mytext != null)
        {
            mytext.text = CureList.Count.ToString();
        }

        Vector3 myposition = userPostionControll.currectPostion;
        Ray     ray        = new Ray(myposition + Vector3.up * .1f, -Vector3.up * 1.2f);

        Debug.DrawRay(myposition + Vector3.up * .1f, -Vector3.up * 1.2f, Color.black);
        RaycastHit hit;

        Physics.Raycast(myposition + Vector3.up * .1f, -Vector3.up, out hit, 20f, cureCheckMask);
        GameObject o = hit.collider.gameObject;

        TurnZeroPoint =
            new Vector3(userPostionControll.currectPostion.x, o.transform.position.y, userPostionControll.currectPostion.z) +
            new Vector3(0, 1, 0);
        if (Input.GetKeyDown(KeyCode.J) || isJ)
        {
            bool exist = false;
            foreach (GameObject g in CureList)
            {
                if (g == o)
                {
                    exist = true;
                }
            }
            if (!exist && o.tag != "Plane")
            {
                CureList.Add(o);
            }
            foreach (GameObject g in CureList)
            {
                g.GetComponent <Renderer>().material = turnMat;
                g.transform.localScale = new Vector3(0.98f, 0.98f, 0.98f);
            }
            isJ = false;
        }
        if (Input.GetKeyDown(KeyCode.K) || isK)
        {
            if (CureList.Count != 0)
            {
                GameObject g = CureList[CureList.Count - 1] as GameObject;
                g.GetComponent <Renderer>().material = defaultMat;
                g.transform.localScale = new Vector3(0.96f, 0.96f, 0.96f);
                CureList.RemoveAt(CureList.Count - 1);
            }
            isK = false;
        }

        //按照y轴旋转
        if (Input.GetKeyDown(KeyCode.LeftArrow) || isLeft)
        {
            foreach (GameObject g in CureList)
            {
                Vector3 p = new Vector3(Mathf.RoundToInt(TurnZeroPoint.x - (TurnZeroPoint.z - g.transform.position.z)),
                                        Mathf.RoundToInt(g.transform.position.y), Mathf.RoundToInt(TurnZeroPoint.z + (TurnZeroPoint.x - g.transform.position.x)));
                g.transform.position = p;
            }
            isLeft = false;
        }
        if (Input.GetKeyDown(KeyCode.RightArrow) || isRight)
        {
            foreach (GameObject g in CureList)
            {
                Vector3 p = new Vector3(Mathf.RoundToInt(TurnZeroPoint.x + (TurnZeroPoint.z - g.transform.position.z)),
                                        Mathf.RoundToInt(g.transform.position.y), Mathf.RoundToInt(TurnZeroPoint.z - (TurnZeroPoint.x - g.transform.position.x)));
                g.transform.position = p;
            }
            isRight = false;
        }
        //按照摄像头水平为轴旋转
        Transform tCamera = Camera.main.transform;

        if (Input.GetKeyDown(KeyCode.UpArrow) || isUp)
        {
            if (Mathf.Abs(0 - tCamera.forward.z) > 0.001)
            {
                foreach (GameObject g in CureList)
                {
                    Vector3 p = new Vector3(Mathf.RoundToInt(g.transform.position.x),
                                            Mathf.RoundToInt(TurnZeroPoint.y + (TurnZeroPoint.z - g.transform.position.z)),
                                            Mathf.RoundToInt(TurnZeroPoint.z - (TurnZeroPoint.y - g.transform.position.y)));
                    g.transform.position = p;
                }
            }
            if (Mathf.Abs(0 - tCamera.forward.x) > 0.001)
            {
                foreach (GameObject g in CureList)
                {
                    Vector3 p = new Vector3(Mathf.RoundToInt(TurnZeroPoint.x + (TurnZeroPoint.y - g.transform.position.y)),
                                            Mathf.RoundToInt(TurnZeroPoint.y - (TurnZeroPoint.x - g.transform.position.x)), Mathf.RoundToInt(g.transform.position.z));
                    g.transform.position = p;
                }
            }
            isUp = false;
        }
        if (Input.GetKeyDown(KeyCode.DownArrow) || isDown)
        {
            if (Mathf.Abs(0 - tCamera.forward.z) > 0.001)
            {
                foreach (GameObject g in CureList)
                {
                    Vector3 p = new Vector3(Mathf.RoundToInt(g.transform.position.x),
                                            Mathf.RoundToInt(TurnZeroPoint.y - (TurnZeroPoint.z - g.transform.position.z)),
                                            Mathf.RoundToInt(TurnZeroPoint.z + (TurnZeroPoint.y - g.transform.position.y)));
                    g.transform.position = p;
                }
            }
            if (Mathf.Abs(0 - tCamera.forward.x) > 0.001)
            {
                foreach (GameObject g in CureList)
                {
                    Vector3 p = new Vector3(Mathf.RoundToInt(TurnZeroPoint.x - (TurnZeroPoint.y - g.transform.position.y)),
                                            Mathf.RoundToInt(TurnZeroPoint.y + (TurnZeroPoint.x - g.transform.position.x)), Mathf.RoundToInt(g.transform.position.z));
                    g.transform.position = p;
                }
            }
            isDown = false;
        }
    }
Example #37
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 #38
0
    static void Main(string[] args)
    {
        // Enter user id, password, and Oracle data source (i.e. net service name, EZ Connect, etc.)
        string constr = "user id=<USER ID>;password=<PASSWORD>;data source=<DATA SOURCE>";

        string sql1 = "select col1 from odp_varray_sample_rel_tab";
        string sql2 = "odp_varray_sample_proc";

        // Create a new simple varray with values 1, 2, 3, and 4.
        SimpleVarray pa = new SimpleVarray();

        pa.Array = new Int32[] { 1, 2, 3, 4 };

        // Create status array and indicate element 2 is Null.
        pa.StatusArray = new OracleUdtStatus[] { OracleUdtStatus.NotNull,
                                                 OracleUdtStatus.Null, OracleUdtStatus.NotNull, OracleUdtStatus.NotNull };

        OracleConnection con    = null;
        OracleCommand    cmd    = null;
        OracleDataReader reader = null;

        try
        {
            // Establish a connection to Oracle DB.
            con = new OracleConnection(constr);
            con.Open();

            cmd             = new OracleCommand(sql2, con);
            cmd.CommandType = CommandType.StoredProcedure;

            OracleParameter param = new OracleParameter();
            param.OracleDbType = OracleDbType.Array;
            param.Direction    = ParameterDirection.InputOutput;

            // Note: The UdtTypeName is case-senstive.
            param.UdtTypeName = "ODP_VARRAY_SAMPLE_TYPE";
            param.Value       = pa;
            cmd.Parameters.Add(param);

            // Insert SimpleVarray(1, NULL, 3, 4) into the table.
            // The stored procedure adds a fifth VARRAY element with a value
            //  of 9, then inserts the VARRAY into the table.
            cmd.ExecuteNonQuery();

            // Print out the updated Simple Varray.
            // Results should return values: 1, NULL, 3, 4, and 9.
            Console.WriteLine("Updated SimpleVarray: " + param.Value);
            Console.WriteLine();

            // Modify element 3 to Null and element 2 to Not Null.
            pa.StatusArray[1] = OracleUdtStatus.NotNull;
            pa.StatusArray[2] = OracleUdtStatus.Null;

            param.Value = pa;

            // Insert SimpleVarray(1, 2, NULL, 4) into the table.
            // The stored procedure adds a fifth VARRAY element with a value
            //  of 9, then inserts the VARRAY into the table.
            cmd.ExecuteNonQuery();

            // Print out the updated Simple Varray.
            // Results should return values: 1, 2, NULL, 4, and 9.
            Console.WriteLine("Updated SimpleVarray: " + param.Value);
            Console.WriteLine();

            // Add/Remove some elements by converting the Int32[] to an ArrayList.
            ArrayList pa1 = new ArrayList(pa.Array);

            // Create a corresponding array list to track each element's
            //  Null or NotNull status.
            ArrayList sa1 = new ArrayList(pa.StatusArray);

            // Remove the first element. (2, 3, 4)
            pa1.RemoveAt(0);
            sa1.RemoveAt(0);

            // Add element 6. (2, 3, 4, 6)
            pa1.Add(6);
            sa1.Add(OracleUdtStatus.NotNull);

            // Add element -1. (2, 3, 4, 6, -1)
            pa1.Add(-1);
            // Make the new element NULL now when inserted into DB.
            sa1.Add(OracleUdtStatus.Null);

            // Convert ArrayLists into a SimpleVarray
            pa.Array       = (Int32[])pa1.ToArray(typeof(Int32));
            pa.StatusArray = (OracleUdtStatus[])sa1.ToArray(typeof(OracleUdtStatus));

            param.Value = pa;

            Console.WriteLine("Updated SimpleVarray: " + param.Value);
            Console.WriteLine();

            // Insert SimpleVarray(2, NULL, 4, 6, NULL) into the table.
            // The stored procedure adds a sixth VARRAY element with a value
            //  of 9, then inserts the VARRAY into the table.
            cmd.ExecuteNonQuery();

            cmd.CommandText = sql1;
            cmd.CommandType = CommandType.Text;
            reader          = cmd.ExecuteReader();

            // Fetch each row and display the VARRAY data.
            // Results should return values 2, NULL, 4, 6, NULL, and 9
            // for the last SimpleArray returned.
            int rowCount = 1;
            while (reader.Read())
            {
                // Fetch the objects as custom types.
                SimpleVarray p;
                if (reader.IsDBNull(0))
                {
                    p = SimpleVarray.Null;
                }
                else
                {
                    p = (SimpleVarray)reader.GetValue(0);
                }

                Console.WriteLine("Row {0}: {1}", rowCount++, p);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            // Clean up
            if (reader != null)
            {
                reader.Dispose();
            }
            if (cmd != null)
            {
                cmd.Dispose();
            }
            if (con != null)
            {
                con.Dispose();
            }
        }
    }
Example #39
0
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint   epSender  = (EndPoint)ipeSender;

                serverSocket.EndReceiveFrom(ar, ref epSender);

                var diachiip = epSender.ToString().Split(':')[0];


                // Chuyển mảng byte người nhận
                Data msgReceived = new Data(byteData);

                // Gửi tin nhắn
                Data msgToSend = new Data();

                byte [] message;

                //If the message is to login, logout, or simple text message
                //then when send to others the type of the message remains the same
                msgToSend.cmdCommand = msgReceived.cmdCommand;
                msgToSend.strName    = msgReceived.strName;

                switch (msgReceived.cmdCommand)
                {
                case Command.Login:

                    //Khi một người đăng nhập thì add người đó vào danh sách các client

                    ClientInfo clientInfo = new ClientInfo();
                    clientInfo.endpoint = epSender;
                    clientInfo.strName  = msgReceived.strName;

                    clientList.Add(clientInfo);

                    //Gửi tin nhắn tới tất cả các client đã tham gia phòng
                    msgToSend.strMessage = "<<<" + diachiip + " đã tham gia phòng chat>>>";
                    break;

                case Command.Logout:

                    //Khi một người sử dụng muốn đăng xuất thì server sẽ tìm người đó trong danh sách các client và đóng kết nối của client đó

                    int nIndex = 0;
                    foreach (ClientInfo client in clientList)
                    {
                        if (client.endpoint == epSender)
                        {
                            clientList.RemoveAt(nIndex);
                            break;
                        }
                        ++nIndex;
                    }

                    msgToSend.strMessage = "<<<" + diachiip + " đã rời phòng chat>>>";
                    break;

                case Command.Message:

                    //cài đặt kí tự khi gửi
                    msgToSend.strMessage = msgReceived.strName + ": " + msgReceived.strMessage;
                    break;

                case Command.List:

                    //Gửi tên của tất cả các client đến client mới
                    msgToSend.cmdCommand = Command.List;
                    msgToSend.strName    = null;
                    msgToSend.strMessage = null;

                    // lên danh sách tên client
                    foreach (ClientInfo client in clientList)
                    {
                        msgToSend.strMessage += client.strName + "*";
                    }

                    message = msgToSend.ToByte();

                    //gửi lên phòng chat
                    serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, epSender,
                                             new AsyncCallback(OnSend), epSender);
                    break;
                }

                if (msgToSend.cmdCommand != Command.List)
                {
                    message = msgToSend.ToByte();

                    foreach (ClientInfo clientInfo in clientList)
                    {
                        if (clientInfo.endpoint != epSender ||
                            msgToSend.cmdCommand != Command.Login)
                        {
                            //Gửi tin nhắn tới tất cả mọi client
                            serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientInfo.endpoint,
                                                     new AsyncCallback(OnSend), clientInfo.endpoint);
                        }
                    }

                    txtLog.Text += msgToSend.strMessage + "\r\n";
                }

                //phản hồi từ client khi muốn đăng xuât
                if (msgReceived.cmdCommand != Command.Logout)
                {
                    serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender,
                                                  new AsyncCallback(OnReceive), epSender);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #40
0
    protected void btnSend_Click(object sender, EventArgs e)
    {
        try
        {
            string StrRep = txtEmailAddress.Text.Replace("\r", "");
            string[] str12 = StrRep.Split('\n');
            ArrayList str = new ArrayList();
            foreach (string s in str12)
                str.Add(s);

            ArrayList strMatch = new ArrayList();

            var sList = new ArrayList();

            for (int i = 0; i < str.Count; i++)
            {
                if (sList.Contains(str[i].ToString().Trim()) == false)
                {
                    sList.Add(str[i].ToString().Trim());
                }
            }

            for (int c = 0; c < sList.Count; c++)
            {
                if (sList[c].ToString().Trim() == "")
                {
                    sList.RemoveAt(c);
                }
            }
            ArrayList sNewlist = new ArrayList();
            for (int d = 0; d < sList.Count; d++)
            {
                string[] strNew = sList[d].ToString().Split(' ');

                if (strNew.Length > 0)
                {
                    string sattach = string.Empty;
                    for (int s = 0; s < strNew.Length; s++)
                    {
                        if (s == 0)
                        {
                            sattach = strNew[s].Trim();
                        }
                        else
                        {
                            sattach = sattach + " " + strNew[s].Trim();
                        }
                    }
                    sNewlist.Add(sattach);
                }
                else
                {
                    sNewlist.Add(sList[d]);
                }
            }

            str = sNewlist;
            for (int i = 0; i < str.Count; i++)
            {
                string Username = str[i].ToString();
                string Agentname = objGeneralFunc.ToProper(txtAgentName.Text);
                SendIntromail(Agentname, Username);
            }
            Session.Timeout = 180;
            mpealteruser.Show();
            lblErr.Visible = true;
            lblErr.Text = "Email(s) successfully send";
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 /// <summary>
 /// Removes the object at the specified index of the PropertySpecCollection.
 /// </summary>
 /// <param name="index">The zero-based index of the element to remove.</param>
 public void RemoveAt(int index)
 {
     _innerArray.RemoveAt(index);
 }
Example #42
0
 /// <summary>
 /// Removes a vector from the primitive line object.
 /// </summary>
 /// <param name="index">The index of the vector to remove.</param>
 public void RemoveVector(int index)
 {
     vectors.RemoveAt(index);
 }
Example #43
0
 public void deleteItemFromList(int index)
 {
     list.RemoveAt(index);
 }
 public void RemoveAt(int index)
 {
     arrayList.RemoveAt(index);
 }
Example #45
0
        protected void createNewProduct()
        {
            Dictionary <String, String> allExistingProdDict = (Dictionary <String, String>)Session[SessionFactory.ALL_PRODUCT_CREATE_PRODUCT_EXISTING_NAMES];

            if (allExistingProdDict.ContainsKey(TextBox_Prod_Name.Text.Trim()))
            {
                Label_Status.Text      = "Product Name Already Exists";
                Label_Status.Visible   = true;
                Label_Status.ForeColor = System.Drawing.Color.Red;
            }
            else if (Session[SessionFactory.CREATE_PRODUCT_SELECTED_PRODUCT_CAT] == null || Session[SessionFactory.CREATE_PRODUCT_SELECTED_PRODUCT_CAT].ToString().Equals(""))
            {
                Label_Status.Text      = "Must select one product category";
                Label_Status.Visible   = true;
                Label_Status.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                if (!TextBox_Spec.Text.Equals(""))
                {
                    getAddintionalProdSrvList();
                    TextBox_Spec.Text = "";
                }

                ArrayList prodSpecList = (ArrayList)Session[SessionFactory.CREATE_PRODUCT_CHILD_PROD_SPEC_MAP];

                Dictionary <String, String> rSpecUniqnessValidation = new Dictionary <string, string>();
                String mainEntId = Session[SessionFactory.MAIN_BUSINESS_ENTITY_ID_STRING].ToString();

                if (prodSpecList != null)
                {
                    for (int i = 0; i < prodSpecList.Count; i++)
                    {
                        ShopChildProdsSpecs prodSpecObj = (ShopChildProdsSpecs)prodSpecList[i];

                        prodSpecObj.setProdName(TextBox_Prod_Name.Text);

                        if (rSpecUniqnessValidation.ContainsKey(prodSpecObj.getEntityId() + ":" + prodSpecObj.getProdName() + ":" + prodSpecObj.getFeatId()))
                        {
                            prodSpecList.RemoveAt(i);
                        }
                        else
                        {
                            rSpecUniqnessValidation.Add(prodSpecObj.getEntityId() + ":" + prodSpecObj.getProdName() + ":" + prodSpecObj.getFeatId(), prodSpecObj.getEntityId());
                            if (prodSpecObj != null && prodSpecObj.getFileStream() != null && prodSpecObj.getFileStream().HasFile)
                            {
                                prodSpecObj.setImgPathInFileStore(Session[SessionFactory.MAIN_BUSINESS_ENTITY_ID_STRING].ToString());
                            }
                        }
                    }
                }

                ShopChildProdsInventory childProdObj = new ShopChildProdsInventory();
                childProdObj.setCreatedBy(User.Identity.Name);
                childProdObj.setDateCreated(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                childProdObj.setEntityId(mainEntId);
                childProdObj.setMsrmntUnit(DropDownList_Unit_Of_Msrmnt.SelectedValue);
                childProdObj.setProdCatId(Session[SessionFactory.CREATE_PRODUCT_SELECTED_PRODUCT_CAT].ToString());
                childProdObj.setProdName(TextBox_Prod_Name.Text);
                childProdObj.setQnty((!TextBox_Stock.Text.Equals("")?float.Parse(TextBox_Stock.Text):0));
                childProdObj.setUnitListPrice(TextBox_List_Price.Text);
                childProdObj.setUnitSrcPrice(TextBox_Src_Price.Text);
                childProdObj.setCurrency(DropDownList_Curr.SelectedValue);

                try
                {
                    BackEndObjects.ShopChildProdsInventory.insertShopChildProdsInventoryDB(childProdObj);
                    if (prodSpecList != null)
                    {
                        BackEndObjects.ShopChildProdsSpecs.insertShopChildProdsSpecsListDB(prodSpecList);
                    }

                    //Refresh the session variable with the newly added product name
                    allExistingProdDict.Add(childProdObj.getProdName(), childProdObj.getProdName());
                    Session[SessionFactory.ALL_PRODUCT_CREATE_PRODUCT_EXISTING_NAMES] = allExistingProdDict;

                    Dictionary <String, ProductCategory> existingProdDict = MainBusinessEntity.
                                                                            getProductDetailsforMainEntitybyIdDB(mainEntId);

                    Label_Status.Text                 = "Product/Service Details Created Successfully";
                    Label_Status.Visible              = true;
                    Label_Status.ForeColor            = System.Drawing.Color.Green;
                    DropDownList_Level1.SelectedIndex = -1;
                    DropDownList_Level2.SelectedIndex = -1;
                    DropDownList_Level3.SelectedIndex = -1;


                    if (!existingProdDict.ContainsKey(DropDownList_Level1.SelectedValue))
                    {
                        ArrayList newMainProdCat = new ArrayList();
                        newMainProdCat.Add(DropDownList_Level1.SelectedValue);

                        MainBusinessEntity.insertProductDetailsforEntityDB(mainEntId, newMainProdCat);
                        Label_Status.Text += "...New Product category added to your product list";
                    }

                    DataTable dt = (DataTable)Session[SessionFactory.ALL_PRODUCT_PROD_DATA_GRID];

                    dt.Rows.Add();
                    int count = dt.Rows.Count - 1;

                    dt.Rows[count]["ProdCatId"] = childProdObj.getProdCatId();
                    dt.Rows[count]["ProdName"]  = childProdObj.getProdName();
                    dt.Rows[count]["Stock"]     = childProdObj.getQnty();
                    dt.Rows[count]["msrmnt"]    = childProdObj.getMsrmntUnit();
                    dt.Rows[count]["srcPrice"]  = childProdObj.getUnitSrcPrice();
                    dt.Rows[count]["listPrice"] = childProdObj.getUnitListPrice();
                    dt.Rows[count]["curr"]      = DropDownList_Curr.SelectedItem.Text;

                    Session[SessionFactory.ALL_PRODUCT_PROD_DATA_GRID] = dt;
                    ScriptManager.RegisterStartupScript(this, typeof(string), "RefreshProdGrid", "RefreshParent();", true);
                }
                catch (Exception ex)
                {
                    Label_Status.Text      = "Product/Service Details Creation Failed";
                    Label_Status.Visible   = true;
                    Label_Status.ForeColor = System.Drawing.Color.Red;
                }
                finally
                {
                    Session.Remove(SessionFactory.CREATE_PRODUCT_CHILD_PROD_SPEC_MAP);
                    Session.Remove(SessionFactory.CREATE_PRODUCT_SELECTED_PRODUCT_CAT);
                }
            }
        }
Example #46
0
        /// <summary>
        /// Function to make a twelve leads signals object.
        /// </summary>
        /// <returns>returns twelve leads signals object or null</returns>
        public Signals CalculateTwelveLeads()
        {
            LeadType[] lt = new LeadType[] { LeadType.I, LeadType.II, LeadType.III,
                                             LeadType.aVR, LeadType.aVL, LeadType.aVF,
                                             LeadType.V1, LeadType.V2, LeadType.V3,
                                             LeadType.V4, LeadType.V5, LeadType.V6 };

            int nrSim = NrSimultaneosly();

            if (nrSim != _Lead.Length)
            {
                return(null);
            }

            Signal[] leads = null;

            if (nrSim == 12)
            {
                ArrayList pos_list = new ArrayList(lt);

                int       check_one = 0;
                ArrayList check_two = new ArrayList(lt);
                Signal[]  pos       = new Signal[12];

                for (int i = 0; i < nrSim; i++)
                {
                    if (_Lead[i].Type == lt[i])
                    {
                        check_one++;
                    }

                    int temp = check_two.IndexOf(_Lead[i].Type);
                    if (temp < 0)
                    {
                        return(null);
                    }

                    check_two.RemoveAt(temp);

                    pos[pos_list.IndexOf(_Lead[i].Type)] = _Lead[i];
                }

                if (check_one == 12)
                {
                    return(this);
                }

                if (check_two.Count == 0)
                {
                    for (int i = 0; i < pos.Length; i++)
                    {
                        if (pos[i] != null)
                        {
                            pos[i] = pos[i].Clone();
                        }
                    }

                    leads = pos;
                }
            }
            else
            {
                short[][]
                tempRhythm = null,
                tempMedian = null;

                Signal[] pos = new Signal[12];

                if (nrSim == 8)
                {
                    ArrayList pos_list = new ArrayList(lt);

                    ArrayList check = new ArrayList(
                        new LeadType[] { LeadType.I, LeadType.II,
                                         LeadType.V1, LeadType.V2, LeadType.V3,
                                         LeadType.V4, LeadType.V5, LeadType.V6 });

                    for (int i = 0; i < nrSim; i++)
                    {
                        int temp = check.IndexOf(_Lead[i].Type);
                        if (temp < 0)
                        {
                            return(null);
                        }

                        check.RemoveAt(temp);

                        pos[pos_list.IndexOf(_Lead[i].Type)] = _Lead[i];
                    }

                    if (check.Count == 0)
                    {
                        for (int i = 0; i < pos.Length; i++)
                        {
                            if (pos[i] != null)
                            {
                                pos[i] = pos[i].Clone();
                            }
                        }

                        tempRhythm    = new short[2][];
                        tempRhythm[0] = pos[0].Rhythm;
                        tempRhythm[1] = pos[1].Rhythm;

                        tempMedian    = new short[2][];
                        tempMedian[0] = pos[0].Median;
                        tempMedian[1] = pos[1].Median;
                    }
                }
                else if (nrSim == 9)
                {
                    ArrayList pos_list = new ArrayList(lt);

                    ArrayList check = new ArrayList(
                        new LeadType[] { LeadType.I, LeadType.II, LeadType.III,
                                         LeadType.V1, LeadType.V2, LeadType.V3,
                                         LeadType.V4, LeadType.V5, LeadType.V6 });

                    for (int i = 0; i < nrSim; i++)
                    {
                        int temp = check.IndexOf(_Lead[i].Type);
                        if (temp < 0)
                        {
                            return(null);
                        }

                        check.RemoveAt(temp);

                        pos[pos_list.IndexOf(_Lead[i].Type)] = _Lead[i];
                    }

                    if (check.Count == 0)
                    {
                        for (int i = 0; i < pos.Length; i++)
                        {
                            if (pos[i] != null)
                            {
                                pos[i] = pos[i].Clone();
                            }
                        }

                        tempRhythm    = new short[3][];
                        tempRhythm[0] = pos[0].Rhythm;
                        tempRhythm[1] = pos[1].Rhythm;
                        tempRhythm[2] = pos[2].Rhythm;

                        tempMedian    = new short[3][];
                        tempMedian[0] = pos[0].Median;
                        tempMedian[1] = pos[1].Median;
                        tempMedian[2] = pos[2].Median;
                    }
                }

                if ((tempRhythm != null) ||
                    (tempMedian != null))
                {
                    short[][] calcLeads;

                    if ((tempRhythm != null) &&
                        (tempRhythm[0] != null) &&
                        ECGTool.CalculateLeads(tempRhythm, tempRhythm[0].Length, out calcLeads) == 0)
                    {
                        for (int i = 0; i < calcLeads.Length; i++)
                        {
                            Signal sig = new Signal();
                            sig.Type        = lt[i + tempRhythm.Length];
                            sig.RhythmStart = pos[0].RhythmStart;
                            sig.RhythmEnd   = pos[0].RhythmEnd;
                            sig.Rhythm      = calcLeads[i];

                            pos[i + tempRhythm.Length] = sig;
                        }

                        if ((tempMedian != null) &&
                            (tempMedian[0] != null) &&
                            (ECGTool.CalculateLeads(tempMedian, tempMedian[0].Length, out calcLeads) == 0))
                        {
                            for (int i = 0; i < calcLeads.Length; i++)
                            {
                                pos[i + tempRhythm.Length].Median = calcLeads[i];
                            }
                        }

                        leads = pos;
                    }
                }
            }

            if (leads != null)
            {
                Signals sigs = this.Clone();

                sigs.NrLeads = (byte)leads.Length;

                for (int i = 0; i < leads.Length; i++)
                {
                    sigs._Lead[i] = leads[i];
                }

                return(sigs);
            }

            return(null);
        }
    public static void Main()
    {
        ArrayList computers = new ArrayList();
        string    option;
        bool      finished = false;

        do
        {
            Console.WriteLine("1.Add data");
            Console.WriteLine("2.Show brands & models");
            Console.WriteLine("3.Search computers");
            Console.WriteLine("4.Update information");
            Console.WriteLine("5.Delete data");
            Console.WriteLine("6.Insert data");
            Console.WriteLine("7.Sort alphabetically");
            Console.WriteLine("8.Remove extra spaces");
            Console.WriteLine("Q.Exit");
            Console.WriteLine();

            Console.Write("Choose an option: ");
            option = Console.ReadLine();

            Computer c;
            switch (option)
            {
            case "1":       // Add new data
                do
                {
                    Console.Write("Enter the brand: ");
                    c.brand = Console.ReadLine();
                    if (c.brand == "")
                    {
                        Console.WriteLine("The brand cannot be empty");
                    }
                }while (c.brand == "");

                do
                {
                    Console.Write("Enter the model: ");
                    c.model = Console.ReadLine();
                    if (c.model.Length > 50)
                    {
                        Console.WriteLine("The model cannot be more "
                                          + "than 50 letters");
                    }
                }while (c.model.Length > 50);

                Console.Write("Enter the year: ");
                c.year =
                    Convert.ToUInt16(Console.ReadLine());
                if (c.year < 1900)
                {
                    c.year = 0;
                }

                Console.Write("Enter the type of memory (eg KB): ");
                c.memory.unit = Console.ReadLine();

                Console.Write("Enter the size of memory (eg 64): ");
                c.memory.size =
                    Convert.ToUInt16(Console.ReadLine());

                Console.Write("Enter the comments: ");
                c.comments = Console.ReadLine();

                computers.Add(c);
                break;

            case "2":       // Show brands and models
                if (computers.Count == 0)
                {
                    Console.WriteLine("No data available");
                }
                else
                {
                    for (int i = 0; i < computers.Count; i++)
                    {
                        c = (Computer)computers[i];
                        Console.WriteLine(c.brand + " - " +
                                          c.model);
                        if (i % 24 == 23)
                        {
                            Console.WriteLine("Press Enter to continue");
                            Console.ReadLine();
                        }
                    }
                }
                break;

            case "3":       // Search
                bool datafound = false;
                Console.Write("Text to search? ");
                string str = Console.ReadLine().ToLower();
                for (int i = 0; i < computers.Count; i++)
                {
                    c = (Computer)computers[i];
                    if (c.brand.ToLower().Contains(str) ||
                        c.model.ToLower().Contains(str) ||
                        c.comments.ToLower().Contains(str))
                    {
                        datafound = true;
                        Console.WriteLine("Computer {0}", i + 1);
                        Console.WriteLine("Brand: {0}", c.brand);
                        Console.WriteLine("Model: {0}", c.model);
                        if (c.year == 0)
                        {
                            Console.WriteLine("Year unknown");
                        }
                        else
                        {
                            Console.WriteLine("Year: {0}",
                                              c.year);
                        }
                        Console.WriteLine("Memory: {0} {1}",
                                          c.memory.size,
                                          c.memory.unit);
                        // Let's modify the comments with a different syntax
                        Console.WriteLine("Comments: {0}",
                                          ((Computer)computers[i]).comments);
                        Console.WriteLine();
                    }
                }
                if (!datafound)
                {
                    Console.WriteLine("Data not found");
                }
                break;

            case "4":       // Modify
                Console.Write("Number of record to modify? ");
                int num = Convert.ToInt32(Console.ReadLine()) - 1;
                if (num >= computers.Count || num < 0)
                {
                    Console.WriteLine("Not a valid record number");
                }
                else
                {
                    c = (Computer)computers[num];
                    Console.WriteLine("Computer {0}", num + 1);
                    Console.WriteLine("Enter the new brand (it was {0})",
                                      c.brand);
                    string answer = Console.ReadLine();
                    if (answer != "")
                    {
                        c.brand = answer;
                    }

                    Console.WriteLine("Enter the new model (it was {0})",
                                      c.model);
                    answer = Console.ReadLine();
                    if (answer != "")
                    {
                        c.model = answer;
                    }

                    Console.WriteLine("Enter the new year (it was {0})",
                                      c.year);
                    answer = Console.ReadLine();
                    if (answer != "")
                    {
                        c.year = Convert.ToUInt16(answer);
                    }

                    Console.WriteLine("Enter the new unit (it was {0})",
                                      c.memory.unit);
                    answer = Console.ReadLine();
                    if (answer != "")
                    {
                        c.memory.unit = answer;
                    }

                    Console.WriteLine("Enter the new size (it was {0})",
                                      c.memory.size);
                    answer = Console.ReadLine();
                    if (answer != "")
                    {
                        c.memory.size =
                            Convert.ToUInt16(answer);
                    }

                    Console.WriteLine("Enter the new comment (it was {0})",
                                      c.comments);
                    answer = Console.ReadLine();
                    if (answer != "")
                    {
                        c.comments = answer;
                    }

                    computers[num] = c;
                }
                break;

            case "5":       // Delete one record
                Console.Write("Number of record to delete? ");
                int pos = Convert.ToInt32(Console.ReadLine()) - 1;
                if (pos >= computers.Count || pos < 0)
                {
                    Console.WriteLine("Not a valid record");
                }
                else
                {
                    computers.RemoveAt(pos);
                }
                break;

            case "6":      // Insert one record
                Console.Write("Position to insert data? ");
                pos = Convert.ToInt32(Console.ReadLine()) - 1;
                if (pos >= computers.Count || pos < 0)
                {
                    Console.WriteLine("Not a valid record");
                }
                else
                {
                    Console.WriteLine("Computer {0}", pos + 1);
                    Console.Write("Brand: ");
                    c.brand = Console.ReadLine();
                    Console.Write("Model: ");
                    c.model = Console.ReadLine();
                    Console.Write("Year: ");
                    c.year = Convert.ToUInt16(Console.ReadLine());
                    Console.Write("Memory type: ");
                    c.memory.unit = Console.ReadLine();
                    Console.Write("Memory size: ");
                    c.memory.size = Convert.ToUInt16(Console.ReadLine());
                    Console.Write("Comments: ");
                    c.comments = Console.ReadLine();
                    computers.Insert(pos, c);
                }
                break;

            case "7":       // Sort
                /*
                 * for (int i = 0; i < count - 1; i++)
                 * {
                 *  for (int j = i + 1; j < count; j++)
                 *  {
                 *      if (String.Compare(computers[i].brand + computers[i].model,
                 *          computers[j].brand + computers[j].model, true) > 0)
                 *      {
                 *          Computer temp = computers[i];
                 *          computers[i] = computers[j];
                 *          computers[j] = temp;
                 *      }
                 *  }
                 * }
                 */
                break;

            case "8":       // Normalize descriptions
                for (int i = 0; i < computers.Count; i++)
                {
                    c            = (Computer)computers[i];
                    c.brand      = c.brand.Trim();
                    c.model      = c.model.Trim();
                    c.comments   = c.comments.Trim();
                    computers[i] = c;
                }
                break;

            case "q":       // Quit
            case "Q":
                finished = true;
                break;
            }
        } while (!finished);
        Console.WriteLine("Bye!");
    }
Example #48
0
        public void CheckPlayers()
        {
            bool removed = false;

            for (int i = 0; i < m_Players.Length; i++)
            {
                Mobile player = m_Players[i];

                if (player != null)
                {
                    if (player.Deleted)
                    {
                        m_Players[i] = null;

                        SendPlayerExitMessage(player);
                        UpdateDealer(true);

                        removed = true;
                    }
                    else if (m_InGame[i])
                    {
                        if (player.NetState == null)
                        {
                            m_InGame[i] = false;

                            SendPlayerExitMessage(player);
                            UpdateDealer(true);

                            removed = true;
                        }
                        else if (!m_Game.IsAccessibleTo(player) || player.Map != m_Game.Map || !player.InRange(m_Game.GetWorldLocation(), 5))
                        {
                            m_InGame[i] = false;

                            player.Send(new MahjongRelieve(m_Game));

                            SendPlayerExitMessage(player);
                            UpdateDealer(true);

                            removed = true;
                        }
                    }
                }
            }

            for (int i = 0; i < m_Spectators.Count;)
            {
                Mobile mobile = (Mobile)m_Spectators[i];

                if (mobile.NetState == null || mobile.Deleted)
                {
                    m_Spectators.RemoveAt(i);
                }
                else if (!m_Game.IsAccessibleTo(mobile) || mobile.Map != m_Game.Map || !mobile.InRange(m_Game.GetWorldLocation(), 5))
                {
                    m_Spectators.RemoveAt(i);

                    mobile.Send(new MahjongRelieve(m_Game));
                }
                else
                {
                    i++;
                }
            }

            if (removed && !UpdateSpectators())
            {
                SendPlayersPacket(true, true);
            }
        }
 /// <summary>
 /// Removes the IList item at the specified index.
 /// </summary>
 /// <param name="index">The zero-based index of the item to remove.</param>
 public void RemoveAt(int index)
 {
     _values.RemoveAt(index);
 }
        /// <summary>
        ///  Populate the internal InnerList with sources/physical connectors
        ///  found on the crossbars. Each instance of this class is limited
        ///  to video only or audio only sources ( specified by the isVideoDevice
        ///  parameter on the constructor) so we check each source before adding
        ///  it to the list.
        /// </summary>
        protected ArrayList findCrossbarSources(ICaptureGraphBuilder2 graphBuilder, IAMCrossbar crossbar, bool isVideoDevice)
        {
            ArrayList sources = new ArrayList();
            int       hr;
            int       numOutPins;
            int       numInPins;

            hr = crossbar.get_PinCounts(out numOutPins, out numInPins);
            if (hr < 0)
            {
                Marshal.ThrowExceptionForHR(hr);
            }

            // We loop through every combination of output and input pin
            // to see which combinations match.

            // Loop through output pins
            for (int cOut = 0; cOut < numOutPins; cOut++)
            {
                // Loop through input pins
                for (int cIn = 0; cIn < numInPins; cIn++)
                {
                    // Can this combination be routed?
                    hr = crossbar.CanRoute(cOut, cIn);
                    if (hr == 0)
                    {
                        // Yes, this can be routed
                        int relatedPin;
                        PhysicalConnectorType connectorType;
                        hr = crossbar.get_CrossbarPinInfo(true, cIn, out relatedPin, out connectorType);
                        if (hr < 0)
                        {
                            Marshal.ThrowExceptionForHR(hr);
                        }

                        // Is this the correct type?, If so add to the InnerList
                        CrossbarSource source = new CrossbarSource(crossbar, cOut, cIn, connectorType);
                        if (connectorType < PhysicalConnectorType.Audio_Tuner)
                        {
                            if (isVideoDevice)
                            {
                                sources.Add(source);
                            }
                            else
                            if (!isVideoDevice)
                            {
                                sources.Add(source);
                            }
                        }
                    }
                }
            }

            // Some silly drivers (*cough* Nvidia *cough*) add crossbars
            // with no real choices. Every input can only be routed to
            // one output. Loop through every Source and see if there
            // at least one other Source with the same output pin.
            int refIndex = 0;

            while (refIndex < sources.Count)
            {
                bool           found     = false;
                CrossbarSource refSource = (CrossbarSource)sources[refIndex];
                for (int c = 0; c < sources.Count; c++)
                {
                    CrossbarSource s = (CrossbarSource)sources[c];
                    if ((refSource.OutputPin == s.OutputPin) && (refIndex != c))
                    {
                        found = true;
                        break;
                    }
                }
                if (found)
                {
                    refIndex++;
                }
                else
                {
                    sources.RemoveAt(refIndex);
                }
            }

            return(sources);
        }
Example #51
0
 /// <summary>
 /// Removes a promo code from line item list.
 /// </summary>
 /// <param name="Index">Index of promo code to be removed.</param>
 /// <remarks>
 /// <para>Use this method to remove a promo code at a particular index
 /// in the requester.</para>
 /// </remarks>
 /// <example>
 /// <code lang="C#" escaped="false">
 ///	.................
 ///	// SetPayLaterLineItem is the PayLater object
 ///	.................
 ///	// Remove item at index 0
 ///	setPayLater.PayLaterRemoveLineItem(0);
 ///	.................
 ///	</code>
 /// <code lang="Visual Basic" escaped="false">
 ///	.................
 ///	' SetPayLaterLineItem is the PayLater object
 ///	.................
 ///	' Remove item at index 0;
 ///	SetPayLater.PayLaterRemoveLineItem(0)
 ///	.................
 ///	</code>
 /// </example>
 public void PayLaterRemoveLineItem(int Index)
 {
     mItemList.RemoveAt(Index);
 }
Example #52
0
 public void DeQueue()
 {
     pqueue.RemoveAt(0);
 }
Example #53
0
        /// <summary>
        /// Combines two path strings.
        /// </summary>
        /// <param name="path1">The first path.</param>
        /// <param name="path2">The second path.</param>
        /// <returns>
        /// A string containing the combined paths. If one of the specified
        /// paths is a zero-length string, this method returns the other path.
        /// If <paramref name="path2" /> contains an absolute path, this method
        /// returns <paramref name="path2" />.
        /// </returns>
        /// <remarks>
        ///   <para>
        ///   On *nix, processing is delegated to <see cref="Path.Combine(string, string)" />.
        ///   </para>
        ///   <para>
        ///   On Windows, this method normalized the paths to avoid running into
        ///   the 260 character limit of a path and converts forward slashes in
        ///   both <paramref name="path1" /> and <paramref name="path2" /> to
        ///   the platform's directory separator character.
        ///   </para>
        /// </remarks>
        public static string CombinePaths(string path1, string path2)
        {
            if (PlatformHelper.IsUnix)
            {
                return(Path.Combine(path1, path2));
            }

            if (path1 == null)
            {
                throw new ArgumentNullException("path1");
            }
            if (path2 == null)
            {
                throw new ArgumentNullException("path2");
            }

            if (Path.IsPathRooted(path2))
            {
                return(path2);
            }

            char separatorChar = Path.DirectorySeparatorChar;

            char[] splitChars = new char[] { '/', separatorChar };

            // Now we split the Path by the Path Separator
            String[] path2Parts = path2.Split(splitChars);

            ArrayList arList = new ArrayList();

            // for each Item in the path that differs from ".." we just add it
            // to the ArrayList, but skip empty parts
            for (int iCount = 0; iCount < path2Parts.Length; iCount++)
            {
                string currentPart = path2Parts[iCount];

                // skip empty parts or single dot parts
                if (currentPart.Length == 0 || currentPart == ".")
                {
                    continue;
                }

                // if we get a ".." Try to remove the last item added (as if
                // going up in the Directory Structure)
                if (currentPart == "..")
                {
                    if (arList.Count > 0 && ((string)arList[arList.Count - 1] != ".."))
                    {
                        arList.RemoveAt(arList.Count - 1);
                    }
                    else
                    {
                        arList.Add(currentPart);
                    }
                }
                else
                {
                    arList.Add(currentPart);
                }
            }

            bool trailingSeparator = (path1.Length > 0 && path1.IndexOfAny(splitChars, path1.Length - 1) != -1);

            // if the first path ends in directory seperator character, then
            // we need to omit that trailing seperator when we split the path
            string[] path1Parts;
            if (trailingSeparator)
            {
                path1Parts = path1.Substring(0, path1.Length - 1).Split(splitChars);
            }
            else
            {
                path1Parts = path1.Split(splitChars);
            }

            int counter = path1Parts.Length;

            // if the second path starts with parts to move up the directory tree,
            // then remove corresponding parts in the first path
            //
            // eg. path1 = d:\whatever\you\want\to\do
            //     path2 = ../../test
            //
            //     ->
            //
            //     path1 = d:\whatever\you\want
            //     path2 = test
            ArrayList arList2 = (ArrayList)arList.Clone();

            for (int i = 0; i < arList2.Count; i++)
            {
                // never discard first part of path1
                if ((string)arList2[i] != ".." || counter < 2)
                {
                    break;
                }

                // skip part of current directory
                counter--;

                arList.RemoveAt(0);
            }

            string separatorString = separatorChar.ToString(CultureInfo.InvariantCulture);

            // if path1 only has one remaining part, and the original path had
            // a trailing separator character or the remaining path had multiple
            // parts (which were discarded by a relative path in path2), then
            // add separator to remaining part
            if (counter == 1 && (trailingSeparator || path1Parts.Length > 1))
            {
                path1Parts[0] += separatorString;
            }

            string combinedPath = Path.Combine(string.Join(separatorString, path1Parts,
                                                           0, counter), string.Join(separatorString, (String[])arList.ToArray(typeof(String))));

            // if path2 ends in directory separator character, then make sure
            // combined path has trailing directory separator character
            if (path2.EndsWith("/") || path2.EndsWith(separatorString))
            {
                combinedPath += Path.DirectorySeparatorChar;
            }

            return(combinedPath);
        }
Example #54
0
    void Question()
    {
        string fullQuestion = Camera.main.GetComponent <Questions>().askQuestion();
        //print("Current "+ currentQuestion);
        int    split         = fullQuestion.IndexOf(";");
        string splitQuestion = fullQuestion.Substring(0, split);

        string[] questionWords  = splitQuestion.Split(' ');
        string   parsedQuestion = "";

        for (int r = 0; r < questionWords.Length; r++)
        {
            if (r == 6)
            {
                parsedQuestion = parsedQuestion + " \n";
            }
            parsedQuestion = parsedQuestion + " " + questionWords[r];
        }
        question.text = parsedQuestion;
        string[]  fullAns     = fullQuestion.Substring(split + 1).Split(',');
        ArrayList fullAnswers = new ArrayList();

        for (int i = 0; i < 10; i++)
        {
            fullAnswers.Add(fullAns[i]);
        }

        string correctAnswer = (string)fullAnswers[0];

        fullAnswers.RemoveAt(0);

        float  wrongAnswer1    = Mathf.Ceil(Random.value * (fullAnswers.Count - 2) + 1);
        int    wrongAnswer1Int = (int)wrongAnswer1;
        string wrongAnswer1Ans = (string)fullAnswers[wrongAnswer1Int];

        fullAnswers.RemoveAt(wrongAnswer1Int);

        float  wrongAnswer2    = Mathf.Ceil(Random.value * (fullAnswers.Count - 2) + 1);
        int    wrongAnswer2Int = (int)wrongAnswer2;
        string wrongAnswer2Ans = (string)fullAnswers[wrongAnswer2Int];

        fullAnswers.RemoveAt(wrongAnswer2Int);

        float  wrongAnswer3    = Mathf.Ceil(Random.value * (fullAnswers.Count - 2) + 1);
        int    wrongAnswer3Int = (int)wrongAnswer3;
        string wrongAnswer3Ans = (string)fullAnswers[wrongAnswer3Int];

        fullAnswers.RemoveAt(wrongAnswer3Int);

        string[] answers = new string[4] {
            correctAnswer, wrongAnswer1Ans, wrongAnswer2Ans, wrongAnswer3Ans
        };
        answers[0] = answers[0].Substring(0, 2).ToUpper() + answers[0].Substring(2).ToLower();
        answers[1] = answers[1].Substring(0, 2).ToUpper() + answers[1].Substring(2).ToLower();
        answers[2] = answers[2].Substring(0, 2).ToUpper() + answers[2].Substring(2).ToLower();
        answers[3] = answers[3].Substring(0, 2).ToUpper() + answers[3].Substring(2).ToLower();
        float correctAns = Mathf.Floor(Random.value * 40);

        if (correctAns % 4 == 0)
        {
            ansTextA.text = answers[0];
            ansTextB.text = answers[1];
            ansTextC.text = answers[2];
            ansTextD.text = answers[3];
        }
        else if (correctAns % 4 == 1)
        {
            ansTextA.text = answers[1];
            ansTextB.text = answers[0];
            ansTextC.text = answers[2];
            ansTextD.text = answers[3];
        }
        else if (correctAns % 4 == 2)
        {
            ansTextA.text = answers[2];
            ansTextB.text = answers[1];
            ansTextC.text = answers[0];
            ansTextD.text = answers[3];
        }
        else if (correctAns % 4 == 3)
        {
            ansTextA.text = answers[3];
            ansTextB.text = answers[1];
            ansTextC.text = answers[2];
            ansTextD.text = answers[0];
        }
        Camera.main.GetComponent <Questions>().incrementQuestion();
        int questionsAsked = Camera.main.GetComponent <Questions>().getQuestionNum();

        questionTrack.text = "Question # " + questionsAsked;
        Camera.main.GetComponent <Questions>().rightAnswer();
        int questionScore = Camera.main.GetComponent <Questions>().getQuestionScore();

        possibleScore.text = "Points remaining for question: " + questionScore;
    }
Example #55
0
        /// <summary>
        /// Check to make sure that something didn't get split by a comma when it shouldn't
        /// </summary>
        /// <param name="vals"> The values of one line. </param>
        /// <param name="dt"> The dt. </param>
        private static void ConditionValues(string[] vals, DataTable dt)
        {
            // Check to make sure that something didn't get split by a comma when it
            // shouldn't have... e.g., "Reston" and " VA" should have been "Reston, VA"
            // First Pass:
            if (vals.Length != dt.Columns.Count)
            {
                var unmatchedStarting = new ArrayList();
                var unmatchedEnding   = new ArrayList();
                for (var i = 0; i < vals.Length - 1; i++)
                {
                    if (vals[i].StartsWith(((char)34).ToString()) && !vals[i].EndsWith(((char)34).ToString()))
                    {
                        unmatchedStarting.Add(i);
                    }
                    else if (vals[i].EndsWith(((char)34).ToString()) && !vals[i].StartsWith(((char)34).ToString()))
                    {
                        unmatchedEnding.Add(i);
                    }
                }

                if (unmatchedStarting.Count != unmatchedEnding.Count)
                {
                    ConditionValues_OneCommaOnly(vals); // Fallback -has some disadvantages
                }
                else
                {
                    var newVals   = new ArrayList();
                    var append    = string.Empty;
                    var appending = false;
                    for (var i = 0; i < vals.Length; i++)
                    {
                        if (!appending && !unmatchedStarting.Contains(i) && !unmatchedEnding.Contains(i))
                        {
                            newVals.Add(vals[i]);
                        }
                        else if (Convert.ToInt32(unmatchedEnding[0]) == i)
                        {
                            unmatchedStarting.RemoveAt(0);
                            unmatchedEnding.RemoveAt(0);
                            append += vals[i];
                            newVals.Add(append);
                            append    = string.Empty;
                            appending = false;
                        }
                        else
                        {
                            appending = true;
                            append   += vals[i] + ",";
                        }
                    }

                    vals = (string[])newVals.ToArray(vals[0].GetType());
                }
            }

            for (var i = 0; i < vals.Length; i++)
            {
                vals[i] = vals[i].Trim();
                if ((vals[i].StartsWith(((char)34).ToString()) && vals[i].EndsWith(((char)34).ToString())) ||
                    (vals[i].StartsWith("'") && vals[i].EndsWith("'")))
                {
                    vals[i] = vals[i].Substring(1, vals[i].Length - 2);
                }
            }
        }
Example #56
0
        /// <summary>
        ///  Populate the internal InnerList with sources/physical connectors
        ///  found on the crossbars. Each instance of this class is limited
        ///  to video only or audio only sources ( specified by the isVideoDevice
        ///  parameter on the constructor) so we check each source before adding
        ///  it to the list.
        /// </summary>
        protected ArrayList findCrossbarSources(ICaptureGraphBuilder2 graphBuilder, IAMCrossbar crossbar, bool isVideoDevice)
        {
            ArrayList sources = new ArrayList();
            int       hr;
            int       numOutPins;
            int       numInPins;

            hr = crossbar.get_PinCounts(out numOutPins, out numInPins);
            if (hr < 0)
            {
                Marshal.ThrowExceptionForHR(hr);
            }

            // We loop through every combination of output and input pin
            // to see which combinations match.

            // Loop through output pins
            for (int cOut = 0; cOut < numOutPins; cOut++)
            {
                // Loop through input pins
                for (int cIn = 0; cIn < numInPins; cIn++)
                {
                    // Can this combination be routed?
                    hr = crossbar.CanRoute(cOut, cIn);
                    if (hr == 0)
                    {
                        // Yes, this can be routed
                        int relatedInputPin;
                        PhysicalConnectorType connectorType;
                        hr = crossbar.get_CrossbarPinInfo(true, cIn, out relatedInputPin, out connectorType);
                        if (hr < 0)
                        {
                            Marshal.ThrowExceptionForHR(hr);
                        }

                        // Add it to the list
                        CrossbarSource source = new CrossbarSource(crossbar, cOut, cIn, relatedInputPin, connectorType);
                        sources.Add(source);
                    }
                }
            }

            // Some silly drivers (*cough* Nvidia *cough*) add crossbars
            // with no real choices. Every input can only be routed to
            // one output. Loop through every Source and see if there
            // at least one other Source with the same output pin.
            int refIndex = 0;

            while (refIndex < sources.Count)
            {
                bool           found     = false;
                CrossbarSource refSource = (CrossbarSource)sources[refIndex];
                for (int c = 0; c < sources.Count; c++)
                {
                    CrossbarSource s = (CrossbarSource)sources[c];
                    if ((refSource.OutputPin == s.OutputPin) && (refIndex != c))
                    {
                        found = true;
                        break;
                    }
                }
                if (found)
                {
                    refIndex++;
                }
                else
                {
                    sources.RemoveAt(refIndex);
                }
            }

            // Some of the video input pins have related audio pins
            // that should be connected at the same time. We noted the pin number
            // in the CrossbarSource.RelatedInputPin. Now that we have all
            // the sources, lookup the CrossbarSource object associated with
            // that pin
            foreach (CrossbarSource source in sources)
            {
                if (source.RelatedInputPin != -1)
                {
                    foreach (CrossbarSource related in sources)
                    {
                        if (source.RelatedInputPin == related.InputPin)
                        {
                            source.RelatedInputSource = related;
                        }
                    }
                }
            }

            // Remove any sources that are not of the correct type
            for (int c = 0; c < sources.Count; c++)
            {
                if (((CrossbarSource)sources[c]).ConnectorType < PhysicalConnectorType.Audio_Tuner)
                {
                    if (!isVideoDevice)
                    {
                        sources.RemoveAt(c);
                        c--;
                    }
                }
                else
                {
                    if (isVideoDevice)
                    {
                        sources.RemoveAt(c);
                        c--;
                    }
                }
            }
            return(sources);
        }
 public virtual bool runTest()
 {
     int iCountErrors = 0;
     int iCountTestcases = 0;
     Console.Error.WriteLine( strName + ": " + strTest + " runTest started..." );
     ArrayList arrList = null;
     String[] arrCopy = null;
     int start = 3;
     int count = 15;
     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",
     };
     String [] strResult =
         {
             "Aquaman",
             "Atom",
             "Batman",
             "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 ArrayList" );
                 ++iCountErrors;
                 break;
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine( strTest+ "E_10001: Unexpected Exception: " + ex.ToString() );
             ++iCountErrors;
             break;
         }
         ++iCountTestcases;
         Console.Error.WriteLine( "[]  Remove objects from the ArrayList" );
         try
         {
             for ( int ii = 0; ii < count; ++ii )
             {
                 arrList.RemoveAt( start );
             }
             for ( int ii = 0; ii < strResult.Length; ++ii )
             {
                 if ( strResult[ii].CompareTo( (String)arrList[ii] ) != 0 )
                 {
                     String strInfo = strTest + " error: ";
                     strInfo = strInfo + "Expected hero <"+ strResult[ii] + "> ";
                     strInfo = strInfo + "Returned hero <"+ (String)arrList[ii] + "> ";
                     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 remove using negative index" );
         try
         {
             arrList.RemoveAt( -100 );
             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 remove using out of range index" );
         try
         {
             arrList.RemoveAt( 1000 );
             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;
         }
     }
     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;
     }
 }
Example #58
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();
        }
	// Finds all packable sprite objects:
	void FindPackableSprites(ArrayList sprites)
	{
		// Get all packed sprites in the scene:
		Object[] o = FindObjectsOfType(typeof(SpriteRoot));

		for (int i = 0; i < o.Length; ++i)
		{
#if UNITY_IPHONE && !(UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_3_6 || UNITY_3_7 || UNITY_3_8 || UNITY_3_9)
			if (onlyScanProjectFolder)
#else
			if (scanProjectFolder)
#endif
			{
				// Check to see if this is a prefab instance,
				// and if so, don't use it since we'll be updating
				// the prefab itself anyway.
				// Don't add it at all if we're in Unity iPhone and
				// we'll be scanning the project folder since in
				// iPhone, we can't tell if a scene instance is a
				// prefab instance and we'll mess up prefab relationships
				// otherwise:
#if !UNITY_IPHONE || (UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_3_6 || UNITY_3_7 || UNITY_3_8 || UNITY_3_9)
				if (PrefabType.PrefabInstance != EditorUtility.GetPrefabType(o[i]))
					sprites.Add(o[i]);
#endif
			}
			else
				sprites.Add(o[i]);
		}

		// See if we need to scan the Assets folder for sprite objects
#if UNITY_IPHONE && !(UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_3_6 || UNITY_3_7 || UNITY_3_8 || UNITY_3_9)
		if (onlyScanProjectFolder)
#else
		if (scanProjectFolder)
#endif
			ScanProjectFolder(sprites);

		// Now filter for the types of sprites we want:
		for (int i = 0; i < sprites.Count; ++i)
		{
			if (!packableType.IsInstanceOfType(sprites[i]))
			{
				sprites.RemoveAt(i);
				--i;
			}
		}
	}
Example #60
0
    public bool runTest()
    {
        Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer);
        int       iCountErrors    = 0;
        int       iCountTestcases = 0;
        String    strLoc          = "Loc_000oo";
        ArrayList alst1;
        ArrayList alst2;
        String    strValue;
        Object    oValue;

        try
        {
            do
            {
                strLoc = "Loc_8345vdfv";
                alst1  = new ArrayList();
                for (int i = 0; i < 10; i++)
                {
                    strValue = "String_" + i;
                    alst1.Add(strValue);
                }
                alst2 = ArrayList.FixedSize(alst1);
                iCountTestcases++;
                for (int i = 0; i < 10; i++)
                {
                    strValue = "String_" + i;
                    if (!strValue.Equals((String)alst2[i]))
                    {
                        iCountErrors++;
                        Console.WriteLine("Err_561dvs_" + i + "! Expected value not returned, " + strValue);
                    }
                }
                alst1.RemoveAt(9);
                try
                {
                    iCountTestcases++;
                    oValue = alst1[9];
                    iCountErrors++;
                    Console.WriteLine("Err_034cd! exception not thrown");
                }
                catch (ArgumentOutOfRangeException)
                {
                }
                catch (Exception ex)
                {
                    iCountErrors++;
                    Console.WriteLine("Err_03472fd! Unexpected exception, " + ex.ToString());
                }
                try
                {
                    iCountTestcases++;
                    oValue = alst2[9];
                    iCountErrors++;
                    Console.WriteLine("Err_8452vs! exception not thrown");
                }
                catch (ArgumentOutOfRangeException)
                {
                }
                catch (Exception ex)
                {
                    iCountErrors++;
                    Console.WriteLine("Err_13753vdf! Unexpected exception, " + ex.ToString());
                }
                try
                {
                    iCountTestcases++;
                    alst2.RemoveAt(0);
                    iCountErrors++;
                    Console.WriteLine("Err_8342sf! exception not thrown");
                }
                catch (NotSupportedException)
                {
                }
                catch (Exception ex)
                {
                    iCountErrors++;
                    Console.WriteLine("Err_135234vdf! Unexpected exception, " + ex.ToString());
                }
                try
                {
                    iCountTestcases++;
                    alst2.Clear();
                    iCountErrors++;
                    Console.WriteLine("Err_8342sf! exception not thrown");
                }
                catch (NotSupportedException)
                {
                }
                catch (Exception ex)
                {
                    iCountErrors++;
                    Console.WriteLine("Err_135234vdf! Unexpected exception, " + ex.ToString());
                }
                try
                {
                    iCountTestcases++;
                    alst2.Add("This sort of thing will not be allowed");
                    iCountErrors++;
                    Console.WriteLine("Err_8342sf! exception not thrown");
                }
                catch (NotSupportedException)
                {
                }
                catch (Exception ex)
                {
                    iCountErrors++;
                    Console.WriteLine("Err_135234vdf! Unexpected exception, " + ex.ToString());
                }
                try
                {
                    iCountTestcases++;
                    alst2.Insert(0, "This sort of thing will not be allowed");
                    iCountErrors++;
                    Console.WriteLine("Err_8342sf! exception not thrown");
                }
                catch (NotSupportedException)
                {
                }
                catch (Exception ex)
                {
                    iCountErrors++;
                    Console.WriteLine("Err_135234vdf! Unexpected exception, " + ex.ToString());
                }
                alst1 = new ArrayList();
                for (int i = 0; i < 10; i++)
                {
                    strValue = "String_" + i;
                    alst1.Add(strValue);
                }
                alst2    = ArrayList.FixedSize(alst1);
                strValue = "Hello World";
                alst2[0] = strValue;
                iCountTestcases++;
                if (!strValue.Equals((String)alst2[0]))
                {
                    iCountErrors++;
                    Console.WriteLine("Err_654234fgd! Expected value not returned, " + strValue);
                }
            } while (false);
        }
        catch (Exception exc_general)
        {
            ++iCountErrors;
            Console.WriteLine(s_strTFAbbrev + " : Error Err_8888yyy!  strLoc==" + strLoc + ", exc_general==\n" + exc_general.ToString());
        }
        if (iCountErrors == 0)
        {
            Console.WriteLine("paSs.   " + s_strTFPath + " " + s_strTFName + " ,iCountTestcases==" + iCountTestcases);
            return(true);
        }
        else
        {
            Console.WriteLine("FAiL!   " + s_strTFPath + " " + s_strTFName + " ,iCountErrors==" + iCountErrors + " , BugNums?: " + s_strActiveBugNums);
            return(false);
        }
    }