public void TestTryGetValueAndRemoveKey(bool track)
        {
            var events = 0;
            var acc    = new Accumulator("test");
            var dic    = new TrackableDictionary <string, int>(acc, track)
            {
                { "one", 1 }, { "two", 2 }
            };

            dic.CollectionChanged += (s, e) =>
            {
                events++;
                Assert.AreEqual(e.Action, NotifyCollectionChangedAction.Remove);
                Assert.AreEqual(e.OldItems[0], new KeyValuePair <string, int>("one", 1));
            };
            Assert.IsTrue(dic.TryGetValueAndRemoveKey("one", out var val));
            Assert.AreEqual(1, val);
            Assert.IsFalse(dic.ContainsKey("one"));
            Assert.AreEqual(1, events);
            if (track)
            {
                Assert.AreEqual(3, acc.Records.Count);
            }
            else
            {
                Assert.AreEqual(0, acc.Records.Count);
            }
        }
Beispiel #2
0
        public void DeserializationTest()
        {
            //45 degre
            var rhoIntervalCount = 4;
            var conventer        = new Accumulator(4, 4, rhoIntervalCount, 4);

            List <int> indices = new List <int>()
            {
                3, 2
            };
            //rho
            // [0] = 0     - 22,5
            // [1] = 22,5  - 67,5
            // [2] = 67,5  - 112,5
            // [3] = 112,5 - 157,5
            // [4] = 157,5 - 180

            //theta
            // [0] = -2.828 - -0.0707
            // [1] = -0.707 -  1,414
            // [2] =  1,414 -  3,535
            // [3] =  3.535 -  5.656

            var pointF = conventer.GetLineFromIndex(indices);

            //2.35619449 rad =  135 deg - middle of 3rd range
            Assert.AreEqual(2.35619449, pointF.Rho, 0.0001);
            Assert.AreEqual(2.4745, pointF.Theta, 0.001);
        }
Beispiel #3
0
 static FreeTimeDebug()
 {
     totalTime     = new Accumulator <string>();
     count         = new Accumulator <string>();
     triggerTime   = new LinkedHashMap <FreeTimeDebug.ActionTime, int>();
     realTotalTime = new Accumulator <string>();
 }
Beispiel #4
0
        public Game?LoadGame()
        {
            if (!File.Exists("game.json"))
            {
                return(null);
            }
            var gameString  = File.ReadAllText("game.json");
            var gameModel   = JsonSerializer.Deserialize <GameModel>(gameString);
            var carModel    = gameModel.Car;
            var engineModel = carModel !.Engine !;
            var engine      = new Engine(engineModel.Durability, engineModel.BuyPrice,
                                         engineModel.RepairPrice, engineModel.Capacity);
            var accumulatorModel = carModel.Accumulator !;
            var accumulator      = new Accumulator(
                accumulatorModel.Durability,
                accumulatorModel.BuyPrice,
                accumulatorModel.RepairPrice,
                accumulatorModel.Capacity);
            var disks = carModel.Disks
                        !.Select(x => new Disk(x.Durability, x.BuyPrice, x.RepairPrice, x.Capacity))
                        .ToArray();
            var car         = new Car(engine, accumulator, disks);
            var playerModel = gameModel.Player;
            var player      = new Player(playerModel !.Money);

            return(new Game(car, player));
        }
Beispiel #5
0
        public void SerializationTest()
        {
            //45 degre
            var rhoIntervalCount = 4;


            var conventer = new Accumulator(4, 4, rhoIntervalCount, 4);
            var pointF    = new PolarPointF()
            {
                Rho   = 1.22173048, // 70 degre
                Theta = 4
            };

            var indexes = conventer.GetAccumulatorIndex(pointF);

            Assert.AreEqual(2, indexes[0]);
            Assert.AreEqual(3, indexes[1]);
            //rho
            // [0] = 0     - 22,5
            // [1] = 22,5  - 67,5
            // [2] = 67,5  - 112,5
            // [3] = 112,5 - 157,5
            // [4] = 157,5 - 180

            //theta
            // [0] = -2.828 - -0.0707
            // [1] = -0.707 -  1,141
            // [2] =  1,141 -  3,535
            // [3] =  3.535 -  5.656
        }
 public Task( long start , long end , double delta , Accumulator accumulator )
 {
     this.start = start ;
       this.end = end ;
       this.delta = delta ;
       this.accumulator = accumulator ;
 }
Beispiel #7
0
 public static QueryMetrics ToQueryMetrics(Accumulator accumulator)
 {
     return(new QueryMetrics(
                BackendMetrics.Accumulator.ToBackendMetrics(accumulator.BackendMetricsAccumulator),
                IndexUtilizationInfo.Accumulator.ToIndexUtilizationInfo(accumulator.IndexUtilizationInfoAccumulator),
                ClientSideMetrics.Accumulator.ToClientSideMetrics(accumulator.ClientSideMetricsAccumulator)));
 }
 private static void execute( int numberOfTasks )
 {
     const long n = 1000000000L ;
     const double delta = 1.0 / n ;
     long startTimeHundredsOfNanos = System.DateTime.Now.Ticks ;
     long sliceSize = n / numberOfTasks ;
     System.Threading.Thread[] threads = new System.Threading.Thread [ numberOfTasks ] ;
     Accumulator accumulator = new Accumulator ( ) ;
     for ( int i = 0 ; i < numberOfTasks ; ++i ) {
       long start = 1 + i * sliceSize ;
       long end =  ( i + 1 ) * sliceSize ;
       threads[i] = new System.Threading.Thread ( new System.Threading.ThreadStart ( delegate ( ) {
         double localSum = 0.0 ;
         for ( long j = start ; j <= end ; ++j ) {
           double x = ( j - 0.5 ) * delta ;
           localSum += 1.0 / ( 1.0 + x * x ) ;
         }
         accumulator.add ( localSum ) ;
       }
       ) ) ;
     }
     foreach ( System.Threading.Thread t in threads ) { t.Start ( ) ; }
     foreach ( System.Threading.Thread t in threads ) { t.Join ( ) ; }
     double pi = 4.0 * delta * accumulator.getSum ( ) ;
     double elapseTime = ( System.DateTime.Now.Ticks - startTimeHundredsOfNanos ) / 1e7 ;
     System.Console.WriteLine ( "==== C# Threads Anonymous Delegate Sync Object pi = " + pi ) ;
     System.Console.WriteLine ( "==== C# Threads Anonymous Delegate Sync Object iteration count = " + n ) ;
     System.Console.WriteLine ( "==== C# Threads Anonymous Delegate Sync Object elapse = " + elapseTime ) ;
     System.Console.WriteLine ( "==== C# Threads Anonymous Delegate Sync Object processor count = " + System.Environment.ProcessorCount ) ;
     System.Console.WriteLine ( "==== C# Threads Anonymous Delegate Sync Object thread count = " + numberOfTasks ) ;
 }
		public MemoryMeasurementEvaluation(
			FromProcessMeasurement<MemoryStruct.IMemoryMeasurement> MemoryMeasurement,
			Accumulator.MemoryMeasurementAccumulator MemoryMeasurementAccu = null)
		{
			this.MemoryMeasurement = MemoryMeasurement?.Value;

			try
			{
				MemoryMeasurementParsed = MemoryMeasurement?.Value?.Parse();
			}
			catch (Exception Exception)
			{
				MemoryMeasurementParseException = Exception;
			}

			if (null == MemoryMeasurement)
			{
				return;
			}

			try
			{
				MemoryMeasurementAccu = MemoryMeasurementAccu ?? new Accumulator.MemoryMeasurementAccumulator();

				MemoryMeasurementAccu.Accumulate(MemoryMeasurement?.MapValue(t => MemoryMeasurementParsed));

				this.MemoryMeasurementAccumulation = MemoryMeasurementAccu;
			}
			catch (Exception Exception)
			{
				MemoryMeasurementAccuException = Exception;
			}
		}
Beispiel #10
0
        public void TestAccumuatorSuccess()
        {
            Accumulator <int> accumulator = sc.Accumulator <int>(0);

            using (var s = sock.GetStream())
            {
                // write numUpdates
                int numUpdates = 1;
                SerDe.Write(s, numUpdates);

                // write update
                int key   = 0;
                int value = 100;
                Tuple <int, dynamic> update = new Tuple <int, dynamic>(key, value);
                var ms        = new MemoryStream();
                var formatter = new BinaryFormatter();
                formatter.Serialize(ms, update);
                byte[] sendBuffer = ms.ToArray();
                SerDe.Write(s, sendBuffer.Length);
                SerDe.Write(s, sendBuffer);

                s.Flush();
                byte[] receiveBuffer = new byte[1];
                s.Read(receiveBuffer, 0, 1);

                Assert.AreEqual(accumulator.Value, value);
            }
        }
 private static void execute(int numberOfTasks) {
   const long n = 1000000000L;
   const double delta = 1.0 / n;
   long startTimeHundredsOfNanos = System.DateTime.Now.Ticks;
   long sliceSize = n / numberOfTasks;
   System.Threading.Thread[] threads = new System.Threading.Thread[numberOfTasks];
   Accumulator accumulator = new Accumulator();
   for (int i = 0; i < numberOfTasks; ++i) {
     long start = 1 + i * sliceSize;
     long end = (i + 1) * sliceSize;
     threads[i] = new System.Threading.Thread(new System.Threading.ThreadStart(delegate() {
           double localSum = 0.0;
           for (long j = start; j <= end; ++j) {
             double x = (j - 0.5) * delta;
             localSum += 1.0 / (1.0 + x * x);
           }
           accumulator.add(localSum);
         }
        ));
   }
   foreach (System.Threading.Thread t in threads) { t.Start(); }
   foreach (System.Threading.Thread t in threads) { t.Join(); }
   double pi = 4.0 * delta * accumulator.getSum();
   double elapseTime = (System.DateTime.Now.Ticks - startTimeHundredsOfNanos) / 1e7;
   Output.output("Threads Anonymous Delegate Sync Object", pi, n, elapseTime, numberOfTasks);
 }
Beispiel #12
0
        /// <summary>
        /// Executes the GET command.
        /// </summary>
        public void Execute()
        {
            if (!_runEnvironment.CurrentLine.LineNumber.HasValue)
            {
                throw new Exceptions.IllegalDirectException();
            }

            var         variableReference = _expressionEvaluator.GetLeftValue();
            var         newChar           = _teletypeWithPosition.ReadChar();
            Accumulator newValue;

            if (variableReference.IsString)
            {
                newValue = new Accumulator(newChar.ToString());
            }
            else
            {
                if ("+-E.\0".Contains(newChar.ToString()))
                {
                    newChar = '0';
                }

                if (newChar < '0' || newChar > '9')
                {
                    throw new Exceptions.SyntaxErrorException();
                }

                newValue = new Accumulator((double)(newChar - '0'));
            }

            variableReference.SetValue(newValue);
        }
Beispiel #13
0
        /// <include file='FactorDocs.xml' path='factor_docs/message_op_class[@name="UsesEqualDefGibbsOp2{T}"]/message_doc[@name="MarginalEstimatorInit{TDist}(TDist, int)"]/*'/>
        public static BurnInAccumulator <TDist> MarginalEstimatorInit <TDist>([IgnoreDependency] TDist to_marginal, int burnIn)
            where TDist : IDistribution <T>
        {
            Accumulator <TDist> est = (Accumulator <TDist>)ArrayEstimator.CreateEstimator <TDist, T>(to_marginal, true);

            return(new BurnInAccumulator <TDist>(burnIn, 1, est));
        }
        /// <summary>
        /// Executes a user defined function.
        /// </summary>
        /// <param name="parameter">new parameter value.</param>
        /// <param name="runEnvironment">Run evironment.</param>
        /// <param name="expressionEvaluator">Expression evaluator.</param>
        /// <param name="variableRepository">Variable repository.</param>
        /// <returns>Value of function.</returns>
        public Accumulator Execute(
            Accumulator parameter,
            IRunEnvironment runEnvironment,
            IExpressionEvaluator expressionEvaluator,
            IVariableRepository variableRepository)
        {
            // Save the variable and program line.
            var savedVariable    = variableRepository.GetOrCreateVariable(VariableName, new short[] { }).GetValue();
            var savedProgramLine = runEnvironment.CurrentLine;

            // Change the variable to be our parameter.
            variableRepository.GetOrCreateVariable(VariableName, new short[] { }).SetValue(parameter);
            runEnvironment.CurrentLine = Line;
            runEnvironment.CurrentLine.CurrentToken = LineToken;

            // Evaluate the expression.
            var returnValue = expressionEvaluator.GetExpression();

            // Restore the variable and program line.
            variableRepository.GetOrCreateVariable(VariableName, new short[] { }).SetValue(savedVariable);
            runEnvironment.CurrentLine = savedProgramLine;

            // return the value.
            return(returnValue);
        }
            Tuple <T, FSharpList <TEvent> > decide_(TState state)
            {
                var a = new Accumulator <TEvent, TState>(FuncConvert.FromFunc(_fold), state);
                var r = decide(a);

                return(Tuple.Create(r, a.Accumulated));
            }
Beispiel #16
0
        /// <summary>
        /// Updates the accumulator with values added to and removed from the revocation list.
        /// Although unuseful, it is legal to have a value present in both the revoked and unrevoked set.
        /// </summary>
        /// <param name="revoked">Set of values to add to the accumulator.</param>
        /// <param name="unrevoked">Set of values to remove from the accumulator (optional).</param>
        public void UpdateAccumulator(HashSet <FieldZqElement> revoked, HashSet <FieldZqElement> unrevoked = null)
        {
            var minusDelta = PrivateKey.Negate();

            var exponent = RAParameters.group.FieldZq.One;

            if (revoked != null)
            {
                foreach (var x in revoked)
                {
                    if (minusDelta.Equals(x)) // TODO: add unit test with -delta on revocation list
                    {
                        throw new ArgumentException("revoked set cannot contain the negation of the private key");
                    }
                    exponent *= (PrivateKey + x);
                }
                Accumulator = Accumulator.Exponentiate(exponent);
            }

            exponent = RAParameters.group.FieldZq.One;
            if (unrevoked != null)
            {
                foreach (var x in unrevoked)
                {
                    if (minusDelta.Equals(x)) // TODO: add unit test with -delta on revocation list
                    {
                        throw new ArgumentException("unrevoked set cannot contain the negation of the private key");
                    }
                    exponent *= (PrivateKey + x);
                }
                Accumulator = Accumulator.Exponentiate(exponent.Invert());
            }
        }
Beispiel #17
0
        EstimateDistributionParameters(
            IEnumerable <double> samples
            )
        {
            Accumulator accumulator = new Accumulator(samples);

            SetDistributionParameters(accumulator.Mean, accumulator.Sigma);
        }
Beispiel #18
0
        public void AccumulatorInitialiseToShort()
        {
            var sut = new Accumulator((short)-3);

            Assert.AreEqual(typeof(short), sut.Type);
            Assert.AreEqual((short)-3, sut.ValueAsShort());
            Assert.AreEqual("-3 ", sut.ToString());
        }
Beispiel #19
0
        public void AccumulatorInitialiseToDouble()
        {
            var sut = new Accumulator(3.25);

            Assert.AreEqual(typeof(double), sut.Type);
            Assert.AreEqual(3.25, sut.ValueAsDouble());
            Assert.AreEqual(" 3.25 ", sut.ToString());
        }
 public ConfigurationDefault(ReadonlyMemory memory, RandomAccessMemory ram, GraphicsProcessor graphicsProcessor, Accumulator accumulator, InputDevice inputDevice, Random random) : base(memory)
 {
     RAM = ram;
     GraphicsProcessor = graphicsProcessor;
     Accumulator       = accumulator;
     InputDevice       = inputDevice;
     Random            = random;
 }
Beispiel #21
0
        public void AccumulatorInitialiseToString()
        {
            var sut = new Accumulator("HELLO");

            Assert.AreEqual(typeof(string), sut.Type);
            Assert.AreEqual("HELLO", sut.ValueAsString());
            Assert.AreEqual("HELLO", sut.ToString());
        }
Beispiel #22
0
        public CalculatorTest()
        {
            // Create the validator mock.
            ValidatorMock = new Mock<IValidator>();

            // Create the object to test.
            TestedObject = new Accumulator(ValidatorMock.Object);
        }
Beispiel #23
0
 internal IEnumerable <dynamic> Execute(int pid, IEnumerable <dynamic> iter)
 {
     return(iter.Select(e =>
     {
         accumulator += 1;
         return e;
     }));
 }
Beispiel #24
0
 public static IndexUtilizationInfo ToIndexUtilizationInfo(Accumulator accumulator)
 {
     return(new IndexUtilizationInfo(
                utilizedSingleIndexes: accumulator.UtilizedSingleIndexes.ToList(),
                potentialSingleIndexes: accumulator.PotentialSingleIndexes.ToList(),
                utilizedCompositeIndexes: accumulator.UtilizedCompositeIndexes.ToList(),
                potentialCompositeIndexes: accumulator.PotentialCompositeIndexes.ToList()));
 }
Beispiel #25
0
        public Processor(MemoryMap memory)
        {
            this.Memory           = memory;
            instructions          = new InstructionSet();
            extraCodeInstructions = new ExtraCodeInstructionSet();

            // configure registers

            // main registers?
            A  = memory.AddRegister <Accumulator>(0x00);
            L  = memory.AddRegister <ErasableMemory>(0x01);
            Q  = memory.AddRegister <FullRegister>(0x02);
            EB = memory.AddRegister <ErasableBankRegister>(0x03);
            FB = memory.AddRegister <FixedBankRegister>(0x4);
            Z  = memory.AddRegister <ProgramCounter>(0x05);
            BB = memory.AddRegister <BothBanksRegister>(0x06);

            //memory[0x7] = 0; // this is always set to 0, TODO: need to hard code?

            // interrupt helper registers
            ARUPT = memory.AddRegister <ErasableMemory>(0x08);
            LRUPT = memory.AddRegister <ErasableMemory>(0x09);
            QRUPT = memory.AddRegister <ErasableMemory>(0x0A);
            // 0XB, 0XC are spares. not used?
            ZRUPT  = memory.AddRegister <ErasableMemory>(0x0D);
            BBRUPT = memory.AddRegister <ErasableMemory>(0x0E);
            BRUPT  = memory.AddRegister <ErasableMemory>(0x0F);

            // editing registers
            CYR  = memory.AddRegister <CycleRightRegister>(0x10);
            SR   = memory.AddRegister <ShiftRightRegister>(0x11);
            CYL  = memory.GetWord(0x12);
            EDOP = memory.GetWord(0x13);

            // time registers
            TIME2 = memory.GetWord(0x14);
            TIME1 = memory.GetWord(0x15);
            TIME3 = memory.GetWord(0x16);
            TIME4 = memory.GetWord(0x17);
            TIME5 = memory.GetWord(0x18);
            TIME6 = memory.GetWord(0x19);

            // orientation registers
            CDUX  = memory.AddRegister <ErasableMemory>(0x1A);
            CDUY  = memory.AddRegister <ErasableMemory>(0x1B);
            CDUZ  = memory.AddRegister <ErasableMemory>(0x1C);
            OPTY  = memory.AddRegister <ErasableMemory>(0x1D);
            OPTX  = memory.AddRegister <ErasableMemory>(0x1E);
            PIPAX = memory.AddRegister <ErasableMemory>(0x1F);
            PIPAY = memory.AddRegister <ErasableMemory>(0x20);
            PIPAZ = memory.AddRegister <ErasableMemory>(0x21);
            // LM Only Pitch, Yaw, and Roll registers

            INLINK = memory.AddRegister <ErasableMemory>(0x25);

            // prime Z to start at the boot interrupt
            Z.Write(new OnesCompliment(0x800));
        }
Beispiel #26
0
        public void DynamicBinaryUnidirectional()
        {
            dynamic x = new Accumulator(23);
            dynamic y = new AddableNum(42);
            dynamic r = x + y;

            Assert.Equal(23 + 42, r.Value);
            Assert.Throws <RuntimeBinderException>(() => y + x);
        }
Beispiel #27
0
        public static async Task InvokeActionAsyncFailure()
        {
            var    acc    = new Accumulator();
            Action action = acc.IncBy1;

            action += acc.Throw;
            action += acc.IncBy3;
            await ThrowsAsync <Exception>(async() => await action.InvokeAsync());
        }
Beispiel #28
0
        private double EvaluateInternal(ValueVector x, ValueVector y, int size)
        {
            Accumulator acc = CreateAccumulator();

            // error handling is as if the x is fully evaluated before y
            ErrorEval firstXerr      = null;
            ErrorEval firstYerr      = null;
            bool      accumlatedSome = false;
            double    result         = 0.0;

            for (int i = 0; i < size; i++)
            {
                ValueEval vx = x.GetItem(i);
                ValueEval vy = y.GetItem(i);
                if (vx is ErrorEval)
                {
                    if (firstXerr == null)
                    {
                        firstXerr = (ErrorEval)vx;
                        continue;
                    }
                }
                if (vy is ErrorEval)
                {
                    if (firstYerr == null)
                    {
                        firstYerr = (ErrorEval)vy;
                        continue;
                    }
                }
                // only count pairs if both elements are numbers
                if (vx is NumberEval && vy is NumberEval)
                {
                    accumlatedSome = true;
                    NumberEval nx = (NumberEval)vx;
                    NumberEval ny = (NumberEval)vy;
                    result += acc.Accumulate(nx.NumberValue, ny.NumberValue);
                }
                else
                {
                    // all other combinations of value types are silently ignored
                }
            }
            if (firstXerr != null)
            {
                throw new EvaluationException(firstXerr);
            }
            if (firstYerr != null)
            {
                throw new EvaluationException(firstYerr);
            }
            if (!accumlatedSome)
            {
                throw new EvaluationException(ErrorEval.DIV_ZERO);
            }
            return(result);
        }
Beispiel #29
0
 public void Reset()
 {
     RunningAverage.Reset();
     PerSecond.Reset();
     Accumulator.Reset();
     Snapshot.Reset();
     Peak.Reset();
     SnapshotDouble.Reset();
 }
Beispiel #30
0
        public void AccumulatorSetValueToShort()
        {
            var sut = new Accumulator(0.0);

            sut.SetValue((short)-3);
            Assert.AreEqual(typeof(short), sut.Type);
            Assert.AreEqual((short)-3, sut.ValueAsShort());
            Assert.AreEqual("-3 ", sut.ToString());
        }
Beispiel #31
0
        public void AccumulatorSetValueToString()
        {
            var sut = new Accumulator(0.0);

            sut.SetValue("HELLO");
            Assert.AreEqual(typeof(string), sut.Type);
            Assert.AreEqual("HELLO", sut.ValueAsString());
            Assert.AreEqual("HELLO", sut.ToString());
        }
        public void MulShiftTest()
        {
            Accumulator <Pow2.N4> v1 = new Accumulator <Pow2.N4>(Mantissa <Pow2.N4> .Full);
            Accumulator <Pow2.N4> v2 = new Accumulator <Pow2.N4>(Mantissa <Pow2.N4> .One);
            Accumulator <Pow2.N4> v3 = v1 * 5 / 9;

            Accumulator <Pow2.N4> v11 = Accumulator <Pow2.N4> .MulShift(v1, v1);

            Console.WriteLine(v11.ToHexcode());
            Assert.AreEqual(5, v11.Digits);

            Accumulator <Pow2.N4> v12 = Accumulator <Pow2.N4> .MulShift(v1, v2);

            Console.WriteLine(v12.ToHexcode());
            Assert.AreEqual(4, v12.Digits);
            Assert.AreEqual(v1, v12);

            Accumulator <Pow2.N4> v13 = Accumulator <Pow2.N4> .MulShift(v1, v3);

            Console.WriteLine(v13.ToHexcode());
            Assert.AreEqual(5, v13.Digits);

            Accumulator <Pow2.N4> v21 = Accumulator <Pow2.N4> .MulShift(v2, v1);

            Console.WriteLine(v21.ToHexcode());
            Assert.AreEqual(4, v21.Digits);
            Assert.AreEqual(v1, v21);

            Accumulator <Pow2.N4> v22 = Accumulator <Pow2.N4> .MulShift(v2, v2);

            Console.WriteLine(v22.ToHexcode());
            Assert.AreEqual(4, v22.Digits);
            Assert.AreEqual(v2, v22);

            Accumulator <Pow2.N4> v23 = Accumulator <Pow2.N4> .MulShift(v2, v3);

            Console.WriteLine(v23.ToHexcode());
            Assert.AreEqual(4, v23.Digits);
            Assert.AreEqual(v3, v23);

            Accumulator <Pow2.N4> v31 = Accumulator <Pow2.N4> .MulShift(v3, v1);

            Console.WriteLine(v31.ToHexcode());
            Assert.AreEqual(5, v31.Digits);

            Accumulator <Pow2.N4> v32 = Accumulator <Pow2.N4> .MulShift(v3, v2);

            Console.WriteLine(v32.ToHexcode());
            Assert.AreEqual(4, v32.Digits);
            Assert.AreEqual(v3, v32);

            Accumulator <Pow2.N4> v33 = Accumulator <Pow2.N4> .MulShift(v3, v3);

            Console.WriteLine(v33.ToHexcode());
            Assert.AreEqual(4, v33.Digits);
        }
Beispiel #33
0
 public Convolution1D(
     Vector <V> v,
     Accumulator <U, V> acc,
     Func <int, U> factory)
 {
     this.v       = v;
     this.vc      = v.Length / 2;
     this.acc     = acc;
     this.factory = factory;
 }
Beispiel #34
0
        /// <summary>
        /// Can a meld be added to the current accumulator?
        /// </summary>
        private bool CanAddMeld(int index, Mentsu mentsu)
        {
            if (index > TypesInSuit - mentsu.Stride)
            {
                return(false);
            }
            var max = TilesPerType - mentsu.Amount;

            return(Accumulator.Skip(index).Take(mentsu.Stride).All(i => i <= max));
        }
Beispiel #35
0
 public Convolution2D(
     Matrix <V> v,
     Accumulator <U, V> acc,
     Func <int, int, U> factory)
 {
     this.v       = v;
     this.vc      = Vector.Build <int>().Dense(v.RowCount / 2, v.ColumnCount / 2);
     this.acc     = acc;
     this.factory = factory;
 }
Beispiel #36
0
        public void CreateAndProcessOneMessage()
        {
            ManualResetEvent handle = new ManualResetEvent(false);

            Accumulator accumulator = new Accumulator(1, handle);
            MessageActor<int> actor = new MessageActor<int>(accumulator);

            actor.Send(1);

            handle.WaitOne();

            Assert.AreEqual(1, accumulator.Result);
        }
 private  Accumulator<Guid,Store> Initialize(int count)
 {
     _repository = new ConcurrentDictionary<Guid, Store>(
         MockHelper.RandomPairs<Guid, string>(count)
                   .Select(k => new Store {Key = k.Item1, Name = k.Item2})
                   .ToDictionary(k => k.Key));
     var accDict = new Accumulator<Guid, Store>(
         (k,v,t)=>_repository.AddOrUpdate(k,v,(l,m)=>v),
         _repository.ContainsKey,
         key=>_repository[key],
         k=>k.Select(Get).ToDictionary(k2=>k2.Key));
     return accDict;
 }
Beispiel #38
0
 static void fill_accumulator(Accumulator acc, int x_steps, int y_steps, int z_steps, System.Func<double,double,double,int> f)
 {
     foreach (var x in range(x_steps))
     {
         foreach (var y in range(y_steps))
         {
             foreach (var z in range(z_steps))
             {
                 int rgbint = f(x,y,z);
                 acc.Increment(rgbint);
             }
         }
     }            
 }
Beispiel #39
0
        public void TestAccumulatorInWorker()
        {
            StringBuilder output = new StringBuilder();

            Process worker;
            TcpListener CSharpRDD_SocketServer = CreateServer(output, out worker);

            using (var serverSocket = CSharpRDD_SocketServer.AcceptSocket())
            using (var s = new NetworkStream(serverSocket))
            {
                WritePayloadHeaderToWorker(s);
                const int accumulatorId = 1001;
                var accumulator = new Accumulator<int>(accumulatorId, 0);
                byte[] command = SparkContext.BuildCommand(new CSharpWorkerFunc(new AccumulatorHelper(accumulator).Execute),
                    SerializedMode.String, SerializedMode.String);

                SerDe.Write(s, command.Length);
                SerDe.Write(s, command);

                const int expectedCount = 100;
                for (int i = 0; i < expectedCount; i++)
                {
                    SerDe.Write(s, i.ToString());
                }

                SerDe.Write(s, (int)SpecialLengths.END_OF_DATA_SECTION);
                SerDe.Write(s, (int)SpecialLengths.END_OF_STREAM);
                s.Flush();

                int count = 0;
                foreach (var bytes in ReadDataSection(s))
                {
                    Assert.AreEqual(count++.ToString(), Encoding.UTF8.GetString(bytes));
                }

                Assert.AreEqual(expectedCount, count);

                // read accumulator
                int accumulatorsCount = SerDe.ReadInt(s);
                Assert.IsTrue(accumulatorsCount == 1);
                var accumulatorFromWorker = ReadAccumulator(s, accumulatorsCount).First();
                Assert.AreEqual(accumulatorId, accumulatorFromWorker.Key);
                Assert.AreEqual(expectedCount, accumulatorFromWorker.Value);

                SerDe.ReadInt(s);
            }

            AssertWorker(worker, output);
            CSharpRDD_SocketServer.Stop();
        }
        public override IAccumulator BuildAccumulator(IEnumerable<string> variables)
        {
            var acc = new Accumulator(variables, SortVariables);
            var variableIndexes = new int[_matchLength];
            for(int i = 0 ; i < _matchLength; i++)
            {
                variableIndexes[i] = acc.Columns.IndexOf(SortVariables[i]);
            }

            if (_matchEnumerations.Count == 1)
            {
                return new VirtualizingAccumulator(acc.Columns, _matchEnumerations[0], variableIndexes, SortVariables);
            }

            bool keepGoing = true;
            ulong[] toMatch = new ulong[_matchLength];
            foreach (var enumerator in _matchEnumerations)
            {
                keepGoing &= enumerator.MoveNext();
                if (CompareArrays(enumerator.Current, toMatch) > 0) toMatch = enumerator.Current;
            }
            while (keepGoing)
            {
                for(int i = 0; i < _matchEnumerations.Count; i++)
                {
                    while(keepGoing && CompareArrays(toMatch, _matchEnumerations[i].Current) > 0)
                    {
                        keepGoing &= _matchEnumerations[i].MoveNext();
                    }
                    if (keepGoing && CompareArrays(_matchEnumerations[i].Current, toMatch) > 0)
                    {
                        toMatch = _matchEnumerations[i].Current;
                    }
                }
                if (keepGoing && _matchEnumerations.All(x=>CompareArrays(toMatch, x.Current) == 0))
                {
                    // Bingo!
                    var newRow = new ulong[acc.Columns.Count];
                    for(int i = 0; i < _matchLength; i++)
                    {
                        newRow[variableIndexes[i]] = toMatch[i];
                    }
                    acc.AddRow(newRow);
                    keepGoing &= _matchEnumerations[0].MoveNext();
                    toMatch = _matchEnumerations[0].Current;
                }
            }
            return acc;
        }
 static void Main(string[] args)
 {
     try {
         // Compare using Accumulator and ordinary summation for a sum of large and
         // small terms.
         double sum = 0;
         Accumulator acc = new Accumulator();
         acc.Assign( 0.0 );
         sum += 1e20; sum += 1; sum += 2; sum += 100; sum += 5000; sum += -1e20;
         acc.Sum( 1e20 ); acc.Sum( 1 ); acc.Sum( 2 ); acc.Sum( 100 ); acc.Sum( 5000 ); acc.Sum( -1e20 );
         Console.WriteLine(String.Format("{0} {1}", sum, acc.Result()));
     }
     catch (GeographicErr e) {
         Console.WriteLine( String.Format(  "Caught exception: {0}", e.Message ) );
     }
 }
 private static void execute(int numberOfTasks) {
   const long n = 1000000000L;
   const double delta = 1.0 / n;
   long startTimeHundredsOfNanos = System.DateTime.Now.Ticks;
   long sliceSize = n / numberOfTasks;
   System.Threading.Thread[] threads = new System.Threading.Thread [ numberOfTasks ];
   Accumulator accumulator = new Accumulator();
   for (int i = 0; i < numberOfTasks; ++i) {
     Task task = new Task(1 + i * sliceSize ,  (i + 1) * sliceSize , delta , accumulator);
     threads[i] = new System.Threading.Thread(new System.Threading.ThreadStart(task.execute));
   }
   foreach (System.Threading.Thread t in threads) { t.Start(); }
   foreach (System.Threading.Thread t in threads) { t.Join(); }
   double pi = 4.0 * delta * accumulator.getSum();
   double elapseTime = (System.DateTime.Now.Ticks - startTimeHundredsOfNanos) / 1e7;
   Output.output("Threads Task Class Delegate Sync Object", pi, n, elapseTime, numberOfTasks);
 }
Beispiel #43
0
        private static void Main(string[] args)
        {
            const int acc_size = 256 * 256 * 256;
            const string hdr = "h_steps,s_steps,l_steps,notfound,found,foundmult,foundsingle,miliseconds";
            string filename = "output_" + System.DateTime.Now.ToString("s").Replace(":", "-") + ".txt";

            var steps_col_a = Enumerable.Range(1,10).Select(i=>i*100); // hundreds 100, 200, ... 1000
            var steps_col_b = Enumerable.Range(64, 193); // 64 to 256
            var steps_col_c = new int[] { 256 }; // 

            var steps_col = steps_col_c;

            var stopwatch = new System.Diagnostics.Stopwatch();
            var acc = new Accumulator(acc_size);
            var fp = System.IO.File.CreateText(filename);

            Console.WriteLine(hdr);
            fp.WriteLine(hdr);
            
            foreach (int numsteps in steps_col)
            {
                acc.Clear();
                stopwatch.Reset();
                stopwatch.Start();

                // for each hsl value, calculate the 24bit rgb value
                // and then increment the corresponding index in the accumulator
                int h_steps = numsteps;
                int s_steps = numsteps;
                int l_steps = numsteps;

                fill_accumulator(acc,h_steps, s_steps, l_steps, ColorRGBBit.HSL_To_RGBInt );

                var stats = acc.GetStats();
                stopwatch.Stop();

                string msg = string.Format("{0},{1},{2}", h_steps, stopwatch.ElapsedMilliseconds,stats.ToCSV());
                Console.WriteLine(msg);
                fp.WriteLine(msg);
            }
           fp.Close();
        }
        public override IAccumulator BuildAccumulator(IEnumerable<string> variables)
        {
            var acc = new Accumulator(variables, SortVariables);
            var variableIndexes = new int[_matchLength];
            for (int i = 0; i < _matchLength; i++)
            {
                variableIndexes[i] = acc.Columns.IndexOf(SortVariables[i]);
            }

            foreach(var triple in _store.MatchAllTriples(_graphUris))
            {
                var newRow = new ulong[acc.Columns.Count];
                for (int i = 0; i < _matchLength; i++)
                {
                    newRow[variableIndexes[i]] = triple[i];
                }
                acc.AddRow(newRow);
            }
            return acc;
        }
        public void TestAccumulatingWithCache()
        {
            var cache =
                new UpgradedCache
                    <Guid, TestClass, NoReferenceUpdatableElement<TestClass>>(true,
                    Comparer<Guid>.Default,  EqualityComparer<Guid>.Default,
                                                                a => a());
            var acc = new Accumulator<Guid, TestClass>(
                cache.Push, 
                cache.HasActualValue,
                k => cache.RetrieveByFunc(k, o => new TestClass {Test = k.ToString()}),
                k => k.ToDictionary(k2 => k2, k2 => new TestClass {Test = k2.ToString()}));
            var count = 100000;
            var keys = Enumerable.Range(0, count).Select(_ => Guid.NewGuid()).ToArray();

            var t1 = Get(acc, keys.Take(count/3));

            var res1 = t1.ContinueWith(tt =>
                                           {
                                               GC.Collect(2, GCCollectionMode.Forced);
                                               return Get2(tt.Result);
                                           });
            var t2 = t1.ContinueWith(tt2 => Get(acc, keys.Skip(count/3).Take(count/3))
                                                .ContinueWith(t =>
                                                                  {
                                                                      GC.Collect
                                                                          (2,  GCCollectionMode.Forced);
                                                                      return  Get2(t.Result);
                                                                  }));

            var res3 = Get(acc, keys.Skip(count/3*2).ToArray())
                             .ContinueWith(t =>
                                  {
                                      GC.Collect(2, GCCollectionMode.Forced);
                                      return Get2(t.Result);
                                  });

            Assert.AreEqual(res1.Result.Count(k => k!=null),count/3);
            Assert.AreEqual(t2.Result.Result.Count(k => k != null), count/3);
            Assert.AreEqual(res3.Result.Count(k => k != null), count -  count / 3*2);
        }
        public override IAccumulator BuildAccumulator(IEnumerable<string> variables)
        {
            var acc = new Accumulator(variables, _triplePatterns[0].Variables.Take(1));
            var varIx = acc.Columns.IndexOf(_triplePatterns[0].Variables[0]);

            bool keepGoing = true;
            ulong[] topItems = new ulong[_matchEnumerations.Count];
            ulong toMatch = 0;
            for (int i = 0; i < _matchEnumerations.Count; i++)
            {
                keepGoing &= _matchEnumerations[i].MoveNext();
                if (!keepGoing) break;
                topItems[i] = _matchEnumerations[i].Current;
                if (topItems[i] > toMatch) toMatch = topItems[i];
            }
            while (keepGoing)
            {
                for(int i = 0; i < _matchEnumerations.Count; i++)
                {
                    while (_matchEnumerations[i].Current < toMatch && keepGoing)
                    {
                        keepGoing &= _matchEnumerations[i].MoveNext();
                    }
                    if (keepGoing && _matchEnumerations[i].Current > toMatch)
                    {
                        toMatch = _matchEnumerations[i].Current;
                    }
                }
                if (keepGoing && _matchEnumerations.All(x=>x.Current.Equals(toMatch)))
                {
                    // Bingo!
                    var newRow = new ulong[acc.Columns.Count];
                    newRow[varIx] = toMatch;
                    acc.AddRow(newRow);
                    keepGoing &= _matchEnumerations[0].MoveNext();
                    toMatch = _matchEnumerations[0].Current;
                }
            }
            return acc;
        }
 private static void execute( int numberOfTasks )
 {
     const long n = 1000000000L ;
     const double delta = 1.0 / n ;
     long startTimeHundredsOfNanos = System.DateTime.Now.Ticks ;
     long sliceSize = n / numberOfTasks ;
     System.Threading.Thread[] threads = new System.Threading.Thread [ numberOfTasks ] ;
     Accumulator accumulator = new Accumulator ( ) ;
     for ( int i = 0 ; i < numberOfTasks ; ++i ) {
       Task task = new Task ( 1 + i * sliceSize ,  ( i + 1 ) * sliceSize , delta , accumulator ) ;
       threads[i] = new System.Threading.Thread ( new System.Threading.ThreadStart ( task.execute ) ) ;
     }
     foreach ( System.Threading.Thread t in threads ) { t.Start ( ) ; }
     foreach ( System.Threading.Thread t in threads ) { t.Join ( ) ; }
     double pi = 4.0 * delta * accumulator.getSum ( ) ;
     double elapseTime = ( System.DateTime.Now.Ticks - startTimeHundredsOfNanos ) / 1e7 ;
     System.Console.WriteLine ( "==== C# Threads Task Class Delegate Sync Object pi = " + pi ) ;
     System.Console.WriteLine ( "==== C# Threads Task Class Delegate Sync Object iteration count = " + n ) ;
     System.Console.WriteLine ( "==== C# Threads Task Class Delegate Sync Object elapse = " + elapseTime ) ;
     System.Console.WriteLine ( "==== C# Threads Task Class Delegate Sync Object processor count = " + System.Environment.ProcessorCount ) ;
     System.Console.WriteLine ( "==== C# Threads Task Class Delegate Sync Object thread count = " + numberOfTasks ) ;
 }
Beispiel #48
0
 internal IEnumerable<dynamic> Execute(int pid, IEnumerable<dynamic> iter)
 {
     return iter.Select(e =>
     {
         accumulator += 1;
         return e;
     });
 }
Beispiel #49
0
 internal AccumulatorHelper(Accumulator<int> accumulator)
 {
     this.accumulator = accumulator;
 }
Beispiel #50
0
 private static void ConfirmXY(Accumulator acc, double[] xarr, double[] yarr,
     double expectedResult)
 {
     double result = 0.0;
     for (int i = 0; i < xarr.Length; i++)
     {
         result += acc.Accumulate(xarr[i], yarr[i]);
     }
     Assert.AreEqual(expectedResult, result, 0.0);
 }
 /// <summary>
 /// Estimate and set all distribution parameters based on a sample set.
 /// </summary>
 /// <param name="samples">Samples of this distribution.</param>
 public void EstimateDistributionParameters(IEnumerable<double> samples)
 {
     Accumulator accumulator = new Accumulator(samples);
     SetDistributionParameters(accumulator.Mean, accumulator.Sigma);
 }
Beispiel #52
0
 internal void Execute(IEnumerable<Row> iter)
 {
     foreach (var row in iter)
     {
         accumulator = accumulator + 1;
     }
 }
Beispiel #53
0
        static void Main(string[] args)
        {
            // Project Euler Problem 280 Ant and Seeds
            // Author:  D.
            // Date: 11/26/2014
            //
            // https://projecteuler.net/problem=280
            // Ant and seeds
            // Problem 280:
            // "A laborious ant walks randomly on a 5x5 grid. The walk starts from the central square.
            //  At each step, the ant moves to an adjacent square at random, without leaving the grid; thus there
            //  are 2, 3 or 4 possible moves at each step depending on the ant's position.
            //  At the start of the walk, a seed is placed on each square of the lower row. When the ant
            //  isn't carrying a seed and reaches a square of the lower row containing a seed, it
            //  will start to carry the seed. The ant will drop the seed on the first empty square of
            //  the upper row it eventually reaches.
            //  What's the expected number of steps until all seeds have been dropped in the top row?
            //  Give your answer rounded to 6 decimal places."

            // Windows .NET console application in C#.
            // Created with Windows 10, .NET framework 4.6, and Visual Studio Community Edition 2015

            // Solution - Brute force approach:  run a set of simulations keeping track of number
            // of moves required to move all the seeds to their final position.
            // When all the simulations have been run, find the average number of moves
            // and display on screen.

            // Assumptions or inferences from the problem statement:
            // "Ant can only move to adjacent square" - must mean no diagonal moves.
            // Ant can only carry one seed at a time.
            // Ant may only drop seed in top row.
            // Ant can move to cell containing a seed, even if it already has a seed.
            // The grid has 'walls' - the ant never tries to move to a cell outside the grid.

            // This was an exercise in C# development.
            // Solution was not checked against official number on Project Euler site.

            Console.WriteLine("Project Euler Problem 280: Ant and Seeds");

            const int numRows = 5; //num rows in the grid
            const int numCols = 5; //num cols in the grid

            //create an array to hold the count of moves from each simulation run.  Array size = number of simulations to run.
            const double nbrSimulationsToRun = 1000;
            double nbrMoves;

            // create the ant and place it in the grid on which the ant moves in the simulations
            AntGrid antGrid = new AntGrid(numRows, numCols);

            Accumulator sumOfMoves = new Accumulator();

            for (int i = 0; i < nbrSimulationsToRun; i++)
            {
                // initialize and center the ant on the grid
                antGrid.InitializeGrid();
                //antGrid.DisplayGrid(numRows, numCols, grid, ant);

                // run a simulation
                nbrMoves = antGrid.RunSimulation();
                sumOfMoves.AddDataValue(nbrMoves);
            };

            Console.WriteLine("The average number of moves in {0} simulations was:  {1:f6}", nbrSimulationsToRun, sumOfMoves.Mean());

            //antGrid.DisplayGrid(numRows, numCols, grid, ant);

            // keep console window open until user is ready to close out.
            Console.WriteLine("Complete.  Press any key to exit.");
            Console.ReadKey();
        }
        private IAccumulator Product(IAccumulator other)
        {
            var product = new Accumulator(Columns, BoundVariables.Union(other.BoundVariables));
            /*
            IEnumerable<ulong[]> outerEnumerator, innerEnumerator;
            if (this.HighestBoundColumnIndex < other.HighestBoundColumnIndex)
            {
                outerEnumerator = this.Rows;
                innerEnumerator = other.Rows;
            }
            else
            {
                // This accumulator needs to be inner, so if it is a virtual one we need to materialize it first
                if (this is VirtualizingAccumulator)
                {
                    return (this as VirtualizingAccumulator).Materialize().Product(other);
                }
                outerEnumerator = other.Rows;
                innerEnumerator = this.Rows;
            }
            foreach(var outer in outerEnumerator)
            {
                foreach(var inner in innerEnumerator)
                {
                    product.AddRow(RowJoin(outer, inner));
                }
            }
             */

            IEnumerable<ulong[]> outerEnumerator = this.Rows;
            IEnumerable<ulong[]> innerEnumerator = other.Rows;
            foreach(var outer in outerEnumerator)
            {
                foreach(var inner in innerEnumerator)
                {
                    product.AddRow(RowJoin(outer, inner));
                }
            }

            // Update the sort order for the product
            product.SortOrder = this.SortOrder;
            foreach(var sortCol in other.SortOrder)
            {
                if(!product.SortOrder.Contains(sortCol)) product.SortOrder.Add(sortCol);
            }

            return product;
        }
Beispiel #55
0
 internal ForeachRowHelper(Accumulator<int> accumulator)
 {
     this.accumulator = accumulator;
 }
        private static IAccumulator JoinSorted(IAccumulator outer, IAccumulator inner)
        {
            var output = new Accumulator(outer, inner);
            IEnumerator<ulong[]> outerEnumerator = outer.Rows.GetEnumerator();
            if (inner is VirtualizingAccumulator) inner = (inner as VirtualizingAccumulator).Materialize();
            var innerAcc = inner as Accumulator;
            RewindableListEnumerator<ulong[]> innerEnumerator = innerAcc.RewindableEnumerator;
            //IEnumerator<ulong[]> innerEnumerator = inner.Rows.GetEnumerator();

            bool keepGoing = outerEnumerator.MoveNext() && innerEnumerator.MoveNext();
            while (keepGoing)
            {
                while (keepGoing && RowMatch(outerEnumerator.Current, innerEnumerator.Current))
                {
                    output.AddRow(RowJoin(outerEnumerator.Current, innerEnumerator.Current));
                    innerEnumerator.SetMark();
                    bool innerKeepGoing = innerEnumerator.MoveNext();
                    while (innerKeepGoing && RowMatch(outerEnumerator.Current, innerEnumerator.Current))
                    {
                        output.AddRow(RowJoin(outerEnumerator.Current, innerEnumerator.Current));
                        innerKeepGoing = innerEnumerator.MoveNext();
                    }
                    innerEnumerator.RewindToMark();
                    keepGoing = outerEnumerator.MoveNext();
                }
                if (keepGoing)
                {
                    var cmp = RowCompare(outerEnumerator.Current, innerEnumerator.Current);
                    while (cmp != 0 && keepGoing)
                    {
                        keepGoing = cmp > 0 ? innerEnumerator.MoveNext() : outerEnumerator.MoveNext();
                        if (keepGoing) cmp = RowCompare(outerEnumerator.Current, innerEnumerator.Current);
                    }
                }
                if (!keepGoing)
                {
                    keepGoing = outerEnumerator.MoveNext();
                    if (keepGoing)
                    {
                        innerEnumerator.Reset();
                        keepGoing &= innerEnumerator.MoveNext();
                    }
                }
                /*
                while (keepGoing && RowCompare(outerEnumerator.Current, innerEnumerator.Current) < 0)
                    keepGoing = outerEnumerator.MoveNext();
                while (keepGoing && RowCompare(outerEnumerator.Current, innerEnumerator.Current) > 0)
                    keepGoing = innerEnumerator.MoveNext();
                     */
            }
            return output;
        }
 public void Start()
 {
    _accumulator = new Accumulator<ContextElement>( TimeSpan.FromSeconds( 5 ) );
    _accumulator.Accumulated += Accumulator_Accumulated;
    _publishSubscriberEndpoint = ConfigurationManager.AppSettings.Get( "ngsi:PublishSubscriberEndpoint" );
 }
Beispiel #58
0
 internal void Execute(Row row)
 {
     accumulator = accumulator + 1;
 }
Beispiel #59
0
 internal PartitionCountHelper(Accumulator<int> accumulator)
 {
     this.accumulator = accumulator;
 }
Beispiel #60
0
 internal void Execute(IEnumerable<Row> iter)
 {
     // Count only once for a partition iter
     accumulator = accumulator + 1;
     int i = 0;
     foreach (var row in iter)
     {
         i++;
     }
 }