Clone() public method

public Clone ( ) : object
return object
Esempio n. 1
0
        //Runs the algoritm for number of iterations
        public override void Run(Configuration config)
        {
            log = new RandomLogSpecification(data.DataFileName, config.RandomSeed, config.NumberOfRuns, config.PenaltyCoefficient);
            solution = new SolutionSpecification();

            BitArray routerswitches = new BitArray((int)data.RouterCount);
            double highestfitness = 0.0;
            BitArray best = new BitArray((int)data.RouterCount);
            for(int i = 0; i < config.NumberOfRuns; i++)
            {
                routerswitches = new BitArray((int)data.RouterCount);
                int numbertoswitch = randomgenerator.Next((int)data.RouterCount);
                for(int j = 0; j < numbertoswitch; j++)
                {
                    int switching;
                    while(routerswitches.Get(switching = randomgenerator.Next((int)data.RouterCount)) == true);
                    routerswitches.Set(switching, true);
                }

                double fitness = FitnessEvaluation(data.NetworkPaths, routerswitches, numbertoswitch, config.PenaltyCoefficient);

                if(fitness > highestfitness)
                {
                    ((RandomLogSpecification)log).AddEvaluation(i, fitness);
                    highestfitness = fitness;
                    best = (BitArray)routerswitches.Clone();
                }
            }

            solution.RoutersTurnedOff = ExtensionMethods.ConvertBitArrayToOffRouterNumbers(best, data.HostCount);
        }
Esempio n. 2
0
 public Node(BitArray parentAvailAttrs)
 {
     attrCount = Globals.attrCount;
     availableAttrs = (BitArray) parentAvailAttrs.Clone();	// !!
     tuples = new List<Tuple>();
     childNodes = new List<Node>();
 }
 static public int Clone(IntPtr l)
 {
     try {
         System.Collections.BitArray self = (System.Collections.BitArray)checkSelf(l);
         var ret = self.Clone();
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Esempio n. 4
0
        //Runs the algoritm for number of iterations
        public override void Run(int iterations, int randseed)
        {
            log = new RandomLogSpecification(data.DataFileName, randseed, iterations);
            solution = new SolutionSpecification();

            BitArray routerswitches = new BitArray((int)data.RouterCount);
            double highestfitness = 0.0;
            BitArray best = new BitArray((int)data.RouterCount);
            for(int i = 0; i < iterations; i++)
            {
              //  Console.WriteLine("Run #" + i);
                routerswitches = new BitArray((int)data.RouterCount);
              //  Console.WriteLine("Router count: " + routerswitches.Count);
                int numbertoswitch = randomgenerator.Next((int)data.RouterCount);
              //  Console.WriteLine("Switching amount: " + numbertoswitch);
                for(int j = 0; j < numbertoswitch; j++)
                {
                    int switching;
                    while(routerswitches.Get(switching = randomgenerator.Next((int)data.RouterCount)) == true);
                //    Console.WriteLine("Switching: " + switching);
                    routerswitches.Set(switching, true);
                }

                double fitness = FitnessEvaluation(data.NetworkPaths, routerswitches, numbertoswitch);

               // Console.WriteLine("Fitness: " + fitness);
                if(fitness > highestfitness)
                {
                    ((RandomLogSpecification)log).AddEvaluation(i, fitness);
                    highestfitness = fitness;
                    best = (BitArray)routerswitches.Clone();
                }
            }

            solution.RoutersTurnedOff = ExtensionMethods.ConvertBitArrayToOffRouterNumbers(best, data.HostCount);
        }
Esempio n. 5
0
File: Tab.cs Progetto: ggrov/tacny
	public static void Subtract(BitArray a, BitArray b) { // a = a - b
		BitArray c = (BitArray) b.Clone();
		a.And(c.Not());
	}
        internal virtual void DoRandomSets(int maxSize, int iter, int mode)
        {
            BitArray a0 = null;
            LongBitSet b0 = null;

            for (int i = 0; i < iter; i++)
            {
                int sz = TestUtil.NextInt(Random(), 2, maxSize);
                BitArray a = new BitArray(sz);
                LongBitSet b = new LongBitSet(sz);

                // test the various ways of setting bits
                if (sz > 0)
                {
                    int nOper = Random().Next(sz);
                    for (int j = 0; j < nOper; j++)
                    {
                        int idx;

                        idx = Random().Next(sz);
                        a.SafeSet(idx, true);
                        b.Set(idx);

                        idx = Random().Next(sz);
                        a.SafeSet(idx, false);
                        b.Clear(idx);

                        idx = Random().Next(sz);
                        a.SafeSet(idx, !a.SafeGet(idx));
                        b.Flip(idx, idx + 1);

                        idx = Random().Next(sz);
                        a.SafeSet(idx, !a.SafeGet(idx));
                        b.Flip(idx, idx + 1);
                        
                        bool val2 = b.Get(idx);
                        bool val = b.GetAndSet(idx);
                        Assert.IsTrue(val2 == val);
                        Assert.IsTrue(b.Get(idx));
                        
                        if (!val)
                        {
                            b.Clear(idx);
                        }
                        Assert.IsTrue(b.Get(idx) == val);
                    }
                }

                // test that the various ways of accessing the bits are equivalent
                DoGet(a, b);
                
                // test ranges, including possible extension
                int fromIndex, toIndex;
                fromIndex = Random().Next(sz / 2);
                toIndex = fromIndex + Random().Next(sz - fromIndex);
                BitArray aa = (BitArray)a.Clone();
                aa.Flip(fromIndex, toIndex);
                LongBitSet bb = b.Clone();
                bb.Flip(fromIndex, toIndex);

                fromIndex = Random().Next(sz / 2);
                toIndex = fromIndex + Random().Next(sz - fromIndex);
                aa = (BitArray)a.Clone();
                aa.Clear(fromIndex, toIndex);
                bb = b.Clone();
                bb.Clear(fromIndex, toIndex);

                DoNextSetBit(aa, bb); // a problem here is from clear() or nextSetBit

                DoPrevSetBit(aa, bb);

                fromIndex = Random().Next(sz / 2);
                toIndex = fromIndex + Random().Next(sz - fromIndex);
                aa = (BitArray)a.Clone();
                aa.Set(fromIndex, toIndex);
                bb = b.Clone();
                bb.Set(fromIndex, toIndex);

                DoNextSetBit(aa, bb); // a problem here is from set() or nextSetBit

                DoPrevSetBit(aa, bb);

                if (b0 != null && b0.Length() <= b.Length())
                {
                    Assert.AreEqual(a.Cardinality(), b.Cardinality());

                    BitArray a_and = (BitArray)a.Clone();
                    a_and = a_and.And_UnequalLengths(a0);
                    BitArray a_or = (BitArray)a.Clone();
                    a_or = a_or.Or_UnequalLengths(a0);
                    BitArray a_xor = (BitArray)a.Clone();
                    a_xor = a_xor.Xor_UnequalLengths(a0);
                    BitArray a_andn = (BitArray)a.Clone();
                    a_andn.AndNot(a0);

                    LongBitSet b_and = b.Clone();
                    Assert.AreEqual(b, b_and);
                    b_and.And(b0);
                    LongBitSet b_or = b.Clone();
                    b_or.Or(b0);
                    LongBitSet b_xor = b.Clone();
                    b_xor.Xor(b0);
                    LongBitSet b_andn = b.Clone();
                    b_andn.AndNot(b0);

                    Assert.AreEqual(a0.Cardinality(), b0.Cardinality());
                    Assert.AreEqual(a_or.Cardinality(), b_or.Cardinality());

                    Assert.AreEqual(a_and.Cardinality(), b_and.Cardinality());
                    Assert.AreEqual(a_or.Cardinality(), b_or.Cardinality());
                    Assert.AreEqual(a_xor.Cardinality(), b_xor.Cardinality());
                    Assert.AreEqual(a_andn.Cardinality(), b_andn.Cardinality());
                }

                a0 = a;
                b0 = b;
            }
        }
Esempio n. 7
0
 //Uses a bit mask to see if a path is cut by switching routers (on bits) in roterswitches off.
 private bool IsPathCut(BitArray path, BitArray routerswitches)
 {
     BitArray p = (BitArray)path.Clone();
     BitArray r = (BitArray)routerswitches.Clone();
     return (!ExtensionMethods.AreBitArraysEqual(path, p.And(r.Not())));
 }
        private void ComputeLocalLiveSets()
        {
            var liveSetTrace = new CompilerTrace(trace, "ComputeLocalLiveSets");

            foreach (var block in extendedBlocks)
            {
                if (liveSetTrace.Active)
                    liveSetTrace.Log("Block # " + block.BasicBlock.Sequence.ToString());

                BitArray liveGen = new BitArray(registerCount, false);
                BitArray liveKill = new BitArray(registerCount, false);

                liveGen.Set(stackFrameRegister.Index, true);
                liveGen.Set(stackPointerRegister.Index, true);

                if (programCounter != null)
                    liveGen.Set(programCounter.Index, true);

                for (Context context = new Context(instructionSet, block.BasicBlock); !context.IsBlockEndInstruction; context.GotoNext())
                {
                    if (context.IsEmpty)
                        continue;

                    if (liveSetTrace.Active)
                        liveSetTrace.Log(context.ToString());

                    OperandVisitor visitor = new OperandVisitor(context);

                    foreach (var ops in visitor.Input)
                    {
                        if (liveSetTrace.Active)
                            liveSetTrace.Log("INPUT:  " + ops.ToString());

                        int index = GetIndex(ops);
                        if (!liveKill.Get(index))
                        {
                            liveGen.Set(index, true);

                            if (liveSetTrace.Active)
                                liveSetTrace.Log("GEN:  " + index.ToString() + " " + ops.ToString());
                        }
                    }

                    if (context.Instruction.FlowControl == FlowControl.Call)
                    {
                        for (int s = 0; s < physicalRegisterCount; s++)
                        {
                            liveKill.Set(s, true);
                        }

                        if (liveSetTrace.Active)
                            liveSetTrace.Log("KILL ALL PHYSICAL");
                    }

                    foreach (var ops in visitor.Output)
                    {
                        if (liveSetTrace.Active)
                            liveSetTrace.Log("OUTPUT: " + ops.ToString());

                        int index = GetIndex(ops);
                        liveKill.Set(index, true);

                        if (liveSetTrace.Active)
                            liveSetTrace.Log("KILL: " + index.ToString() + " " + ops.ToString());
                    }
                }

                block.LiveGen = liveGen;
                block.LiveKill = liveKill;
                block.LiveKillNot = ((BitArray)liveKill.Clone()).Not();

                if (liveSetTrace.Active)
                {
                    liveSetTrace.Log("GEN:     " + ToString(block.LiveGen));
                    liveSetTrace.Log("KILL:    " + ToString(block.LiveKill));
                    liveSetTrace.Log("KILLNOT: " + ToString(block.LiveKillNot));
                    liveSetTrace.Log(string.Empty);
                }
            }
        }
Esempio n. 9
0
		/// <summary>
		///  Метод перемішування.
		/// </summary>
		/// <param name="x"></param>
		/// <returns></returns>
		public double Method(double x)
		{
			var q = BitConverter.GetBytes(x);
			BitArray bits = new BitArray(q);
			var left = bits.Clone() as BitArray;
			var right = bits.Clone() as BitArray;
			//Кількість розрядів для здвигу.
			var offset = 2;
			//Здвиг
			for(int i = 0; i < offset; i++)
			{
				left = ShiftLeft(left);
				right = ShiftRight(right);
			}
			//Додавання лівої та правої частин.
			var newRandomNumberBitArray = Add(left, right);
			//Переведення масиву бітів в десяткове число.
			var newRandomNumber = BitConverter.ToDouble(BitArrayToByteArray(newRandomNumberBitArray), 0);
			var newnubmer1 = BitConverter.ToDouble(BitArrayToByteArray(left), 0);
			var newnumber2 = BitConverter.ToDouble(BitArrayToByteArray(right), 0);
			var sum = newnubmer1 + newnumber2;
			return Math.Abs(newRandomNumber);
		}
Esempio n. 10
0
        //Uses a bit mask to see if a path is cut by switching routers (on bits) in roterswitches off.
        protected bool IsPathCut(BitArray path, BitArray routerswitches)
        {
            BitArray p = (BitArray)path.Clone();
            BitArray r = (BitArray)routerswitches.Clone();

            //BitArray p = ExtensionMethods.CopyBitArrayValueWise(path);
            //BitArray r = ExtensionMethods.CopyBitArrayValueWise(routerswitches);
            return (!ExtensionMethods.AreBitArraysEqual(path, p.And(r.Not())));
        }
Esempio n. 11
0
		/*		* @returns false if we couldn't assign the integers */
		private static bool AssignIntsToCriticalVertices(Graph graph, int[] g, BitArray ae, BitArray criticalNodes) {
			int x = 0;
			LinkedList<int> toProcess = new LinkedList<int>(); 
			BitArray assigned = new BitArray(g.Length);
			while(!BitArrayEquals(assigned, criticalNodes)) {

				BitArray unprocessed = (BitArray)criticalNodes.Clone(); 
				AndNot (unprocessed, assigned);

				toProcess.AddLast(NextSetBit(unprocessed, 0)); // start at the lowest unassigned critical vertex
				// assign another "tree" of vertices - not all critical ones are necessarily connected!
				x = ProcessCriticalNodes(toProcess, graph, ae, g, x, assigned, criticalNodes);
				if(x < 0) return false; // x is overloaded as a failure signal
			}
			return true;
		}
Esempio n. 12
0
 // Métodos agregados por Manuel para manejo de errores
 static BitArray addConjuntos(BitArray a, BitArray b)
 {
     BitArray c = (BitArray)a.Clone();
     c.Or(b);
     return c;
 }
Esempio n. 13
0
        /*
        //Dibuja la grafica del wave entre los valores [-15,15] hace falta aplicarle un zoom del orden alto/10
        //un buen valor seria asignar como zoom=zoomAux*alto/20
        public Bitmap DrawWave(int[] bufferEntero, int ancho, int alto, double zoom, int modo)
        {
            int zancada = Convert.ToInt32(bufferEntero.Length) / ancho;
            Bitmap aux = new Bitmap(ancho, alto);

            if (modo < 0)
                modo = 0;
            if (modo > 3)
                modo = 3;
            // Tomamos las dimensiones de la imagen
            int width = aux.Width;
            int height = aux.Height;

            // Bloqueamos las imágenes

            BitmapData destinoDatos = aux.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

            // Cogemos el ancho de línea de imagen
            int stride = destinoDatos.Stride;
            // El offset que hay que utilizar (para el relleno)
            int offset = stride - (width * 4);

            unsafe
            {
                // Empezamos en fila 0 columna 0
                byte* dst = (byte*)destinoDatos.Scan0.ToPointer() + stride;
                try
                {
                    for (int x = 0; x < width; x++, dst += 4)
                    {
                        double valorEnI = 0;
                        for (int j = 0; j < zancada; j += zancada / 20)
                        {
                            valorEnI += bufferEntero[j + x * zancada];
                        }

                        valorEnI = 20 * valorEnI / zancada;

                        double rango;
                        if (valorEnI > 0)
                        {
                            switch (modo)
                            {
                                case 3:
                                    rango = zoom * Math.Exp(Math.Log10(zoom * valorEnI / ((min_vol + max_vol) / 40)));
                                    break;
                                case 2:
                                    rango = zoom * Math.Log(zoom * valorEnI / ((min_vol + max_vol) / 40), 2);
                                    break;
                                case 1:
                                    rango = Math.Sqrt(zoom) * Math.Pow(1 + Math.Max(0, ((valorEnI - (min_vol + max_vol) / 50)) / (max_vol / 40)), zoom);
                                    break;
                                default:
                                    rango = Math.Sqrt(zoom) * Math.Pow(1 + valorEnI / (max_vol / 20), zoom);
                                    break;
                            }

                        }
                        else
                            rango = 0;

                        int arriba = Convert.ToInt32((aux.Height / 2) - rango);
                        int abajo = Convert.ToInt32((aux.Height / 2) + rango);
                        dst = (byte*)destinoDatos.Scan0.ToPointer() + stride;
                        dst += x * 4 + stride * arriba;
                        for (int y = arriba; y <= abajo; y++, dst += stride)
                        {

                            dst[0] = 255;
                            dst[1] = 0;
                            dst[2] = 0;
                            dst[3] = 255;

                        }//fin for

                    }//fin for

                }
                catch
                { //algun puntero se acaba escapando
                }

            } aux.UnlockBits(destinoDatos);

            return aux;
        }
        */
        private int Convierte(int a)
        {
            int numBits = 16;
            BitArray b = new BitArray(new int[] { a });
            BitArray bAux = (BitArray)b.Clone();
            for (int i = 0; i < b.Length; i++)
            {
                b[i] = bAux[b.Length - 1 - i];
            }
            int result = -(a & (1 << numBits - 1));
            for (int i = numBits - 2; i >= 0; i--)
                result |= (a & (1 << i));

            return result;
        }
Esempio n. 14
0
        protected int Transitions(BitArray to = null, BitArray from = null)
        {
            if (to == null)
                to = BlankSegments;
            if (from == null)
                from = BlankSegments;

            var cloneTo = (BitArray) to.Clone();
            var cloneFrom = (BitArray)from.Clone();

            var diff = cloneTo.Xor(cloneFrom);

            return diff.Cast<bool>().Count(b => b);
        }
Esempio n. 15
0
        public virtual Dictionary<string, int> RunFacet(Query query, bool showAllVersions, bool isFacet, bool isIdLookup, int pageSize, int pageNumber, string termName, List<string> termValue, BitArray queryBase, string locationFilter)
        {
            var runningCOunt = new Dictionary<string, int>();
            var db = Context.ContentDatabase ?? Sitecore.Context.Database;
            var indexName = BucketManager.GetContextIndex(db.GetItem(locationFilter));

            if (indexName.EndsWith("_remote"))
            {
                Index = RemoteSearchManager.GetIndex(indexName) as RemoteIndex;
            }
            else if (indexName.EndsWith("_inmemory"))
            {
                Index = InMemorySearchManager.GetIndex(indexName) as InMemoryIndex;
            }
            else
            {
                Index = SearchManager.GetIndex(indexName) as Index;
            }
            using (var context = new SortableIndexSearchContext(Index))
            {
                if (Config.EnableBucketDebug || Constants.EnableTemporaryBucketDebug)
                {
                    Log.Info("Using: " + indexName, this);
                    Log.Info("Bucket Facet Original Debug Query: " + query, this);
                }

                foreach (var terms in termValue)
                {
                    var genreQueryFilter = GenreQueryFilter(query, isFacet, isIdLookup, termName, terms);
                    var tempSearchArray = queryBase.Clone() as BitArray;
                    if (Config.EnableBucketDebug || Constants.EnableTemporaryBucketDebug)
                    {
                        Log.Info("Bucket Facet Debug Query: " + genreQueryFilter, this);
                    }

                    BitArray genreBitArray = genreQueryFilter.Bits(context.Searcher.GetIndexReader());
                    if (tempSearchArray.Length == genreBitArray.Length)
                    {
                        BitArray combinedResults = tempSearchArray.And(genreBitArray);

                        var cardinality = SearchHelper.GetCardinality(combinedResults);

                        if (cardinality > 0)
                        {
                            if (!isFacet)
                            {
                                if (!runningCOunt.ContainsKey(terms))
                                {
                                    runningCOunt.Add(terms, cardinality);
                                }
                            }
                            else
                            {
                                if (!runningCOunt.ContainsKey(terms))
                                {
                                    runningCOunt.Add(terms, cardinality);
                                }
                            }
                        }
                    }
                }
            }

            return runningCOunt;
        }
Esempio n. 16
0
		private static void AssignIntsToNonCriticalVertices(Graph graph, int[] g, BitArray ae, BitArray criticalNodes) {
			LinkedList<int> toProcess = new LinkedList<int>();
			for(int v = NextSetBit(criticalNodes, 0); v != -1; v = NextSetBit(criticalNodes, v+1)) { toProcess.AddLast(v); } // load with the critical vertices
			BitArray visited = (BitArray) criticalNodes.Clone();
			ProcessNonCriticalNodes(toProcess, graph, ae, visited, g); // process the critical nodes
			// we've done everything reachable from the critical nodes - but
			// what about isolated chains?
			for(int v = NextClearBit(visited, 0); v != -1 && v < g.Length; v = NextClearBit(visited, v+1)) { 
				toProcess.AddLast(v);
				ProcessNonCriticalNodes(toProcess, graph, ae, visited, g);
			}    
		}
Esempio n. 17
0
 int NewCondSet(BitArray s)
 {
     for (int i = 1; i < symSet.Count; i++) // skip symSet[0] (reserved for union of SYNC sets)
     if (Sets.Equals(s, (BitArray)symSet[i])) return i;
     symSet.Add(s.Clone());
     return symSet.Count - 1;
 }
Esempio n. 18
0
    /// <summary> Zjistí, jestli 2 bitová pole mají spoleèné bity. </summary>
    /// <param name="bits1"> 1. bitové pole. </param>
    /// <param name="bits2"> 2. bitové pole. </param>
    /// <param name="samesize"> true pokud musí být obì pole stejné délky. </param>
    /// <returns> true, pokud mají obì pole spoleèné bity. </returns>
    public static bool BitsIntersect ( BitArray bits1, BitArray bits2, bool samesize )
    {
      if ( bits1 != null && bits2 != null )
      {
        BitArray intersection;
        if ( bits1.Length == bits2.Length )
          intersection = ((BitArray)bits1.Clone()).And( bits2 );
        else
        {
          if ( samesize )
            throw new Exception( string.Format( "Other.BitsIntersect: BitArrays nemají stejnou velikost {0} <> {1}", bits1.Length, bits2.Length ) );

          BitArray bits1Temp, bits2Temp;

          if ( bits1.Length > bits2.Length )
          {
            bits1Temp = ShortenBitArray( bits1, bits2.Length );
            bits2Temp = bits2;
          }
          else
          {
            bits1Temp = (BitArray)bits1.Clone();
            bits2Temp = ShortenBitArray( bits2, bits1.Length );
          }

          intersection = bits1Temp.And( bits2Temp );
        }

        for ( int i = intersection.Length ; --i >= 0 ; )
          if ( intersection[i] )
            return true;
      }

      return false;
    }