Esempio n. 1
0
 public ChunkTable(GameSave gameSave, Tuple<int, int, Chunk>[] chunks)
     : this(gameSave,
         chunks.Select(x => x.Item1).ToArray(),
         chunks.Select(x => x.Item2).ToArray(),
         chunks.Select(x => x.Item3).ToArray())
 {
 }
Esempio n. 2
0
        /// <summary>
        /// Creates a single <see cref="SVR_AnimeGroup"/> for each <see cref="SVR_AnimeSeries"/> in <paramref name="seriesList"/>.
        /// </summary>
        /// <remarks>
        /// This method assumes that there are no active transactions on the specified <paramref name="session"/>.
        /// </remarks>
        /// <param name="session">The NHibernate session.</param>
        /// <param name="seriesList">The list of <see cref="SVR_AnimeSeries"/> to create groups for.</param>
        /// <returns>A sequence of the created <see cref="SVR_AnimeGroup"/>s.</returns>
        private IEnumerable <SVR_AnimeGroup> CreateGroupPerSeries(ISessionWrapper session,
                                                                  IReadOnlyList <SVR_AnimeSeries> seriesList)
        {
            _log.Info("Generating AnimeGroups for {0} AnimeSeries", seriesList.Count);

            DateTime now = DateTime.Now;
            var      newGroupsToSeries = new Tuple <SVR_AnimeGroup, SVR_AnimeSeries> [seriesList.Count];

            // Create one group per series
            for (int grp = 0; grp < seriesList.Count; grp++)
            {
                SVR_AnimeGroup  group  = new SVR_AnimeGroup();
                SVR_AnimeSeries series = seriesList[grp];

                @group.Populate(series, now);
                newGroupsToSeries[grp] = new Tuple <SVR_AnimeGroup, SVR_AnimeSeries>(group, series);
            }

            using (ITransaction trans = session.BeginTransaction())
            {
                _animeGroupRepo.InsertBatch(session, newGroupsToSeries.Select(gts => gts.Item1).AsReadOnlyCollection());
                trans.Commit();
            }

            // Anime groups should have IDs now they've been inserted. Now assign the group ID's to their respective series
            // (The caller of this method will be responsible for saving the AnimeSeries)
            foreach (Tuple <SVR_AnimeGroup, SVR_AnimeSeries> groupAndSeries in newGroupsToSeries)
            {
                groupAndSeries.Item2.AnimeGroupID = groupAndSeries.Item1.AnimeGroupID;
            }

            _log.Info("Generated {0} AnimeGroups", newGroupsToSeries.Length);

            return(newGroupsToSeries.Select(gts => gts.Item1));
        }
Esempio n. 3
0
 public MultipleTimeSeries(Tuple<TimeSeriesLink, TimeSeries>[] src,bool includeValues = true)
 {
     if(includeValues)
         TimeSeries = src.Select(item => new SlimTimeSeries(item.Item1,item.Item2)).ToArray();
     else
         TimeSeries = src.Select(item => new TimeSeriesFullSummary(item.Item1, item.Item2)).ToArray();
 }
Esempio n. 4
0
 public LogItem[][] GetItems(Tuple<CriteriaType, DateTime, int, bool>[] parameters)
 {
     using (var connection = _connectionFactory.Create())
     {
         return parameters.Select(p => _repository.GetItems(connection, p.Item1, p.Item2, p.Item3, p.Item4)).ToArray();
     }
 }
        public PerformanceAggregate RegisterManyAccounts(int countAccounts, string accounLoginPrefix, bool useParallel)
        {
            if (useParallel)
            {
                return(DoParallelTasks(0, countAccounts, ParallelismFactor, async i1 => await RegisterAccount(string.Format("{0}{1}", accounLoginPrefix, i1)), counter =>
                {
                    if (counter % ParallelismFactor == 0)
                    {
                        Console.WriteLine("Registered {0} accounts", counter);
                    }
                }).Item1);

                var res = new Tuple <PerformanceCounter, object> [countAccounts];
                var sw  = new Stopwatch();
                sw.Start();
                Parallel.For(0, countAccounts,
                             async i1 => res[i1] = await RegisterAccount(string.Format("{0}{1}", accounLoginPrefix, i1)));
                var p = new PerformanceAggregate()
                {
                    PerformanceCounters = res.Select(_ => _.Item1).ToArray(),
                    TotalElapsed        = sw.Elapsed
                };
                return(p);
            }
            else
            {
                return(DoSequenceTask(0, countAccounts,
                                      i1 => RegisterAccount(string.Format("{0}{1}", accounLoginPrefix, i1)), i => {
                    if (i % ParallelismFactor == 0)
                    {
                        Console.WriteLine("Registered {0} accounts", i);
                    }
                }).Item1);
            }
        }
Esempio n. 6
0
 public static string AsString(Tuple<string, object>[] keyValues)
 {
     return keyValues.Count() == 1
         ? keyValues.First().Item2 as string
         : keyValues.Select(k => string.Format("{0}='{1}'", k.Item1, k.Item2))
             .Aggregate((c, n) => c + "," + n);
 }
Esempio n. 7
0
        public void GetEnumerator_Validate()
        {
            var items = new Tuple <string, Type, bool> []
            {
                Tuple.Create("Axis1", typeof(string), true),
                Tuple.Create("Axis2", typeof(double), true),
                Tuple.Create("Axis3", typeof(float), true),
            };

            var axisSet = new AxisSet(items.Select(tuple => new Axis(tuple.Item1, tuple.Item2, tuple.Item3)).ToArray());

            var enumerator1 = items.GetEnumerator();
            var enumerator2 = axisSet.GetEnumerator();

            while (enumerator1.MoveNext())
            {
                Assert.IsTrue(enumerator2.MoveNext());

                var current = (Tuple <string, Type, bool>)enumerator1.Current;

                Assert.AreEqual(current.Item1, enumerator2.Current.Name);
                Assert.AreEqual(current.Item2, enumerator2.Current.DataType);
                Assert.AreEqual(current.Item3, enumerator2.Current.AllowTotals);
            }

            Assert.IsFalse(enumerator2.MoveNext());
        }
Esempio n. 8
0
    static void Main(string[] args)
    {
        string[] inputs;
        inputs = Console.ReadLine().Split(' ');
        int nbFloors              = int.Parse(inputs[0]); // number of floors
        int width                 = int.Parse(inputs[1]); // width of the area
        int nbRounds              = int.Parse(inputs[2]); // maximum number of rounds
        int exitFloor             = int.Parse(inputs[3]); // floor on which the exit is found
        int exitPos               = int.Parse(inputs[4]); // position of the exit on its floor
        int nbTotalClones         = int.Parse(inputs[5]); // number of generated clones
        int nbAdditionalElevators = int.Parse(inputs[6]); // ignore (always zero)
        int nbElevators           = int.Parse(inputs[7]); // number of elevators

        Tuple <int, int>[] elevators = new Tuple <int, int> [nbElevators];
        for (int i = 0; i < nbElevators; i++)
        {
            inputs = Console.ReadLine().Split(' ');
            int elevatorFloor = int.Parse(inputs[0]); // floor on which this elevator is found
            int elevatorPos   = int.Parse(inputs[1]); // position of the elevator on its floor
            elevators[i] = Tuple.Create(elevatorFloor, elevatorPos);
        }

        // game loop
        while (true)
        {
            inputs = Console.ReadLine().Split(' ');
            int    cloneFloor = int.Parse(inputs[0]); // floor of the leading clone
            int    clonePos   = int.Parse(inputs[1]); // position of the leading clone on its floor
            string direction  = inputs[2];            // direction of the leading clone: LEFT or RIGHT

            // Write an action using Console.WriteLine()
            // To debug: Console.Error.WriteLine("Debug messages...");
            bool block = false;
            if (cloneFloor == -1 || clonePos == -1 || direction == "NONE")
            {
            }
            else if (cloneFloor == exitFloor)
            {
                if (((clonePos > exitPos) && direction == "RIGHT") ||
                    ((clonePos < exitPos) && direction == "LEFT"))
                {
                    block = true;
                }
            }
            else
            {
                int idxElevator = elevators.Select((val, idx) => new { Val = val, Idx = idx })
                                  .First(elem => elem.Val.Item1 == cloneFloor)
                                  .Idx;
                int elevatorPos = elevators[idxElevator].Item2;
                if (((clonePos > elevatorPos) && direction == "RIGHT") ||
                    ((clonePos < elevatorPos) && direction == "LEFT"))
                {
                    block = true;
                }
            }

            Console.WriteLine(block ? "BLOCK" : "WAIT"); // action: WAIT or BLOCK
        }
    }
        public PropertyChoicesFacetViaMethod(MethodInfo optionsMethod, IFacetHolder holder)
            : base(holder) {
            method = optionsMethod;

            parameterNamesAndTypes = optionsMethod.GetParameters().Select(p => new Tuple<string, INakedObjectSpecification>(p.Name.ToLower(), NakedObjectsContext.Reflector.LoadSpecification(p.ParameterType))).ToArray();
            parameterNames = parameterNamesAndTypes.Select(pnt => pnt.Item1).ToArray();
        }
 public ItemsWithConflictingHighestScoreException(Tuple<IValueProvider, IProbe>[] itemsWithConflictingScore, int highestScore)
     : base(string.Format(
         "items: {0} with conflicting highest score of {1} exists, cannot determine default", string.Concat(itemsWithConflictingScore.Select(x=>x.Item1.ToString())), highestScore))
 {
     ItemsWithConflictingScore = itemsWithConflictingScore;
     HighestScore = highestScore;
 }
Esempio n. 11
0
        private RecipeInference.SuggestedRecipe.SuggestedLearner[] GetTopLearners(IEnumerable <PipelinePattern> history)
        {
            var weights    = LearnerHistoryToWeights(history.ToArray(), IsMaximizingMetric);
            var topKTuples = new Tuple <double, int> [_topK];

            for (int i = 0; i < weights.Length; i++)
            {
                if (i < _topK)
                {
                    topKTuples[i] = new Tuple <double, int>(weights[i], i);
                }
                else
                {
                    for (int j = 0; j < topKTuples.Length; j++)
                    {
                        if (weights[i] > topKTuples[j].Item1)
                        {
                            topKTuples[j] = new Tuple <double, int>(weights[i], i);
                        }
                    }
                }
            }

            return(topKTuples.Select(t => AvailableLearners[t.Item2]).ToArray());
        }
Esempio n. 12
0
        /// <summary>
        /// Returns a string which is what it's expected to be output by debuggers.
        /// </summary>
        public string ToDebugPrintString()
        {
            if (this.m_Object != null && this.m_Object is RefIdObject)
            {
                RefIdObject refid = (RefIdObject)m_Object;

                string typeString = this.Type.ToLuaTypeString();

                if (m_Object is IUserData)
                {
                    IUserData ud  = (IUserData)m_Object;
                    string    str = ud.AsString();
                    if (str != null)
                    {
                        return(str);
                    }
                }
                return(refid.FormatTypeString(typeString));
            }

            switch (Type)
            {
            case DataType.Tuple:
                return(string.Join("\t", Tuple.Select(t => t.ToPrintString()).ToArray()));

            case DataType.TailCallRequest:
                return("(TailCallRequest)");

            case DataType.YieldRequest:
                return("(YieldRequest)");

            default:
                return(ToString());
            }
        }
Esempio n. 13
0
        public void Rank_CoordinatesNullPartialTermMatch_ReturnsExpectedCertainty()
        {
            //vverify that in the case of only partial matches, results are still offset/normalized to 100%
            var entries = new Tuple <GeoDataEntry, double>[]
            {
                new Tuple <GeoDataEntry, double>(new GeoDataEntry()
                {
                    Name = "Test"
                }, 1.0),                                                                  //full match
                new Tuple <GeoDataEntry, double>(new GeoDataEntry()
                {
                    Name = "Test 2 "
                }, .67),                                                                     //whitespaces should be trimmed
                new Tuple <GeoDataEntry, double>(new GeoDataEntry()
                {
                    Name = "Test 3 xx"
                }, .44),
                new Tuple <GeoDataEntry, double>(new GeoDataEntry()
                {
                    Name = "Something"
                }, 0)                                                                       //doesn't start with searchTerm
            };


            foreach (RankingResult result in Target.Rank(entries.Select(e => e.Item1), "te", null))
            {
                Assert.AreEqual(Rounder.Round(entries.Where(e => e.Item1.Equals(result.Entry)).Single().Item2), result.Certainty);
            }
        }
Esempio n. 14
0
        static string encodeTransposition(string message, string keyword)
        {
            string encyptedMessage = "";

            message = message.Replace(" ", "");

            int colLength = keyword.Length;

            string[] cols      = new string[colLength];
            string[] colsFinal = new string[colLength];

            //add padding to message
            int paddingLength = colLength - (message.Length % colLength);

            if (paddingLength < colLength)
            {
                for (int i = 0; i < paddingLength; i++)
                {
                    message += "X";
                }
            }

            for (int i = 0; i < message.Length; i++)
            {
                int j = i % colLength;
                cols[j] += message[i];
            }

            //find ordering of keyword
            Tuple <string, int>[] keywordOrder = new Tuple <string, int> [colLength];

            for (int i = 0; i < colLength; i++)
            {
                keywordOrder[i] = new Tuple <string, int>(keyword[i].ToString(), i);
            }

            List <Tuple <string, int> > sorted = keywordOrder
                                                 .Select((x, i) => new Tuple <string, int>(x.Item1, i))
                                                 .OrderBy(x => x.Item1)
                                                 .ToList();

            List <int> sortedIndex = sorted.Select(x => x.Item2).ToList();

            //reorder cols to ordering of keyword
            for (int i = 0; i < colLength; i++)
            {
                colsFinal[i] = cols[sortedIndex[i]];
            }

            encyptedMessage = String.Join("", colsFinal.ToArray());

            int groupCount = 5;

            for (int i = encyptedMessage.Length / groupCount; i >= 0; i--)
            {
                encyptedMessage = encyptedMessage.Insert(i * groupCount, " ");
            }

            return(encyptedMessage);
        }
Esempio n. 15
0
        public void Rank_CoordinatesNullPerfectTermMatch_ReturnsExpectedCertainty()
        {
            //verify that whitespaces are trimmed and certainty is calculated accurately
            //entries contains a Name that matches searchTerm exactly, so max(Certainty) for matching term should == 100%
            var entries = new Tuple <GeoDataEntry, double>[]
            {
                new Tuple <GeoDataEntry, double>(new GeoDataEntry()
                {
                    Name = "Test"
                }, 1.0),                                                                  //full match
                new Tuple <GeoDataEntry, double>(new GeoDataEntry()
                {
                    Name = "Test 2 "
                }, .6666),                                                                     //whitespaces should be trimmed
                new Tuple <GeoDataEntry, double>(new GeoDataEntry()
                {
                    Name = "Test 3 xx"
                }, .4444),
                new Tuple <GeoDataEntry, double>(new GeoDataEntry()
                {
                    Name = "Something"
                }, 0)                                                                       //doesn't start with searchTerm
            };


            foreach (RankingResult result in Target.Rank(entries.Select(e => e.Item1), "test", null))
            {
                Assert.AreEqual(Rounder.Round(entries.Where(e => e.Item1.Equals(result.Entry)).Single().Item2), result.Certainty);
            }
        }
Esempio n. 16
0
        public void InsertData_WhenCalled_InsertsData()
        {
            var table = new DataTable();

            table.Columns.Add("boolColumn", typeof(bool));
            table.Columns.Add("dateColumn", typeof(DateTime));
            table.Columns.Add("longColumn", typeof(long));
            table.Columns.Add("textColumn", typeof(string));
            table.Columns.Add("noTypeColumn");

            var row = table.NewRow();

            row[0] = true;
            row[1] = DateTime.Now;
            row[2] = long.MaxValue;
            row[3] = "string";
            row[4] = "";

            var parameters = new Tuple <string, object>[] {
                new Tuple <string, object>("param0", true),
                new Tuple <string, object>("param1", DateTime.Now),
                new Tuple <string, object>("param2", long.MaxValue),
                new Tuple <string, object>("param3", "string"),
                new Tuple <string, object>("param4", "")
            };
            var query = $"INSERT INTO table([boolColumn], [dateColumn], [longColumn], [textColumn], [noTypeColumn]) " +
                        $"VALUES ({string.Join(", ", parameters.Select(p => p.Item1))})";

            dbBuilder.InsertData(row);

            sqliteService.Verify(x =>
                                 x.ExecuteQuery(query, null, It.IsAny <IEnumerable <Tuple <string, object> > >()));
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            var   results   = new Tuple <float, float> [512];
            var   sw        = new Stopwatch();
            int   hypotesis = 0;
            float supp      = 0;
            float min       = 1;
            float max       = 0;

            sw.Start();
            for (var i = 0; i < 512; ++i)
            {
                var res  = Test(i, 20, QRLevel.Low);
                var cond = res.Item1 > res.Item2 == ((i >> 4) % 2 == 1);
                Console.WriteLine("{0}: {1} {2} * {3}", i, res.Item1, res.Item2, cond);
                hypotesis += cond ? 1 : 0;
                supp      += res.Item1 + res.Item2;
                if (Math.Max(res.Item1, res.Item2) < min)
                {
                    min = Math.Max(res.Item1, res.Item2);
                }
                if (Math.Min(res.Item1, res.Item2) < max)
                {
                    max = Math.Min(res.Item1, res.Item2);
                }
                results[i] = res;
            }
            sw.Stop();
            System.IO.File.WriteAllLines("readability.txt",
                                         results.Select(t => String.Format("{0} {1}", t.Item1, t.Item2))
                                         );
            Console.WriteLine("Hypotesis: {0} (support = {1})", (float)hypotesis / 512, (float)supp / 512);
            Console.WriteLine("  min = {0}; max = {1}", min, max);
            Console.WriteLine("Time elapsed: {0}s", sw.Elapsed.TotalSeconds);
        }
Esempio n. 18
0
        public void MoveActionTest()
        {
            var testCases = new Tuple <Point, Orientation, Point>[]
            {
                Tuple.Create(new Point(2, 2), Orientation.North, new Point(2, 3)),
                Tuple.Create(new Point(2, 2), Orientation.East, new Point(3, 2)),
                Tuple.Create(new Point(2, 2), Orientation.South, new Point(2, 1)),
                Tuple.Create(new Point(2, 2), Orientation.West, new Point(1, 2)),
            };

            var move = RoverActionPool.GetAction('M');

            Func <Point, Orientation, Point> doMove = (p, o) =>
            {
                var rover = new Rover(null, p, o);
                move.ApplyTo(rover);
                return(rover.Position);
            };


            var result = testCases.Select
                         (
                (c) => Tuple.Create
                (
                    c.Item3,
                    doMove(c.Item1, c.Item2)
                )
                         );

            result.ValidateEquality();
        }
Esempio n. 19
0
 public TableRenderer(string title, Tuple<string, int>[] headers)
 {
     _title = title;
     _headers = headers;
     _totalWidth = _headers.Sum(h => h.Item2) + (_headers.Count() - 1) * 3;
     _rowTemplate = "| " + String.Join(" | ", _headers.Select((h, i) => "{" + i + ",-" + h.Item2 + "}").ToArray()) + " |";
 }
 public void Show(string trainerMatchcode, Tuple<string,string>[] trainings, string error)
 {
     dynamic vm = new ExpandoObject();
     vm.TrainerMatchcode = trainerMatchcode;
     vm.Trainings = trainings.Select(tr => new {Id = tr.Item1, Matchcode = tr.Item2}).ToArray();
     vm.Error = error;
     _portal.SharedResponse = _portal.View["Trainingsuebersicht.Main.html", vm];
 }
Esempio n. 21
0
 public object?[]? InitPreambles(IDataContext dc)
 {
     if (_preambles == null)
     {
         return(null);
     }
     return(_preambles.Select(p => p.Item1(dc)).ToArray());
 }
 public ActionChoicesFacetViaMethod(MethodInfo choicesMethod, Type choicesType, IFacetHolder holder, bool isMultiple = false)
     : base(holder) {
     this.choicesMethod = choicesMethod;
     this.choicesType = choicesType;
     this.isMultiple = isMultiple;
     parameterNamesAndTypes = choicesMethod.GetParameters().Select(p => new Tuple<string, INakedObjectSpecification>(p.Name.ToLower(), NakedObjectsContext.Reflector.LoadSpecification(p.ParameterType))).ToArray();
     parameterNames = parameterNamesAndTypes.Select(pnt => pnt.Item1).ToArray();
 }
        public PropertyChoicesFacetx(MethodInfo optionsMethod, Tuple<string, IObjectSpecImmutable>[] parameterNamesAndTypes, ISpecification holder)
            : base(typeof (IPropertyChoicesFacet), holder) {
            method = optionsMethod;

            this.parameterNamesAndTypes = parameterNamesAndTypes;
            parameterNames = parameterNamesAndTypes.Select(pnt => pnt.Item1).ToArray();
            methodDelegate = DelegateUtils.CreateDelegate(method);
        }
Esempio n. 24
0
        public static void Main(string[] args)
        {
            var options = Options.GetOptions(args);

            if (args.Length == 0 || options.Help)
            {
                Console.WriteLine("Usage:");
                Console.WriteLine(Options.GetHelp());
                return;
            }
            RelaEngine.Mode = EngineMode.Test;
            Func <string, IRelaExample, Tuple <string, IRelaExample> > c = (s, i) => Tuple.Create <string, IRelaExample>(s, i);
            var examples = new Tuple <string, IRelaExample>[] { c("SimpleAcquireRelease", new SimpleAcquireRelease()),
                                                                c("StoreLoad", new StoreLoad()),
                                                                c("SPSC", new BoundedSPSCQueue()),
                                                                c("Petersen", new Petersen()),
                                                                c("TotalOrder", new TotalOrder()),
                                                                c("TransitiveLastSeen", new TransitiveLastSeen()),
                                                                c("SimpleTransitive", new SimpleTransitive()),
                                                                c("RelaxedModOrder", new RelaxedModificationOrder()),
                                                                c("LiveLock", new LiveLock()),
                                                                c("Treiber", new TreiberStack()),
                                                                c("MichaelScott", new MichaelScottQueue()),
                                                                c("Deadlock", new Deadlock()),
                                                                c("LostWakeUp", new LostWakeUp()),
                                                                c("CorrectLeftRight", new LeftRight()),
                                                                c("BuggyLeftRight", new IncorrectLeftRight()),
                                                                c("StarvationLeftRight", new StarvationLeftRight()),
                                                                c("MultiWriterCOWList", new COWList()),
                                                                c("SimpleReadIndicator", new SingleCounterReadIndicator()),
                                                                c("DCLReadIndicator", new DCLReadIndicator()),
                                                                c("AsymmetricPetersen", new AsymmetricPetersen()),
                                                                c("AsymmetricLock", new AsymmetricLock()),
                                                                c("SafeAsymmetricLock", new SafeAsymmetricLock()),
                                                                c("MinimalIPI", new MinimalIPI()),
                                                                c("IPIReadWriteLock", new IPIReadWriteLock()) };

            if (options.ListExamples)
            {
                Console.WriteLine("Available examples:");
                Console.WriteLine("-------------------");
                Console.WriteLine(String.Join("\n", examples.Select(e => $"{e.Item1}\r\t\t\t{e.Item2.Name}")));
                return;
            }
            for (int i = 0; i < examples.Length; ++i)
            {
                var tag     = examples[i].Item1;
                var example = examples[i].Item2;
                if (options.TestTag == null || Regex.Match(tag, options.TestTag, RegexOptions.IgnoreCase) != Match.Empty)
                {
                    if (!options.SelfTest)
                    {
                        Console.WriteLine($"Running example [{i + 1}/{examples.Length}]: {tag}: {example.Name}");
                    }
                    RunExample(tag, example, options);
                }
            }
        }
 // aggregate all the basket consitituents data
 public DatedDataCollectionGen<double> AggregateBasketCollections(Tuple<CustomBasket, DatedDataCollectionGen<double>>[] basketsWithData)
 {
     var results = basketsWithData.Select(basketData =>
     {
         var rolledSeries = RollOverBasket(basketData);
         return rolledSeries.MultiplyBy(basketData.Item1.Weight);
     });
     return results.Add();            
 }
 public ActionChoicesFacetViaMethod(MethodInfo choicesMethod, Tuple<string, IObjectSpecImmutable>[] parameterNamesAndTypes, Type choicesType, ISpecification holder, bool isMultiple = false)
     : base(holder) {
     this.choicesMethod = choicesMethod;
     this.choicesType = choicesType;
     IsMultiple = isMultiple;
     ParameterNamesAndTypes = parameterNamesAndTypes;
     parameterNames = parameterNamesAndTypes.Select(pnt => pnt.Item1).ToArray();
     choicesDelegate = DelegateUtils.CreateDelegate(choicesMethod);
 }
Esempio n. 27
0
 public void AwardMarks(int awarderId, Tuple<int, int>[] guessMarks)
 {
     var player = new Player(awarderId);
     var marks =
         guessMarks.Select(
             gm =>
             Tuple.Create(this.repository.Query<IGuessDTO>(g => g.Id == gm.Item1).FirstOrDefault(), gm.Item2)).ToArray();
     player.AwardMarks(marks);
 }
        public void Process(MeasurementType measurement)
        {
            var values = this.Values.ToList();

            values.Sort();

            int steps = 100;

            Tuple <double, int>[] density = new Tuple <double, int> [steps];
            double span = values.Max() / steps;

            for (int i = 0; i < steps; i++)
            {
                double center = span * i;
                int    count  = values.Count(x => Math.Abs(x - center) < span);
                density[i] = Tuple.Create(center, count);
            }

            // Now we'll sweep through the density curve, finding places where the curve jumps from below 50% to above 50%, then
            // back down to below 50%.
            var    peaks      = new List <double>();
            bool   isAbove    = false;
            double risingEdge = Double.NaN;
            int    thresh     = density.Select(x => x.Item2).Max() / 2;

            for (int i = 0; i < density.Length; i++)
            {
                int count = density[i].Item2;

                if (!isAbove && count > thresh)
                {
                    risingEdge = density[i].Item1;
                    isAbove    = true;
                }

                if (isAbove && count < thresh)
                {
                    var fallingEdge = density[i].Item1;
                    peaks.Add((risingEdge + fallingEdge) / 2.0);
                    isAbove = false;
                }
            }

            if (isAbove)
            {
                peaks.Add(risingEdge);
            }

            var sortedPeaks = peaks.OrderByDescending(x => x).Select(x => ResolvePeak(x, span * 2)).ToList();

            this.Mode1 = sortedPeaks[0];
            this.Mode2 = sortedPeaks[1];
            this.Mode3 = sortedPeaks[2];
        }
Esempio n. 29
0
        public void Setup()
        {
            queryable = new List<SomeModel>()
            {
                new SomeModel()
                {
                    Category = 1,
                    DisplayName = "Cheddar",
                    Id = 123,
                    Scale = 123.456d,
                    Discounted = true
                }
            }.AsQueryable();

            dataTablesParam = new DataTablesParam();
            columns = TypeExtensions.GetSortedProperties<SomeModel>().Select((p, i) =>
                Tuple.Create(i, new ColInfo(p.Name, p.PropertyType))).ToArray();
            dataTablesParam.sSearchColumns = new List<string>(columns.Select(c => null as string));
            dataTablesParam.bSearchable = new List<bool>(columns.Select(c => true));

        }
Esempio n. 30
0
        static int[] GetHandValue(Tuple<int, string>[] hand)
        {
            Predicate<Tuple<int, string>[]> isFlush = c => c.Select(f => f.Item2).Distinct().Count() == 1;
            List<int> handRanks = hand.Select(c => c.Item1).OrderByDescending(c => c).ToList();
            int straightValue = IsStraight(handRanks);

            if (isFlush(hand) && straightValue != -1)
                return new int[] { 10, straightValue };

            List<int> kind4 = HasSets(handRanks, new int[] { 4, 1 });
            if (kind4 != null)
            {
                kind4.Insert(0, 9);
                return kind4.ToArray();
            }

            List<int> kind32 = HasSets(handRanks, new int[] { 3, 2 });
            if (kind32 != null)
            {
                kind32.Insert(0, 8);
                return kind32.ToArray();
            }

            if (isFlush(hand))
                return new int[] { 7, handRanks.Max() };

            if (straightValue != -1)
                return new int[] { 6, straightValue };

            List<int> kind311 = HasSets(handRanks, new int[] { 3, 1, 1 });
            if (kind311 != null)
            {
                kind311.Insert(0, 5);
                return kind311.ToArray();
            }

            List<int> kind221 = HasSets(handRanks, new int[] { 2, 2, 1 });
            if (kind221 != null)
            {
                kind221.Insert(0, 4);
                return kind221.ToArray();
            }

            List<int> kind2111 = HasSets(handRanks, new int[] { 2, 1, 1, 1 });
            if (kind2111 != null)
            {
                kind2111.Insert(0, 3);
                return kind2111.ToArray();
            }

            handRanks.Insert(0, 0);
            return handRanks.ToArray();
        }
        public override byte[] Split(byte[] secretClear, int shareCount, int threshold)
        {
            // var primeArr = ComputeRandomePrime();
            // var prime = new BigInteger(primeArr);
            var primeMinusOne = _prime - 1;
            var number        = new BigInteger(secretClear);

            var coef = new BigInteger[threshold];

            coef[0] = number;

            // TODO: rewrite this to use cryptographically-secure RNG
            var rng = new Random();
            var pmo = new BigRational(primeMinusOne);

            for (int c = 1; c < threshold; ++c)
            {
                coef[c] = BigRational.Multiply(pmo, new BigRational(rng.NextDouble())).GetWholePart();
            }

            var shares = new Tuple <int, BigInteger> [shareCount];

            for (var x = 1; x <= shareCount; ++x)
            {
                System.Console.WriteLine("X: " + x);
                var accum = coef[0];
                for (int exp = 1; exp < threshold; ++exp)
                {
                    // accum = (accum + (coef[exp] * (Math.pow(x, exp) % prime) % prime)) % prime;
                    var a = new BigInteger(Math.Pow(x, exp)) % _prime; // (Math.pow(x, exp) % prime)
                    var b = (coef[exp] * a) % _prime;                  // (coef[exp] * a % prime)
                    var c = (accum + b) % _prime;                      // (accum + b) % prime;

                    accum = c;
                }

                shares[x - 1] = Tuple.Create(x, accum);
            }

            Shares = shares.Select(x => {
                var index = BitConverter.GetBytes(x.Item1);
                var biarr = x.Item2.ToByteArray();
                var bytes = new byte[INT_ARR_LEN + biarr.Length];
                Array.Copy(index, 0, bytes, 0, INT_ARR_LEN);
                Array.Copy(biarr, 0, bytes, INT_ARR_LEN, biarr.Length);
                return(bytes);
            });

            // The original secret value is fully encoded in the distributed shares so there
            // is no need to return any version of the original secreted in encrypted form
            return(new byte[0]);
        }
Esempio n. 32
0
        public void Solver_Should_Return_Fixed_Cycle_Points()
        {
            //Assert
            double[,] optimalityIndexTable = new double[3, 3]
            {
                { 0, 0, 3 },
                { 4, 0, 0 },
                { 5, -7, 0 }
            };

            var validResult = new Tuple <int, int>[]
            {
                new Tuple <int, int>(1, 1),
                new Tuple <int, int>(1, 2),
                new Tuple <int, int>(2, 1),
                new Tuple <int, int>(2, 2)
            };
            var solverResult = _solver.BuildCycle(optimalityIndexTable);

            Assert.IsTrue(CheckEquals(validResult.Select(i => i.Item1).ToArray(), solverResult.Select(i => i.Item1).ToArray()));
            Assert.IsTrue(CheckEquals(validResult.Select(i => i.Item2).ToArray(), solverResult.Select(i => i.Item2).ToArray()));
        }
        public void Setup()
        {
            queryable = new List<SomeModel>()
            {
                new SomeModel()
                {
                    Category = 1,
                    DisplayName = "Cheddar",
                    Id = 123,
                    Scale = 123.456d,
                    Discounted = true,
                    Cost = 123
                }
            }.AsQueryable();

            dataTablesParam = new DataTablesParam();
            columns = DataTablesTypeInfo<SomeModel>.Properties.Select((p, i) =>
                Tuple.Create(i, new DataTablesPropertyInfo(p.PropertyInfo, new DataTablesAttributeBase[]{}))).ToArray();
            dataTablesParam.sSearchColumns = new List<string>(columns.Select(c => null as string));
            dataTablesParam.bSearchable = new List<bool>(columns.Select(c => true));

        }
Esempio n. 34
0
    public void Bonus_ReturnsExpectedValue()
    {
        //Arrange
        var items = new Tuple <FrameResult, Bonus>[]
        {
            new Tuple <FrameResult, Bonus>(new FrameResult(new int[] { 1, 1 }), Bonus.None),
            new Tuple <FrameResult, Bonus>(new FrameResult(new int[] { 10 }), Bonus.Strike),
            new Tuple <FrameResult, Bonus>(new FrameResult(new int[] { 1, 9 }), Bonus.Spare),
            new Tuple <FrameResult, Bonus>(new FrameResult(new int[] { 10, 1, 1 }), Bonus.Strike),
            new Tuple <FrameResult, Bonus>(new FrameResult(new int[] { 10, 10, 10 }), Bonus.Strike),
            new Tuple <FrameResult, Bonus>(new FrameResult(new int[] { 1, 9, 1 }), Bonus.Spare),
            new Tuple <FrameResult, Bonus>(new FrameResult(new int[] { 1, 10, 1 }), Bonus.Spare),
        }
        .Select(t => new
        {
            FrameResult   = t.Item1,
            ExpectedBonus = t.Item2
        })
        .ToArray();

        //Assert
        CollectionAssert.AreEqual(items.Select(i => i.ExpectedBonus), items.Select(i => i.FrameResult.Bonus));
    }
        public override void Invoke(CancellationToken cancellationToken)
        {
            // Get the range for the current snapshot
            ITextSnapshot snapshot       = _textView.TextSnapshot;
            SnapshotPoint target         = _target.TranslateTo(snapshot, PointTrackingMode.Positive);
            int           startLineIndex = snapshot.GetLineNumberFromPosition(target);
            int           endLineIndex   = startLineIndex;

            // Find first #include of block
            while (startLineIndex > 0 && LineIsInclude(snapshot, startLineIndex - 1))
            {
                startLineIndex--;
            }

            // Find last #include of block
            while (endLineIndex < snapshot.LineCount - 1 && LineIsInclude(snapshot, endLineIndex + 1))
            {
                endLineIndex++;
            }

            // Get includes
            int numIncludeLines = endLineIndex - startLineIndex + 1;
            var lines           = new Tuple <string, string> [numIncludeLines];

            for (int i = startLineIndex; i <= endLineIndex; i++)
            {
                ITextSnapshotLine line        = snapshot.GetLineFromLineNumber(i);
                string            lineText    = line.GetText();
                string            includePath = GetIncludePath(snapshot, lineText);
                lines[i - startLineIndex] = new Tuple <string, string>(lineText, includePath);
            }

            // Sort (use LINQ as its stable)
            lines = lines.OrderBy(x => x.Item2.StartsWith("<") ? 0 : 1)
                    .ThenBy(x => x.Item2)
                    .ToArray();

            // Replace the lines with the new sorted lines
            ITextSnapshotLine startLine   = snapshot.GetLineFromLineNumber(startLineIndex);
            ITextSnapshotLine endLine     = snapshot.GetLineFromLineNumber(endLineIndex);
            string            newLineChar = _textView.Options.GetNewLineCharacter();

            using (ITextEdit edit = _textBuffer.CreateEdit(EditOptions.DefaultMinimalChange, null, null))
            {
                var    replaceSpan = Span.FromBounds(startLine.Start, endLine.End);
                string replaceText = String.Join(newLineChar, lines.Select(x => x.Item1));
                edit.Replace(replaceSpan, replaceText);
                edit.Apply();
            }
        }
Esempio n. 36
0
    public BondStructureOTR(Focus focus_, Tuple<int,BondMarket,double>[] points_)
      : base(points_.GetDescription())
    {
      Points = points_;
      m_focus = focus_;

      foreach (BondMarket mkt in points_.Select(x => x.Item2).Distinct())
      {
        CountryBondSource.GetInstance(mkt).OTRCache.ItemAdded += handleCachedChanged;
        CountryBondSource.GetInstance(mkt).OTRCache.ItemRemoved += handleCachedChanged;
      }

      rebuild();
    }
Esempio n. 37
0
        public void MathOperatorsTest()
        {
            var testCases = new Tuple <Point, Point, Point>[]
            {
                Tuple.Create(new Point(2, 4), Point.Empty, new Point(2, 4)),
                Tuple.Create(new Point(2, 4), new Point(x: 2), new Point(4, 4)),
                Tuple.Create(new Point(2, 4), new Point(y: 2), new Point(2, 6)),
                Tuple.Create(new Point(2, 4), new Point(3, 5), new Point(5, 9)),
                Tuple.Create(new Point(2, 4), new Point(x: -2), new Point(0, 4)),
                Tuple.Create(new Point(2, 4), new Point(y: -2), new Point(2, 2)),
            };

            testCases
            .Select((fo) => Tuple.Create(fo.Item3, fo.Item1 + fo.Item2))
            .ValidateEquality();

            testCases
            .Select((fo) => Tuple.Create(fo.Item1, fo.Item3 - fo.Item2))
            .ValidateEquality();

            var testCases2 = new Tuple <Point, Point>[]
            {
                Tuple.Create(new Point(0, 0), new Point(0, 0)),
                Tuple.Create(new Point(2, 0), new Point(-2, 0)),
                Tuple.Create(new Point(0, 2), new Point(0, -2)),
                Tuple.Create(new Point(6, 9), new Point(-6, -9)),
            };

            testCases2
            .Select((fo) => Tuple.Create(fo.Item1, -fo.Item2))
            .ValidateEquality();

            testCases2
            .Select((fo) => Tuple.Create(fo.Item2, -fo.Item1))
            .ValidateEquality();
        }
Esempio n. 38
0
    public BondStructureCMT(Focus focus_, Tuple<int,BondMarket,double>[] points_)
      : base(points_.GetDescription())
    {
      Points = points_;
      Focus = focus_;

      m_bits =
        Points.Select(x => x.Item2)
          .Distinct()
          .Select(x => CountryBondSource.GetInstance(x).GetSmoothCurveGroupForFocus(Focus).LiveCMT)
          .ToDictionary(x => x.Market, x => x);
      subscribeToFit();
      setPriorValue();

      RecalculateLive();
    }
Esempio n. 39
0
        static Tuple <Vector3, float>[] GenerateColorPrefixSum()
        {
            var colors = new Tuple <Vector3, float>[]
            {
                new Tuple <Vector3, float>(new Vector3(249.0f, 251.0f, 249.0f), 4.0f),
                new Tuple <Vector3, float>(new Vector3(46.0f, 46.0f, 45.0f), 1.0f),
                new Tuple <Vector3, float>(new Vector3(221.0f, 1.0f, 0.0f), 1.0f),
                new Tuple <Vector3, float>(new Vector3(32.0f, 80.0f, 149.0f), 1.0f),
                new Tuple <Vector3, float>(new Vector3(250.0f, 201.0f, 0), 1.0f),
            };

            var prefixSum           = PrefixSum(colors.Select(o => o.Item2)).ToArray();
            var prefixSumNormalized = prefixSum.Select(o => o / prefixSum.Last()).ToArray();

            return(colors.Zip(prefixSumNormalized, (a, b) => new Tuple <Vector3, float>(new Vector3(Mathf.GammaToLinearSpace(a.Item1.x / 255.0f), Mathf.GammaToLinearSpace(a.Item1.y / 255.0f), Mathf.GammaToLinearSpace(a.Item1.z / 255.0f)), b)).ToArray());
        }
Esempio n. 40
0
        public void Enumerator_WhenEnumerated_ReturnsUnderlyingFactObjectsInOrder()
        {
            //Arrange
            var tuple0 = new Tuple(null);
            var tuple1 = new Tuple(tuple0, new Fact(1), null);
            var tuple2 = new Tuple(tuple1, new Fact(2), null);
            var tuple3 = new Tuple(tuple2, new Fact(3), null);

            //Act
            var target = tuple3.Select(f => f.Object).ToArray();

            //Assert
            Assert.AreEqual(3, target.Length);
            Assert.AreEqual(1, target[0]);
            Assert.AreEqual(2, target[1]);
            Assert.AreEqual(3, target[2]);
        }
Esempio n. 41
0
        public void Enumerator_WhenEnumerated_ReturnsUnderlyingFactObjectsInOrder()
        {
            //Arrange
            var tuple0 = new Tuple(null);
            var tuple1 = new Tuple(tuple0, new Fact(1), null);
            var tuple2 = new Tuple(tuple1, new Fact(2), null);
            var tuple3 = new Tuple(tuple2, new Fact(3), null);

            //Act
            var target = tuple3.Select(f => f.Object).ToArray();

            //Assert
            Assert.AreEqual(3, target.Length);
            Assert.AreEqual(1, target[0]);
            Assert.AreEqual(2, target[1]);
            Assert.AreEqual(3, target[2]);
        }
        public void Setup()
        {
            //TODO: this became an integration test - proper ProjectionCoreService and ProjectionManager testing is required as well
            _bus.Subscribe(_consumer);

            _processingQueues = GivenProcessingQueues();
            _manager = new ProjectionManager(
                GetInputQueue(), GetInputQueue(), _processingQueues.Select(v => v.Item1).ToArray(), _timeProvider, RunProjections.All,
                _initializeSystemProjections);

            _bus.Subscribe<ProjectionManagementMessage.Internal.CleanupExpired>(_manager);
            _bus.Subscribe<ProjectionManagementMessage.Internal.Deleted>(_manager);
            _bus.Subscribe<CoreProjectionManagementMessage.Started>(_manager);
            _bus.Subscribe<CoreProjectionManagementMessage.Stopped>(_manager);
            _bus.Subscribe<CoreProjectionManagementMessage.Prepared>(_manager);
            _bus.Subscribe<CoreProjectionManagementMessage.Faulted>(_manager);
            _bus.Subscribe<CoreProjectionManagementMessage.StateReport>(_manager);
            _bus.Subscribe<CoreProjectionManagementMessage.ResultReport>(_manager);
            _bus.Subscribe<CoreProjectionManagementMessage.StatisticsReport>(_manager);
            _bus.Subscribe<CoreProjectionManagementMessage.SlaveProjectionReaderAssigned>(_manager);
            _bus.Subscribe<ProjectionManagementMessage.Post>(_manager);
            _bus.Subscribe<ProjectionManagementMessage.UpdateQuery>(_manager);
            _bus.Subscribe<ProjectionManagementMessage.GetQuery>(_manager);
            _bus.Subscribe<ProjectionManagementMessage.Delete>(_manager);
            _bus.Subscribe<ProjectionManagementMessage.GetStatistics>(_manager);
            _bus.Subscribe<ProjectionManagementMessage.GetState>(_manager);
            _bus.Subscribe<ProjectionManagementMessage.GetResult>(_manager);
            _bus.Subscribe<ProjectionManagementMessage.Disable>(_manager);
            _bus.Subscribe<ProjectionManagementMessage.Enable>(_manager);
            _bus.Subscribe<ProjectionManagementMessage.Abort>(_manager);
            _bus.Subscribe<ProjectionManagementMessage.SetRunAs>(_manager);
            _bus.Subscribe<ProjectionManagementMessage.Reset>(_manager);
            _bus.Subscribe<ProjectionManagementMessage.StartSlaveProjections>(_manager);
            _bus.Subscribe<ClientMessage.WriteEventsCompleted>(_manager);
            _bus.Subscribe<ClientMessage.ReadStreamEventsBackwardCompleted>(_manager);
            _bus.Subscribe<ClientMessage.WriteEventsCompleted>(_manager);
            _bus.Subscribe<SystemMessage.StateChangeMessage>(_manager);


            foreach(var q in _processingQueues)
                SetUpCoreServices(q.Item1, q.Item2, q.Item3);

            //Given();
            WhenLoop();
        }
Esempio n. 43
0
        /// <summary>
        /// Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String" /> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            switch (Type)
            {
            case DataType.Void:
                return("void");

            case DataType.Nil:
                return("nil");

            case DataType.Boolean:
                return(Boolean.ToString().ToLower());

            case DataType.Number:
                return(Number.ToString(CultureInfo.InvariantCulture));

            case DataType.String:
                return("\"" + String + "\"");

            case DataType.Function:
                return(string.Format("(Function {0:X8})", Function.EntryPointByteCodeLocation));

            case DataType.ClrFunction:
                return(string.Format("(Function CLR)", Function));

            case DataType.Table:
                return("(Table)");

            case DataType.Tuple:
                return(string.Join(", ", Tuple.Select(t => t.ToString()).ToArray()));

            case DataType.TailCallRequest:
                return("Tail:(" + string.Join(", ", Tuple.Select(t => t.ToString()).ToArray()) + ")");

            case DataType.UserData:
                return("(UserData)");

            case DataType.Thread:
                return(string.Format("(Coroutine {0:X8})", this.Coroutine.ReferenceID));

            default:
                return("(???)");
            }
        }
Esempio n. 44
0
        public void CDSStripperFacts()
        {
            var origin = new DateTime(2020, 06, 15);
            var usd    = TestProviderHelper.CurrencyProvider.GetCurrency("USD");
            var df     = new ConstantRateIrCurve(0.05, origin, "LIBOR", usd);

            var data = new Tuple <Frequency, double>[]
            {
                new Tuple <Frequency, double>(1.Years(), 0.01),
                new Tuple <Frequency, double>(2.Years(), 0.012),
                new Tuple <Frequency, double>(3.Years(), 0.013),
                new Tuple <Frequency, double>(4.Years(), 0.0135),
                new Tuple <Frequency, double>(5.Years(), 0.014),
            };

            var cdses = data.Select(d => new CDS()
            {
                Basis      = DayCountBasis.ACT365F,
                Currency   = usd,
                OriginDate = origin,
                Tenor      = d.Item1,
                Spread     = d.Item2,
                Notional   = 1e6
            }).ToList();

            foreach (var cds in cdses)
            {
                cds.Init();
            }

            var sut = new NewtonRaphsonCreditCurveSolver
            {
                UseSmallSteps = true
            };

            var hz = sut.Solve(cdses, 0.4, df, origin);

            var pz = cdses.Select(c => hz.GetSurvivalProbability(c.FinalSensitivityDate));

            foreach (var p in pz)
            {
                Assert.True(!double.IsNaN(p));
            }
        }
Esempio n. 45
0
        /// <summary>
        /// Return Created Role Ids.
        /// </summary>
        /// <returns>Role Ids.</returns>
        private ICollection <string> CreateRoles()
        {
            var roleSysAdmin          = GetRoleSystemAdministrator();
            var roleWarehouseManager  = GetRoleWarehouseManager();
            var roleWarehouseOperator = GetRoleWarehouseOperator();
            var roles = new Tuple <string, string, string>[] { roleSysAdmin, roleWarehouseManager, roleWarehouseOperator };

            CreateRoles(roles);

            CreateRolePermissions(roleSysAdmin.Item1, PermissionUtils.Permissions.SystemManagement);

            CreateRolePermissions(roleWarehouseManager.Item1, PermissionUtils.Permissions.MaterailInOutManagement);
            CreateRolePermissions(roleWarehouseManager.Item1, PermissionUtils.Permissions.InventoryManagement);
            CreateRolePermissions(roleWarehouseManager.Item1, PermissionUtils.Permissions.ViewsAndReports);

            CreateRolePermissions(roleWarehouseOperator.Item1, PermissionUtils.Permissions.MaterailInOutManagement);

            return(roles.Select(r => r.Item1).ToList());
        }
Esempio n. 46
0
        public bool[] ItWorks(TimeSpan timespan, Tuple<int, bool>[] events)
        {
            var innerTrigger = TriggerTestHelpers.SequenceTrigger(events.Select(x => x.Item2).ToArray());
            var now = DateTime.UtcNow;

            var trigger = new OncePerTimespanTriggerFake(innerTrigger, timespan);

            var results = new List<bool>();

            foreach(var @event in events)
            {
                trigger.SetNow(now.AddSeconds(@event.Item1));
                var result = trigger.Check();

                results.Add(result);
            }

            return results.ToArray();
        }
Esempio n. 47
0
        public async Task UsingMultiConditionalsAsync()
        {
            using (var session = OpenSession())
                using (session.BeginTransaction())
                {
                    // when Name = "testa" then 1 ...
                    var orderOfNames = new Tuple <string, string>[]
                    {
                        System.Tuple.Create("test1", "1"),
                        System.Tuple.Create("testz", "2"),
                        System.Tuple.Create("test2", "3"),
                        System.Tuple.Create("testa", "4")
                    };

                    var criterionProjections =
                        orderOfNames
                        .Select(
                            x => new ConditionalProjectionCase(
                                Restrictions.Eq(nameof(Student.Name), x.Item1),
                                Projections.Constant(x.Item2)))
                        .ToArray();

                    // ... else 99
                    var elseProjection = Projections.Constant("99");

                    var conditionalsProjection = Projections.Conditional(criterionProjections, elseProjection);

                    var order = Order.Asc(conditionalsProjection);

                    var criteria = session.CreateCriteria(typeof(Student)).AddOrder(order);

                    var actuals = await(criteria.ListAsync <Student>());

                    Assert.That(actuals.Count, Is.GreaterThanOrEqualTo(orderOfNames.Length));
                    for (var i = 0; i < orderOfNames.Length; i++)
                    {
                        var expected = orderOfNames[i];
                        var actual   = actuals[i];

                        Assert.That(actual.Name, Is.EqualTo(expected.Item1));
                    }
                }
        }
Esempio n. 48
0
        public IList <int> LexicalOrderV2(int n)
        {
            Tuple <int, string>[] numbers = new Tuple <int, string> [n];
            for (int i = 1; i <= n; i++)
            {
                numbers[i - 1] = new Tuple <int, string>(i, i.ToString());
            }
            int maxLength = numbers[numbers.Length - 1].Item2.Length;

            LinkedList <Tuple <int, string> >[] linkedArray = new LinkedList <Tuple <int, string> > [11];

            for (int i = 0; i < linkedArray.Length; i++)
            {
                linkedArray[i] = new LinkedList <Tuple <int, string> >();
            }

            for (int i = maxLength - 1; i >= 0; i--)
            {
                for (int j = 0; j < numbers.Length; j++)
                {
                    if (numbers[j].Item2.Length - 1 < i)
                    {
                        linkedArray[0].AddLast(numbers[j]);
                    }
                    else
                    {
                        linkedArray[numbers[j].Item2[i] - '0' + 1].AddLast(numbers[j]);
                    }
                }

                int k = 0;
                for (int j = 0; j < linkedArray.Length; j++)
                {
                    while (linkedArray[j].Count > 0)
                    {
                        numbers[k] = linkedArray[j].First.Value;
                        linkedArray[j].RemoveFirst();
                        k++;
                    }
                }
            }
            return(numbers.Select(v => v.Item1).ToArray());
        }
Esempio n. 49
0
        public static string GenerateBlocks()
        {
            var componentsArray = new string[] { "Block A", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sagittis nisl ut tellus egestas facilisis. Nulla eget erat dictum, facilisis libero sit amet, sollicitudin tortor. Morbi iaculis, urna eu tincidunt dapibus, sapien ex dictum nibh, non congue urna tellus vitae risus." };
            var buttonsArray    = new Tuple <string, string>[] { Tuple.Create <string, string>("http://www.google.com", "Button A"), Tuple.Create <string, string>("http://www.disney.com", "Button B") };

            var items   = componentsArray.Select(item => MailBody.CreateBlock().Paragraph(item));
            var buttons = buttonsArray.Select(item => MailBody.CreateBlock().Button(item.Item1, item.Item2));

            var body = MailBody
                       .CreateBody()
                       .Paragraph("Hello,")
                       .SubTitle("Here is the blocks:")
                       .AddBlocksList(items)
                       .AddBlocksList(buttons)
                       .Paragraph("— [Insert company name here]")
                       .ToString();

            return(body);
        }
Esempio n. 50
0
        public void NormalizeTest()
        {
            var testCases = new Tuple <Orientation, Orientation>[]
            {
                Tuple.Create(Orientation.North, Orientation.North),
                Tuple.Create(Orientation.West, Orientation.West),
                Tuple.Create(Orientation.South, Orientation.South),
                Tuple.Create(Orientation.East, Orientation.East),

                Tuple.Create(Orientation.East, Orientation.East + 4),
                Tuple.Create(Orientation.East, Orientation.East + 8),
                Tuple.Create(Orientation.East, Orientation.East - 4),
                Tuple.Create(Orientation.East, Orientation.East - 8),
            };

            testCases
            .Select((i) => Tuple.Create(i.Item1, i.Item2.Normalize()))
            .ValidateEquality();
        }
Esempio n. 51
0
        public void TurnTest()
        {
            var testCases = new Tuple <Orientation, int, Orientation>[]
            {
                Tuple.Create(Orientation.North, 0, Orientation.North),
                Tuple.Create(Orientation.West, 4, Orientation.West),
                Tuple.Create(Orientation.South, -4, Orientation.South),
                Tuple.Create(Orientation.East, 8, Orientation.East),

                Tuple.Create(Orientation.North, 1, Orientation.West),
                Tuple.Create(Orientation.North, 2, Orientation.South),
                Tuple.Create(Orientation.North, -2, Orientation.South),
                Tuple.Create(Orientation.North, 3, Orientation.East),
                Tuple.Create(Orientation.North, -1, Orientation.East),
            };

            testCases
            .Select((fo) => Tuple.Create(fo.Item3, fo.Item1.Turn(fo.Item2)))
            .ValidateEquality();
        }
Esempio n. 52
0
        public void AwardMarks(Tuple<IGuessDTO, int>[] marks)
        {
            var chainId = marks[0].Item1.Chain.Id;

            if(marks.Select(m => m.Item1.Chain.Id).Any(x => x != chainId))
            {
                throw new InvalidOperationException();
            }

            var chain = this.Repository.Query<IChainDTO>(c => c.Id == chainId).FirstOrDefault();

            var chainComplete = new CompleteChain(chain);

            if (chainComplete.HasMarksAssigned(this.Id))
            {
                throw new InvalidOperationException();
            }
            foreach(var mark in marks)
            {
                //this.Repository.Insert<IMarkDTO>(new MarkDTO() {Guess = mark.Item1, Score = mark.Item2, Awarder = this});
            }
        }
Esempio n. 53
0
        private static void DoSv(Tuple<double[], double>[] classified)
        {
            var stripped = classified.Select(t => new Tuple<double[], double>(t.Item1.Skip(1).ToArray(), t.Item2))
            .ToArray();
              var q = GetQ(stripped);

              //all are 0 or more
              var lcc = new LinearConstraintCollection(
            Enumerable.Range(0, stripped.Length)
              .Select(i => new LinearConstraint(1)
              {
            VariablesAtIndices = new[] { i },
            ShouldBe = ConstraintType.GreaterThanOrEqualTo,
            Value = 0.0,
            CombinedAs= new []{1.0} //???
              }));
              //and they zero out with the classificaiton
              lcc.Add(
            //new LinearConstraint(stripped.Select(t => t.Item2).ToArray()) { Value = 0, ShouldBe = ConstraintType.EqualTo }
            new LinearConstraint(stripped.Length)
            {
              Value = 0,
              ShouldBe = ConstraintType.EqualTo,
              VariablesAtIndices = Enumerable.Range(0, stripped.Length).ToArray(),
              CombinedAs = stripped.Select(t => t.Item2).ToArray()
            }        );

              var solver = new GoldfarbIdnaniQuadraticSolver(stripped.Length, lcc);
              solver.Minimize(q, neg1Array(stripped.Length));
              //b  = 1/y - w_*x_

              var tmp = solver.Solution.Zip(stripped, (alpha, s) => s.Item1.Select(x => x * alpha * s.Item2))
            .Aggregate(VAdd).ToList();
              var support = solver.Solution.Zip(stripped, (alpha, s) => Math.Abs(alpha) > 0.0001 ? s : null).Where(x => x != null).ToArray();
              var offset = GetOffset(support, tmp); //I'm pretty sure this calculation for b is wrong: you get a different one for each of elements...
              tmp.Insert(0, offset);
              var wSupp = Norm( tmp.ToArray());
        }
Esempio n. 54
0
 internal static string MultipleApplicableRegistrationsFound(Type serviceType,
     Tuple<Type, Type, InstanceProducer>[] overlappingRegistrations) => 
     string.Format(CultureInfo.InvariantCulture,
         "Multiple applicable registrations found for {0}. The applicable registrations are {1}. " +
         "If your goal is to make one registration a fallback in case another registration is not " +
         "applicable, make the fallback registration last using RegisterConditional and make sure " +
         "the supplied predicate returns false in case the Handled property is true.",
         serviceType.ToFriendlyName(),
         overlappingRegistrations.Select(BuildRegistrationName).ToCommaSeparatedText());
Esempio n. 55
0
 private static double GetOffset(Tuple<double[], double>[] stripped, List<double> tmp)
 {
     //these should all be the same, but they ain't dammit. Am I misunderstanding things, or are doubles this crappy in this situation?
       var foo = stripped.Select(s => 1 / s.Item2 - Dot(tmp.ToArray(), s.Item1)).ToArray();
       return foo.Average(); //.First();
 }
Esempio n. 56
0
        private static void testCluter()
        {
            int ss = 100, sq = 100, k = 10, m = 10; // 采样数,G取前k,S取前m
            int randcount = 5, randtake = 10, randselect = 3;
            var timer = new MyTimer();
            var templatefiles = Directory.GetFiles(@"D:\Play Data\字符模板");
            int templatecount = templatefiles.Length;
            var templateChars = new string[templatecount];
            var templatePoints = new Vector2[templatecount][];
            //var templatesc = new double[templatecount][,];
            var templatesc = new double[templatecount][][];
            #region 计算模板的SC
            for (int f = 0; f < templatecount; ++f) {
                string file = templatefiles[f], filename = Path.GetFileNameWithoutExtension(file);
                using (Image<Gray, Byte> img = new Image<Gray, byte>(file)) {
                    var samples = getEdge(img).Sample(ss);
                    templatesc[f] = Jim.OCR.ShapeContext2D.ShapeContext.ComputeSC2(samples);
                    templatePoints[f] = samples.Select(p => new Vector2(p.X, p.Y)).ToArray();
                }
                templateChars[f] = filename;
                Console.Write(filename);
            }
            Console.WriteLine();
            Debug("模板读取完成");
            #endregion

            #region 处理字符
            foreach (string file in Directory.GetFiles(@"D:\Play Data\字符")) {
                string filename = Path.GetFileNameWithoutExtension(file);
                if (filename != "AB") continue;
                timer.Restart();
                Image<Bgr, Byte> img = new Image<Bgr, Byte>(file);
                var samples = getEdge(img.Convert<Gray, Byte>()).Sample(sq);
                //double[,] SCQ = Jim.OCR.ShapeContext2D.ShapeContext.ComputeSC(samples);
                double[][] SCQ = Jim.OCR.ShapeContext2D.ShapeContext.ComputeSC2(samples);
                var Q_Points = samples.Select(p => new Vector2(p.X, p.Y)).ToArray();
                var mmg = img.Convert<Bgr, Byte>();
                Graphics g = Graphics.FromImage(mmg.Bitmap);
                Q_Points.ToList().ForEach(v => { mmg[(int)v.Y, (int)v.X] = new Bgr(0, 0, 255); });

                var point_distance = new ValueIndexPair<double>[sq][];
                #region 计算采样点之间的距离
                for (int i = 0; i < sq; ++i) {
                    double xi = Q_Points[i].X, yi = Q_Points[i].Y;
                    point_distance[i] = new ValueIndexPair<double>[sq];
                    for (int j = 0; j < sq; ++j) {
                        double xj = Q_Points[j].X, yj = Q_Points[j].Y;
                        point_distance[i][j] = new ValueIndexPair<double> {
                            Value = Math.Sqrt((xi - xj) * (xi - xj) + (yi - yj) * (yi - yj)),
                            Index = j
                        };
                    }
                    Array.Sort(point_distance[i], (a, b) => a.Value.CompareTo(b.Value));
                }
                #endregion
                var randpoints = new int[randcount][];
                #region 随机取randcount个点,并在其周围randtake个点中取randselect个
                for (int i = 0; i < randcount; ++i) {
                    int pi = rand.Next(Q_Points.Length);
                    var p = Q_Points[pi];
                    mmg.Draw(new CircleF(new PointF((float)p.X, (float)p.Y), 2), new Bgr(255, 0, 0), 1);

                    randpoints[i] = new int[randselect];
                    bool[] vi = Utils.InitArray<bool>(randtake, false);
                    for (int cnt = 0; cnt < randselect; ) {
                        int rnd = rand.Next(randtake);
                        if (!vi[rnd]) {
                            vi[rnd] = true;
                            randpoints[i][cnt++] = rnd;
                        }
                    }
                    for (int ppp = 0; ppp < randselect; ++ppp) {
                        var pt = Q_Points[point_distance[pi][randpoints[i][ppp]].Index];
                        //g.DrawString(i.ToString(), new Font("Arial", 7), new SolidBrush(Color.FromArgb(0, 128, 0)), new PointF((float)pt.X, (float)pt.Y));
                    }
                }
                #endregion
                #region 为这randcount组RSC分别选最好的模板
                var rscmatch = new Tuple<int, double, Vector2>[randcount]; // <Si, d, L>
                for (int rc = 0; rc < randcount; ++rc) {
                    var rsc_matches = new Tuple<double, Vector2>[templatecount]; // <d, L>
                    for (int i = 0; i < templatecount; ++i) {
                        #region 拷贝出一个rsc来
                        var rsc = new double[randselect][];
                        for (int j = 0; j < randselect; ++j) {
                            rsc[j] = new double[60];
                            Array.Copy(SCQ[randpoints[rc][j]], rsc[j], 60);
                        }
                        #endregion
                        var costmat = Jim.OCR.ShapeContext2D.ShapeContext.HistCost2(rsc, templatesc[i]);
                        var matches = costmat.Select(
                            row => row.Select((d, c) => new ValueIndexPair<double> { Value = d, Index = c })
                                      .OrderBy(d => d.Value).First()).ToArray();
                        Vector2 L = Vector2.Zero;
                        double M = 0;
                        for (int j = 0; j < randselect; ++j) {
                            int u = randpoints[rc][j], mu = matches[j].Index;
                            double d = matches[j].Value;
                            Vector2 pu = Q_Points[u], pmu = templatePoints[i][mu];
                            M += (1 - d);
                            L += (1 - d) * (pu - pmu);
                        }
                        L /= M;

                        rsc_matches[i] = new Tuple<double, Vector2> {
                            First = matches.Sum(r => r.Value),
                            Second = L
                        };
                    }
                    var best_template = rsc_matches.Select((mt, i) => new { Match = mt, i })
                                                   .OrderBy(t => t.Match.First)
                                                   .First();
                    rscmatch[rc] = new Tuple<int, double, Vector2> {
                        First = best_template.i,
                        Second = best_template.Match.First,
                        Third = best_template.Match.Second
                    };

                    string label = templateChars[best_template.i];
                    g.DrawString(label, new Font("Arial", 48), Brushes.Green,
                                 new PointF((float)best_template.Match.Second.X, (float)best_template.Match.Second.Y));
                }
                #endregion

                //Font f = new Font("Arial", 12);
                //var G = new Tuple<int, int, double>[templatecount][]; // <u, m(u), d>
                //#region 为每个Si挑选合适的Gi
                //{
                //    var costmats = new double[templatecount][,];
                //    for (int i = 0; i < templatecount; ++i) {
                //        double[,] SCi = templatesc[i];
                //        costmats[i] = Jim.OCR.ShapeContext2D.ShapeContext.HistCost(SCQ, SCi);
                //        G[i] = new Tuple<int, int, double>[sq * ss];
                //        for (int u = 0; u < sq; ++u) {
                //            for (int j = 0; j < ss; ++j) {
                //                G[i][u * ss + j] = new Tuple<int, int, double> {
                //                    First = u,
                //                    Second = j,
                //                    Third = costmats[i][u, j]
                //                };
                //            }
                //        }
                //        Array.Sort(G[i], (da, db) => da.Third.CompareTo(db.Third));
                //    }
                //}
                //#endregion
                //var d_Q_S = new double[templatecount];
                //#region 求出每个Si和Q的d(Q, Si)
                //{
                //    for (int i = 0; i < templatecount; ++i) {
                //        var Gi = G[i].Take(k);
                //        foreach (var g in Gi) {
                //            int u = g.First, mu = g.Second;
                //            double d = g.Third;
                //            double Nu = G.Average(gi => gi.First(t => t.First == u).Third);
                //            d_Q_S[i] += d / Nu;
                //        }
                //        d_Q_S[i] /= k;
                //    }
                //}
                //#endregion
                //var firstmG = new Tuple<Tuple<int, int, double>[], double, int>[m]; // <G, d, i> <=> <<u, m(u), d>[], d, i>
                //#region 根据d(Q, Si)截取前20个最好的Gi
                //{
                //    var firstmdQS = d_Q_S.Select((d, i) => new ValueIndexPair<double> { Value = d, Index = i })
                //        .OrderBy(p => p.Value)
                //        .Take(firstmG.Length).ToArray();
                //    for (int p = 0; p < firstmG.Length; ++p) {
                //        double d = firstmdQS[p].Value;
                //        int i = firstmdQS[p].Index;
                //        firstmG[p] = new Tuple<Tuple<int, int, double>[], double, int> {
                //            First = G[i].Take(k).ToArray(),
                //            Second = d,
                //            Third = i
                //        };
                //    }
                //}
                //#endregion
                //#region 计算每个G的位置
                //var L = new Vector2[m];
                //{
                //    for (int i = 0; i < m; ++i) {
                //        L[i] = Vector2.Zero;
                //        double Mi = 0;
                //        var Gi = firstmG[i];
                //        foreach (var u_mu_d in Gi.First) {
                //            int u = u_mu_d.First, mu = u_mu_d.Second;
                //            double d = u_mu_d.Third;
                //            Vector2 pu = Q_Points[u], pmu = templatePoints[Gi.Third][mu];
                //            L[i] += (1 - d) * (pu - pmu);
                //            Mi += (1 - d);
                //        }
                //        L[i] /= Mi;

                //        g.DrawString(templateChars[Gi.Third], new Font("Arial", 12), Brushes.Green,
                //                     new PointF((float)L[i].X, (float)L[i].Y));
                //    }
                //}
                //#endregion
                mmg.Save(Path.Combine(@"D:\Play Data\测试玩意", filename + ".bmp"));
                Debug("{0}\t用时{1}ms.", filename, timer.Stop());
            }
            #endregion
        }
        private static Tuple<double, double>[] TransformValues(Tuple<double, double>[] orig, double fromDist, double toDist, double fromPerc, double toPerc, bool isUpGraph)
        {
            double percentMinRange = 0;
            double percentMaxRange = 1;
            if (!isUpGraph)
            {
                // The slope is going down, so reverse the min/max
                percentMinRange = 1;
                percentMaxRange = 0;
            }

            return orig.Select(o => Tuple.Create(
                UtilityCore.GetScaledValue(fromDist, toDist, 0, 1, o.Item1),
                UtilityCore.GetScaledValue(fromPerc, toPerc, percentMinRange, percentMaxRange, o.Item2)
                )).ToArray();
        }
 private static Tuple<double, double>[] ReverseY(Tuple<double, double>[] orig)
 {
     return orig.
         Select(o => Tuple.Create(o.Item1, 1d - o.Item2)).
         ToArray();
 }
        public string ValidateParms(INakedObjectAdapter nakedObjectAdapter, Tuple<string, INakedObjectAdapter>[] parms) {
            foreach (NakedObjectValidationMethod validator in ValidateMethods) {
                Tuple<string, INakedObjectAdapter>[] matches = validator.ParameterNames.Select(name => parms.SingleOrDefault(p => p.Item1.ToLower() == name)).Where(p => p != null).ToArray();

                if (matches.Count() == validator.ParameterNames.Count()) {
                    INakedObjectAdapter[] parameters = matches.Select(p => p.Item2).ToArray();
                    string result = validator.Execute(nakedObjectAdapter, parameters);
                    if (result != null) return result;
                }
                else {
                    string actual = parms.Select(s => s.Item1).Aggregate((s, t) => s + " " + t);
                    LogNoMatch(validator, actual);
                }
            }
            return null;
        }
Esempio n. 60
-1
        /// <param name="path">Application relative path to the module directory.</param>
        /// <param name="resources">All the unresolved resources found in the module.</param>
        /// <param name="isResourceOrderFixed">When true, the resources will not be sorted by their dependency ordering.</param>
        public UnresolvedModule(string path, UnresolvedResource[] resources, string location, bool isResourceOrderFixed)
        {
            this.path = path;
            this.location = location;

            var pathsInModule = new HashSet<string>(resources.Select(resource => resource.Path));
            partition = PartitionResourceReferences(resources, pathsInModule);
            // Store all the references to external resources.
            this.externalReferences = partition.SelectMany(p => p.Item2).Distinct().ToArray();
            // The resources now only contain references found in this module.
            var resolvedResources = partition.Select(p => p.Item1).ToArray();
            if (isResourceOrderFixed)
            {
                this.resources = resolvedResources;
            }
            else
            {
                this.resources = OrderScriptsByDependency(resolvedResources);
            }
        }