示例#1
0
        private void btnGoooo_Click(object sender, RoutedEventArgs e)
        {
            var selectedPath = txtPath.Text;

            if (string.IsNullOrEmpty(selectedPath))
            {
                var fbd = new System.Windows.Forms.FolderBrowserDialog();
                if (fbd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }
                selectedPath = txtPath.Text = fbd.SelectedPath;
            }

            // Start
            _pictures.Clear();
            var paths = selectedPath.Split('%');

            foreach (var path in paths)
            {
                FindFilesInDirectory(path);
            }

            _pictures.Shuffle();
            _pictureTimer.Interval = 1;
            _pictureTimer.Elapsed += (o, args) =>
            {
                _pictureTimer.Stop();
                _pictureTimer.Interval = 1800;

                if (_pictures.Count > _pictureIndex)
                {
                    // turn down for shuffle
                    _pictures.Shuffle();
                    _pictures.Shuffle();
                    _pictures.Shuffle();

                    _pictureIndex = 0;
                }

                Dispatcher.Invoke(
                    new Action(() =>
                {
                    pictureBoxSlideshowMask.Source =
                        pictureBoxSlideshow.Source =
                            new BitmapImage(
                                new Uri(_pictures[_pictureIndex]));

                    PathTextBox.Text = _pictures[_pictureIndex];

                    _pictureTimer.Start();
                }));

                _pictureIndex++;
            };
            _pictureTimer.Start();
        }
示例#2
0
        /**
         * Loads terms and frequencies from Wikipedia (cached).
         */

        public override void SetUp()
        {
            Debug.Assert(false, "disable assertions before running benchmarks!");
            IList <Input> input = ReadTop50KWiki();

            input.Shuffle();
            dictionaryInput = input.ToArray();
            input.Shuffle();
            benchmarkInput = input;
        }
示例#3
0
        /// <summary>
        /// Reset the deck to its original state, restoring any cards that were consumed.
        /// </summary>
        public void Reset()
        {
            var _fascistCards = Enumerable.Range(1, Constants.TotalFascistPolicies).Select(_ => PolicyType.Fascist);
            var _liberalCards = Enumerable.Range(1, Constants.TotalLiberalPolicies).Select(_ => PolicyType.Liberal);

            _policyDeck.Clear();
            _policyDeck.AddRange(_fascistCards.Concat(_liberalCards));
            _policyDeck.Shuffle();
            _discardDeck.Clear();
        }
示例#4
0
        /**
         * Loads terms and frequencies from Wikipedia (cached).
         */

        public override void SetUp()
        {
            if (Debugging.AssertsEnabled)
            {
                Debugging.Assert(false, () => "disable assertions before running benchmarks!");
            }
            IList <Input> input = ReadTop50KWiki();

            input.Shuffle(Random);
            dictionaryInput = input.ToArray();
            input.Shuffle(Random);
            benchmarkInput = input;
        }
示例#5
0
        public void Train(IList<InputOutput> trainingSet, INeuralNetwork nn)
        {
            Validate();

            if (nn == null)
                throw new ArgumentNullException(nameof(nn));

            var rand = RandomProvider.GetRandom(Seed);

            if (ShouldInitializeWeights)
                InitializeWeights(nn, rand);

            var validationSetFraction = GetValidationSetFraction();

            IList<InputOutput> trainingSubSet;
            IList<InputOutput> validationSubSet = null;

            if (validationSetFraction > 0)
            {
                var split = trainingSet.Shuffle(rand).Split(validationSetFraction);
                validationSubSet = split.First;
                trainingSubSet = split.Second;
            }
            else
            {
                trainingSubSet = trainingSet;
            }

            Train(trainingSubSet, validationSubSet, rand, nn);
        }
示例#6
0
        public Deck()
        {
            IList <Card> cards = CreateCardsOrdered();

            cards.Shuffle();
            Cards = new Stack <Card>(cards);
        }
示例#7
0
        /// <summary>
        /// will use Shuffle if you want many of the items, as it will be more efficient
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="count"></param>
        /// <param name="rand"></param>
        /// <returns></returns>
        public static List <T> SampleAtRandomWithoutReplacement <T>(this IList <T> list, int count, Random rand)
        {
            Helper.CheckCondition(count <= list.Count, "Can't sample without replacement more items that there are");
            if (count > list.Count / 4)
            {
                list.Shuffle(rand).Take(count).ToList();
            }

            //first sample the indexes, and make sure there are no duplicates:
            HashSet <int> sampledIndexes = new HashSet <int>();

            while (sampledIndexes.Count < count)
            {
                int nxtIndex = rand.Next(list.Count);

                if (!sampledIndexes.Contains(nxtIndex))
                {
                    sampledIndexes.Add(nxtIndex);
                }
            }
            Helper.CheckCondition(sampledIndexes.Distinct().Count() == count, "something went wrong--bug");

            List <T> results = list.SubList(sampledIndexes.ToList());

            return(results);
        }
示例#8
0
        public void Train(IList <InputOutput> trainingSet, INeuralNetwork nn)
        {
            Validate();

            if (nn == null)
            {
                throw new ArgumentNullException(nameof(nn));
            }

            var rand = RandomProvider.GetRandom(Seed);

            if (ShouldInitializeWeights)
            {
                InitializeWeights(nn, rand);
            }

            var validationSetFraction = GetValidationSetFraction();

            IList <InputOutput> trainingSubSet;
            IList <InputOutput> validationSubSet = null;

            if (validationSetFraction > 0)
            {
                var split = trainingSet.Shuffle(rand).Split(validationSetFraction);
                validationSubSet = split.First;
                trainingSubSet   = split.Second;
            }
            else
            {
                trainingSubSet = trainingSet;
            }

            Train(trainingSubSet, validationSubSet, rand, nn);
        }
        /// <summary>
        /// Returns a list of matches where each team from list1 plays against a team from teams2.
        /// All teams from both lists play one match. Whether a team plays home or away is determined randomly.
        /// The total number of teams for both lists must be an even number and both lists must contain an equal number of teams.
        /// </summary>
        public List<Match> GetMatches(IList<Team> teams1, IList<Team> teams2)
        {
            // Total number of teams must be even and both lists same number of teams.
             bool isValid = (teams1.Count + teams2.Count) % 2 == 0
                        && teams1.Count == teams2.Count;
             if (!isValid)
             {
            throw new Exception("Even number of teams expected and both lists same number of teams");
             }

             teams1.Shuffle();
             teams2.Shuffle();

             var matches = new List<Match>();
             for (int i = 0; i < teams1.Count; i++)
             {
            // Optionally swith home/away
            var homeTeam = teams1[i];
            var awayTeam = teams2[i];
            bool switchHomeAndAway = _randomizer.GetRandomBoolean();
            if (switchHomeAndAway)
            {
               homeTeam = teams2[i];
               awayTeam = teams1[i];
            }

            var match = MatchFactory.CreateMatch(homeTeam, awayTeam);

            matches.Add(match);
             }

             return matches;
        }
示例#10
0
 /// <summary>
 /// Shuffles an IList in place as many times as specified.
 /// </summary>
 /// <typeparam name="T">The type of elements in the list</typeparam>
 public static void Shuffle <T>(this IList <T> list, int numberOfRuns)
 {
     for (int i = 0; i < numberOfRuns; i++)
     {
         list.Shuffle(new Random());
     }
 }
示例#11
0
        //---------------------------------------------------------------------
        public void Shuffle()
        {
            this.listOfCards = AllCards.Shuffle(Random).ToList();

            mapSameTypeCard = new Dictionary <CardTypeNiuNiu, List <Card> >();
            mapSameSuitCard = new Dictionary <CardSuit, List <Card> >();
            foreach (var i in listOfCards)
            {
                CardTypeNiuNiu card_type         = (CardTypeNiuNiu)i.Type;
                List <Card>    list_sametypecard = null;
                mapSameTypeCard.TryGetValue(card_type, out list_sametypecard);
                if (list_sametypecard == null)
                {
                    list_sametypecard          = new List <Card>();
                    mapSameTypeCard[card_type] = list_sametypecard;
                }

                list_sametypecard.Add(i);

                CardSuit    card_suit         = (CardSuit)i.Suit;
                List <Card> list_samesuitcard = null;
                mapSameSuitCard.TryGetValue(card_suit, out list_samesuitcard);
                if (list_samesuitcard == null)
                {
                    list_samesuitcard          = new List <Card>();
                    mapSameSuitCard[card_suit] = list_samesuitcard;
                }

                list_samesuitcard.Add(i);
            }
        }
示例#12
0
文件: Game.cs 项目: mcsoaa/CardGame2
        private void Awake()
        {
            Log.Verbose("Game Awake", "Unity");
            // TODO: Random Start
            _eventAggregator = new EventAggregator();
            _first           = PhotonNetwork.isMasterClient ? PlayerType.Player : PlayerType.Opponent;
            _idFactory       = new CardIdFactory();
            _players         = new Dictionary <PlayerType, Player>();
            foreach (var type in Extension.GetValues <PlayerType>())
            {
                _players.Add(type, new Player(this, type));
            }
            _battle = null;
            _deck   = new List <string>(Deck.Get().GetList());
            _deck.Shuffle();
            Subscribe(this);


            GuiMediator.OnButtonClick += OnButtonClick;
            GuiMediator.SetButtonClickable(ButtonType.NextPhaseButton, PhotonNetwork.isMasterClient);
            GuiMediator.OnCardDragToZone += OnCardDragToZone;
            GuiMediator.OnCardDragToCard += OnCardDragToCard;
            QuitButton.onClick.AddListener(() => { PhotonNetwork.LeaveRoom(); });
            End = false;
        }
示例#13
0
        private static void CreateLeagueMatches(IList <Team> teams, ICollection <Match> listOfMatches, int leagueId, Func <int, LeagueMatchCreationMode> getMatchCreationMode)
        {
            teams.Shuffle();

            var mode = getMatchCreationMode(leagueId);

            List <Match> generateMatches;

            switch (mode)
            {
            case LeagueMatchCreationMode.Single:
                generateMatches = new SingleRoundMatchCreator().CreateMatches(teams);
                break;

            case LeagueMatchCreationMode.Double:
                generateMatches = new DoubleRoundMatchCreator().CreateMatches(teams);
                break;

            default:
                throw new Exception("Unknown match creation mode");
            }

            foreach (var match in generateMatches)
            {
                match.LeagueId = leagueId;
                listOfMatches.Add(match);
            }
        }
 public Task RandomPruneAsync(IList <Edge> edges, int removeEdgesCount, int[] verticesDegree, CancellationToken token)
 {
     edges.Shuffle();
     return(Task.Run(() =>
     {
         var sw = new Stopwatch(); sw.Start();
         var maxrun = edges.Count;
         while (removeEdgesCount > 0 && !token.IsCancellationRequested && maxrun > 0)
         {
             maxrun--;
             var edge = edges.First();
             var couldRemoveV1 = (verticesDegree[edge.V1] - 1) > 0;
             var couldRemoveV2 = (verticesDegree[edge.V2] - 1) > 0;
             if (couldRemoveV1 && couldRemoveV2)
             {
                 removeEdgesCount--;
                 verticesDegree[edge.V1]--;
                 verticesDegree[edge.V2]--;
                 edges.RemoveAt(0);
             }
         }
         sw.Stop();
         Console.WriteLine($"      SAMPLE takes {sw.ElapsedMilliseconds / 1000f} seconds to prune");
     }));
 }
        public IList <Matchday> CreateSchedule(IList <Team> teams, bool withReverseFixtures)
        {
            var teamToMakeEven = new Team();

            if (teams.Count % 2 != 0)
            {
                teams.Add(teamToMakeEven);
            }
            teams.Shuffle();

            Team markerTeam = teams[1];

            List <Matchday> matchdays      = new List <Matchday>();
            int             matchDayNumber = 1;

            do
            {
                matchdays.Add(createMatchday(matchDayNumber, teams));
                advanceTeams(teams);
                matchDayNumber++;
            } while (teams[1] != markerTeam);

            if (withReverseFixtures)
            {
                matchdays.AddRange(createReverseMatchdays(matchdays));
            }
            teams.Remove(teamToMakeEven);
            return(matchdays);
        }
示例#16
0
        public static IList <string> SortearTabelaCampeonato(IList <string> competidores)
        {
            if (competidores.Count < 3)
            {
                throw new ArgumentException("A lista de competidoes não pode ser menor que 3", "competidores");
            }

            competidores.Shuffle();

            int qtd_competidores = competidores.Count;

            IList <string> competidores_1 = new List <string>();
            IList <string> competidores_2 = new List <string>();

            definir_lista_competidores(ref competidores, ref competidores_1, ref competidores_2);

            List <string> partidas_torneio = new List <string>();

            // A quantidade de rodadas do torneio é igual a quantidade de competidores no caso de quantidade de competidores ímpar
            // No caso de quantidade de competidores par, a quantidade de rodadas é a quantidade de competidores menos 1.
            int qtd_rodadas = qtd_competidores - (competidores.Contains("Folga") ? 0 : 1);

            for (int rodada = 0; rodada < qtd_rodadas; rodada++)
            {
                // A quantidade de partidas da rodada é igual a quantidade de competidores "real" dividido por 2.
                int      qtd_partidas_rodada = qtd_competidores / 2;
                string[] partidas_rodada     = new string[qtd_partidas_rodada];

                for (int partida = 0, competidor = 0; partida < qtd_partidas_rodada; partida++, competidor++)
                {
                    // Se for uma partida válida, insere na rodada, senão, reduz o número da partida para não ignorar o último confronto da rodada.
                    if (competidores_2[competidor] != "Folga" && competidores_1[competidor] != "Folga")
                    {
                        partidas_rodada[partida] = String.Format("Rodada {0}: {1} vs {2}", rodada + 1, competidores_1[competidor], competidores_2[competidor]);
                    }
                    else
                    {
                        partida--;
                    }
                }

                // Pega os competidores que trocarão de lista.
                string competidor_lista1_para_lista2 = competidores_1[competidores_1.Count - 1];
                string competidor_lista2_para_lista1 = competidores_2[0];

                // Remove os competidores da lista.
                competidores_1.Remove(competidor_lista1_para_lista2);
                competidores_2.Remove(competidor_lista2_para_lista1);

                // Insere o competidor logo após o primeiro da lista.
                competidores_1.Insert(1, competidor_lista2_para_lista1);

                // Insere o competidor no final da lista.
                competidores_2.Add(competidor_lista1_para_lista2);

                partidas_torneio.AddRange(partidas_rodada);
            }

            return(partidas_torneio);
        }
示例#17
0
        //---------------------------------------------------------------------
        public void Shuffle()
        {
            this.listOfCards = AllCards.Shuffle(Random).ToList();

            mapSameTypeCard = new Dictionary <MaJiangType, List <Card> >();
            mapSameSuitCard = new Dictionary <MaJiangSuit, List <Card> >();
            foreach (var i in listOfCards)
            {
                List <Card> list_sametypecard = null;
                mapSameTypeCard.TryGetValue((MaJiangType)i.Type, out list_sametypecard);
                if (list_sametypecard == null)
                {
                    list_sametypecard = new List <Card>();
                    mapSameTypeCard[(MaJiangType)i.Type] = list_sametypecard;
                }

                list_sametypecard.Add(i);

                List <Card> list_samesuitcard = null;
                mapSameSuitCard.TryGetValue((MaJiangSuit)i.Suit, out list_samesuitcard);
                if (list_samesuitcard == null)
                {
                    list_samesuitcard = new List <Card>();
                    mapSameSuitCard[(MaJiangSuit)i.Suit] = list_samesuitcard;
                }

                list_samesuitcard.Add(i);
            }
        }
示例#18
0
        /// <summary>
        /// Regenerates stock state by randomizing some values,
        /// such as amount of different items and number of new items in the stock.
        /// </summary>
        public void RegenerateStock()
        {
            // Create a fast variable, in case if I will change the target.
            IList <IItem> stock = myStock;

            // Randomize item positions (just for a visible effect)
            stock.Shuffle();

            // Update last update time
            myLastStockUpdateTime = DateTime.Now;

            // Randomize items amount
            for (int ma = 0; ma < stock.Count; ++ma)
            {
                int randomAmount = Random.Next(0, 20);

                // Remove if amount is 0
                if (randomAmount == 0)
                {
                    stock.RemoveAt(ma);
                    continue;
                }

                // Update item amount
                stock[ma].Amount = randomAmount;
            }

            // Add new items
            int newItemsCount = (Random.Next(2) == 0) ? 0 : Random.Next(1, 4);

            for (var ma = 0; ma < newItemsCount; ++ma)
            {
                stock.Add(GenerateItem());
            }
        }
示例#19
0
        public static T PickAndRemoveBest <T>(this IList <T> enumerable, Func <T, IComparable> keySelector, Random random)
        {
            var pick = enumerable.Shuffle(random).OrderByDescending(keySelector).First();

            enumerable.Remove(pick);
            return(pick);
        }
        /// <summary>Compute parameters (latent factors) for a user represented by ratings</summary>
        /// <returns>a vector of latent factors</returns>
        /// <param name='rated_items'>a list of (item ID, rating value) pairs</param>
        protected virtual float[] FoldIn(IList <Tuple <int, float> > rated_items)
        {
            var user_vector = new float[NumFactors];

            user_vector.InitNormal(InitMean, InitStdDev);
            rated_items.Shuffle();
            double lr = LearnRate;

            for (uint it = 0; it < NumIter; it++)
            {
                for (int index = 0; index < rated_items.Count; index++)
                {
                    int   item_id = rated_items[index].Item1;
                    float err     = rated_items[index].Item2 - Predict(user_vector, item_id, false);

                    // adjust factors
                    for (int f = 0; f < NumFactors; f++)
                    {
                        float u_f = user_vector[f];
                        float i_f = item_factors[item_id, f];

                        double delta_u = err * i_f - Regularization * u_f;
                        user_vector[f] += (float)(lr * delta_u);
                    }
                }
                lr *= Decay;
            }
            return(user_vector);
        }
示例#21
0
 public static void ShuffleManyTimes <T>(this IList <T> list, int nbOfShuffles)
 {
     for (int i = 0; i < nbOfShuffles; i++)
     {
         list.Shuffle();
     }
 }
示例#22
0
        public void Returns_shuffled_collection(IList <int> collection)
        {
            IEnumerable <int> shuffled = collection.Shuffle();

            shuffled.ShouldNotBeSameAs(collection);
            shuffled.ShouldNotBe(new [] { 1, 2, 3, 4, 5, 6 });
        }
示例#23
0
        /// <summary>
        /// Trains the <paramref name="network"/> using <paramref name="trainingDatasetEntries"/> and return the average training cost of the final iteration.
        /// </summary>
        /// <param name="network">The neural network that is to be trained.</param>
        /// <param name="trainingDatasetEntries">The training iterations to train the network with.</param>
        /// <returns>Returns the average training cost of the final iteration.</returns>
        private IDFFNeuralNetwork TrainNetwork(IDFFNeuralNetwork network, IList <INetworkTrainingIteration> trainingDatasetEntries)
        {
            var priorTrainingCost = 999.0;
            var trainingIteration = 0;

            while (true)
            {
                trainingDatasetEntries.Shuffle();

                // TODO: Implement Clone() method for NeuralNetwork and store the BEST network.
                var trainingCost = network.Train(trainingDatasetEntries).Average(i => i.TrainingCost);

                Console.WriteLine($"{trainingIteration} : {trainingCost}");

                // Check the training cost every 500 iterations to ensure it's continuing to improve
                if (trainingIteration % 500 == 0)
                {
                    if ((priorTrainingCost - trainingCost) < .01)
                    {
                        break;
                    }
                    else
                    {
                        priorTrainingCost = trainingCost;
                    }
                }


                trainingIteration++;
            }

            return(network);
        }
示例#24
0
        /// <summary>
        /// Returns a list of matches where each team from list1 plays against a team from teams2.
        /// All teams from both lists play one match. Whether a team plays home or away is determined randomly.
        /// The total number of teams for both lists must be an even number and both lists must contain an equal number of teams.
        /// </summary>
        public List <Match> GetMatches(IList <Team> teams1, IList <Team> teams2)
        {
            // Total number of teams must be even and both lists same number of teams.
            bool isValid = (teams1.Count + teams2.Count) % 2 == 0 &&
                           teams1.Count == teams2.Count;

            if (!isValid)
            {
                throw new Exception("Even number of teams expected and both lists same number of teams");
            }

            teams1.Shuffle();
            teams2.Shuffle();

            var matches = new List <Match>();

            for (int i = 0; i < teams1.Count; i++)
            {
                // Optionally swith home/away
                var  homeTeam          = teams1[i];
                var  awayTeam          = teams2[i];
                bool switchHomeAndAway = _randomizer.GetRandomBoolean();
                if (switchHomeAndAway)
                {
                    homeTeam = teams2[i];
                    awayTeam = teams1[i];
                }

                var match = MatchFactory.CreateMatch(homeTeam, awayTeam);

                matches.Add(match);
            }

            return(matches);
        }
示例#25
0
        /// <summary>
        /// Randomly select specified number of items from the list.
        /// The items with higher weight are in the result with higher probability
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <param name="weight"></param>
        /// <returns></returns>
        public static IList <T> WeightedChoice <T>(this IList <T> items, int selectCount, Func <T, double> weight)
        {
            if (selectCount < 1 || selectCount > items.Count)
            {
                throw new ArgumentOutOfRangeException("The size of the selection must be a positive number equal or less than the size of the list");
            }

            if (selectCount == items.Count)
            {
                return(items);
            }

            items.Shuffle();

            List <Flagable <T> > _list = ConvertToFlagable(items);

            var result = new List <Flagable <T> >();

            while (selectCount > 0)
            {
                var selected = SelectItems(_list, weight, selectCount);
                selectCount -= selected.Count;
                result.AddRange(selected);
                _list.RemoveAll(item => item.Flag == true);                 //remove those that are already selected
            }

            return(result.Select(item => item.obj).ToList <T>());
        }
 public RandomSimilarityProvider(Random random)
 {
     perFieldSeed    = random.Next();
     coordType       = random.Next(3);
     shouldQueryNorm = random.NextBoolean();
     knownSims       = new List <Similarity>(allSims);
     knownSims.Shuffle(random);
 }
示例#27
0
        // Select N random items from list, without replacement.
        // Modifies the given list.

        public static SCG.IEnumerable <T> RandomWithout1 <T>(IList <T> list, int N)
        {
            list.Shuffle(rnd);
            foreach (T x in list.View(0, N))
            {
                yield return(x);
            }
        }
示例#28
0
 public void Shuffle()
 {
     do
     {
         Cards.Shuffle();
     }while (_unshuffledDeck.Cards.SequenceEqual(Cards));
     IsShuffled = true;
 }
示例#29
0
 void Awake()
 {
     foreach (Transform Child in transform)
     {
         SpawnLocations.Add(Child);
     }
     SpawnLocations.Shuffle();
 }
        ///
        protected override float[] FoldIn(IList <Tuple <int, float> > rated_items)
        {
            var user_p = new float[NumFactors];

            user_p.InitNormal(InitMean, InitStdDev);
            float user_bias = 0;

            var   items           = (from pair in rated_items select pair.Item1).ToArray();
            float user_reg_weight = FrequencyRegularization ? (float)(Regularization / Math.Sqrt(items.Length)) : Regularization;

            // compute stuff that will not change
            var    y_sum_vector     = y.SumOfRows(items);
            double norm_denominator = Math.Sqrt(items.Length);

            for (int f = 0; f < y_sum_vector.Count; f++)
            {
                y_sum_vector[f] = (float)(y_sum_vector[f] / norm_denominator);
            }

            rated_items.Shuffle();
            for (uint it = 0; it < NumIter; it++)
            {
                for (int index = 0; index < rated_items.Count; index++)
                {
                    int item_id = rated_items[index].Item1;

                    double prediction = global_bias + user_bias + item_bias[item_id];
                    prediction += DataType.MatrixExtensions.RowScalarProduct(item_factors, item_id, y_sum_vector);
                    prediction += DataType.MatrixExtensions.RowScalarProduct(item_factors, item_id, user_p);

                    float err = (float)(rated_items[index].Item2 - prediction);

                    // adjust bias
                    user_bias += BiasLearnRate * LearnRate * ((float)err - BiasReg * user_reg_weight * user_bias);

                    // adjust factors
                    for (int f = 0; f < NumFactors; f++)
                    {
                        float u_f = user_p[f];
                        float i_f = item_factors[item_id, f];

                        double delta_u = err * i_f - user_reg_weight * u_f;
                        user_p[f] += (float)(LearnRate * delta_u);
                    }
                }
            }

            // assign final parameter values to return vector
            var user_vector = new float[NumFactors + 1];

            user_vector[0] = user_bias;
            for (int f = 0; f < NumFactors; f++)
            {
                user_vector[f + 1] = (float)y_sum_vector[f] + user_p[f];
            }

            return(user_vector);
        }
        public void ShouldThrowExceptionBecauseOfNull()
        {
            // Given
            IList <int> arr    = null;
            Action      action = () => arr.Shuffle();

            // Then
            action.ShouldThrow <ArgumentNullException>();
        }
示例#32
0
        public static void Shuffle <T>(this IList <T> self, System.Random random)
        {
            int GetRandomIndex(int i)
            {
                return(random.Next(0, i + 1));
            }

            self.Shuffle(GetRandomIndex);
        }
示例#33
0
        /// <summary>Online evaluation for rankings of items</summary>
        /// <remarks>
        /// The evaluation protocol works as follows:
        /// For every test user, evaluate on the test items, and then add the those test items to the training set and perform an incremental update.
        /// The sequence of users is random.
        /// </remarks>
        /// <param name="recommender">the item recommender to be evaluated</param>
        /// <param name="test">test cases</param>
        /// <param name="training">training data (must be connected to the recommender's training data)</param>
        /// <param name="test_users">a list of all test user IDs</param>
        /// <param name="candidate_items">a list of all candidate item IDs</param>
        /// <param name="candidate_item_mode">the mode used to determine the candidate items</param>
        /// <returns>a dictionary containing the evaluation results (averaged by user)</returns>
        public static ItemRecommendationEvaluationResults EvaluateOnline(
			this IRecommender recommender,
			IPosOnlyFeedback test, IPosOnlyFeedback training,
			IList<int> test_users, IList<int> candidate_items,
			CandidateItems candidate_item_mode)
        {
            var incremental_recommender = recommender as IIncrementalItemRecommender;
            if (incremental_recommender == null)
                throw new ArgumentException("recommender must be of type IIncrementalItemRecommender");

            // prepare candidate items once to avoid recreating them
            switch (candidate_item_mode)
            {
                case CandidateItems.TRAINING: candidate_items = training.AllItems; break;
                case CandidateItems.TEST:     candidate_items = test.AllItems; break;
                case CandidateItems.OVERLAP:  candidate_items = new List<int>(test.AllItems.Intersect(training.AllItems)); break;
                case CandidateItems.UNION:    candidate_items = new List<int>(test.AllItems.Union(training.AllItems)); break;
            }

            test_users.Shuffle();
            var results_by_user = new Dictionary<int, ItemRecommendationEvaluationResults>();
            foreach (int user_id in test_users)
            {
                if (candidate_items.Intersect(test.ByUser[user_id]).Count() == 0)
                    continue;

                // prepare data
                var current_test_data = new PosOnlyFeedback<SparseBooleanMatrix>();
                foreach (int index in test.ByUser[user_id])
                    current_test_data.Add(user_id, test.Items[index]);
                // evaluate user
                var current_result = Items.Evaluate(recommender, current_test_data, training, current_test_data.AllUsers, candidate_items, CandidateItems.EXPLICIT);
                results_by_user[user_id] = current_result;

                // update recommender
                var tuples = new List<Tuple<int, int>>();
                foreach (int index in test.ByUser[user_id])
                    tuples.Add(Tuple.Create(user_id, test.Items[index]));
                incremental_recommender.AddFeedback(tuples);
            }

            var results = new ItemRecommendationEvaluationResults();

            foreach (int u in results_by_user.Keys)
                foreach (string measure in Items.Measures)
                    results[measure] += results_by_user[u][measure];

            foreach (string measure in Items.Measures)
                results[measure] /= results_by_user.Count;

            results["num_users"] = results_by_user.Count;
            results["num_items"] = candidate_items.Count;
            results["num_lists"] = results_by_user.Count;

            return results;
        }
示例#34
0
 public InfectionDeck(IList<InfectionCard> infectionCards)
 {
     infectionCards.Shuffle();
     foreach (InfectionCard card in infectionCards)
     {
         card.Discarded += CardDiscarded;
     }
     cardPile = new Stack<InfectionCard>(infectionCards);
     discardPile = new Stack<InfectionCard>();
 }
示例#35
0
        /// <summary>
        /// Used by the producer to send a metadata request since it has access to the ProducerConfig
        /// </summary>
        /// <param name="topics">The topics for which the metadata needs to be fetched</param>
        /// <param name="brokers">The brokers in the cluster as configured on the client</param>
        /// <param name="producerConfig">The producer's config</param>
        /// <param name="correlationId">topic metadata response</param>
        /// <returns></returns>
        public static TopicMetadataResponse FetchTopicMetadata(
            ISet<string> topics, IList<Broker> brokers, ProducerConfig producerConfig, int correlationId)
        {
            var fetchMetaDataSucceeded = false;
            var i = 0;
            var topicMetadataRequest = new TopicMetadataRequest(
                TopicMetadataRequest.CurrentVersion, correlationId, producerConfig.ClientId, topics.ToList());

            TopicMetadataResponse topicMetadataResponse = null;
            Exception t = null;

            // shuffle the list of brokers before sending metadata requests so that most requests don't get routed to the same broker
            var shuffledBrokers = brokers.Shuffle();
            while (i < shuffledBrokers.Count() && !fetchMetaDataSucceeded)
            {
                var producer = ProducerPool.CreateSyncProducer(producerConfig, shuffledBrokers[i]);
                Logger.InfoFormat("Fetching metadata from broker {0} with correlation id {1} for {2} topic(s) {3}", shuffledBrokers[i], correlationId, topics.Count, string.Join(",", topics));
                try
                {
                    topicMetadataResponse = producer.Send(topicMetadataRequest);
                    fetchMetaDataSucceeded = true;
                }
                catch (Exception e)
                {
                    Logger.Warn(string.Format("Fetching topic metadata with correlation id {0} for topic [{1}] from broker [{2}] failed", correlationId, topics, shuffledBrokers[i]), e);
                    t = e;
                }
                finally
                {
                    i++;
                    producer.Dispose();
                }
            }

            if (!fetchMetaDataSucceeded)
            {
                throw new KafkaException(
                    string.Format(
                        "fetching topic metadata for topics [{0}] from broker [{1}] failed", string.Join(",", topics), string.Join(", ", shuffledBrokers)),
                    t);
            }

            Logger.DebugFormat("Successfully fetched metadata for {0} topic(s) {1}", topics.Count(), string.Join(",",  topics));
            return topicMetadataResponse;
        }
        /// <summary>
        /// SIDE EFFECT: Sets the Victim property if needed
        /// </summary>
        /// <param name="zoo"></param>
        /// <param name="killer"></param>
        /// <returns>the night activity text</returns>
        public IList<string> GetNightActivity(IList<string> zoo, string killer)
        {
            if (!zoo.Contains(killer))
            {
                return new List<string>();
            }

            zoo.Shuffle();
            Victim = GetVictim(zoo, killer);

            IList<string> nightCopy = new List<string>(GameResources.TwoPersonNightActivities);
            nightCopy.Shuffle();

            IList<string> activities = new List<string>();
            for (int i = 0; i < zoo.Count - 1; i++)
            {
                activities.Add(String.Format(nightCopy[i], zoo[i], zoo[i + 1]));
            }
            activities.Add(String.Format(nightCopy[zoo.Count], zoo[zoo.Count - 1], zoo[0]));
            activities.Shuffle();

            return activities;
        }
示例#37
0
文件: Learn.cs 项目: dbremner/szotar
		void StartRound() {
			int round = rounds.Count + 1;

			var previousRound = currentRound;
			if (currentRound != null)
				rounds.Add(currentRound);
			currentRound = new List<Attempt>();

			items = previousRound != null 
				? new List<PracticeItem>(from x in previousRound where !x.Correct select x.Item) 
				: Owner.GetAllItems();

			items.Shuffle(rng);

			index = 0;
			score = 0;

			state = items.Count > 0 ? State.Guessing : State.GameOverview;
		}
示例#38
0
        /// <summary>
        /// Returns a list of matches where all teams play one match.
        /// Whether a team plays home or away is determined randomly.
        /// The given team list must contain an even number of teams.
        /// </summary>
        public List<Match> GetMatches(IList<Team> teams)
        {
            // Even number of teams expected.
             bool isValid = teams.Count % 2 == 0;
             if (!isValid)
             {
            throw new Exception("Even number of teams expected");
             }

             teams.Shuffle();

             var matches = new List<Match>();
             for (int i = 0; i < teams.Count; i += 2)
             {
            var match = MatchFactory.CreateMatch(teams[i], teams[i + 1]);
            matches.Add(match);
             }

             return matches;
        }
        ///
        protected override float[] FoldIn(IList<Tuple<int, float>> rated_items)
        {
            SetupLoss();

            // initialize user parameters
            float user_bias = 0;
            var factors = new float[NumFactors];
            factors.InitNormal(InitMean, InitStdDev);

            float reg_weight = FrequencyRegularization ? (float) (RegU / Math.Sqrt(rated_items.Count)) : RegU;

            // perform training
            rated_items.Shuffle();
            for (uint it = 0; it < NumIter; it++)
                for (int index = 0; index < rated_items.Count; index++)
                {
                    int item_id = rated_items[index].Item1;

                    // compute rating and error
                    double score = global_bias + user_bias + item_bias[item_id] + DataType.MatrixExtensions.RowScalarProduct(item_factors, item_id, factors);
                    double sig_score = 1 / (1 + Math.Exp(-score));
                    double prediction = min_rating + sig_score * rating_range_size;
                    double err = rated_items[index].Item2 - prediction;

                    float gradient_common = compute_gradient_common(sig_score, err);

                    // adjust bias
                    user_bias += BiasLearnRate * LearnRate * (gradient_common - BiasReg * reg_weight * user_bias);

                    // adjust factors
                    for (int f = 0; f < NumFactors; f++)
                    {
                        float u_f = factors[f];
                        float i_f = item_factors[item_id, f];

                        double delta_u = gradient_common * i_f - reg_weight * u_f;
                        factors[f] += (float) (LearnRate * delta_u);
                    }
                }

            var user_vector = new float[NumFactors + 1];
            user_vector[FOLD_IN_BIAS_INDEX] = user_bias;
            Array.Copy(factors, 0, user_vector, FOLD_IN_FACTORS_START, NumFactors);

            return user_vector;
        }
示例#40
0
        ///
        protected override float[] FoldIn(IList<Tuple<int, float>> rated_items)
        {
            var user_p = new float[NumFactors];
            user_p.InitNormal(InitMean, InitStdDev);
            float user_bias = 0;

            var items = (from pair in rated_items select pair.Item1).ToArray();
            float user_reg_weight = FrequencyRegularization ? (float) (Regularization / Math.Sqrt(items.Length)) : Regularization;

            // compute stuff that will not change
            var y_sum_vector = y.SumOfRows(items);
            double norm_denominator = Math.Sqrt(items.Length);
            for (int f = 0; f < y_sum_vector.Count; f++)
                y_sum_vector[f] = (float) (y_sum_vector[f] / norm_denominator);

            rated_items.Shuffle();
            for (uint it = 0; it < NumIter; it++)
            {
                for (int index = 0; index < rated_items.Count; index++)
                {
                    int item_id = rated_items[index].Item1;

                    double prediction = global_bias + user_bias + item_bias[item_id];
                    prediction += DataType.MatrixExtensions.RowScalarProduct(item_factors, item_id, y_sum_vector);
                    prediction += DataType.MatrixExtensions.RowScalarProduct(item_factors, item_id, user_p);

                    float err = (float) (rated_items[index].Item2 - prediction);

                    // adjust bias
                    user_bias += BiasLearnRate * LearnRate * ((float) err - BiasReg * user_reg_weight * user_bias);

                    // adjust factors
                    for (int f = 0; f < NumFactors; f++)
                    {
                        float u_f = user_p[f];
                        float i_f = item_factors[item_id, f];

                        double delta_u = err * i_f - user_reg_weight * u_f;
                        user_p[f] += (float) (LearnRate * delta_u);
                    }
                }
            }

            // assign final parameter values to return vector
            var user_vector = new float[NumFactors + 1];
            user_vector[0] = user_bias;
            for (int f = 0; f < NumFactors; f++)
                user_vector[f + 1] = (float) y_sum_vector[f] + user_p[f];

            return user_vector;
        }
示例#41
0
文件: Rep.cs 项目: okrotowa/Yorsh
 public async Task BonusGenerateAsync(int count)
 {
     var connect = new SQLiteAsyncConnection(DataBaseFile);
     _bonuses = await connect.Table<BonusTable>().Take(count).ToListAsync();
     _bonuses.Shuffle();
 }
        ///
        protected override float[] FoldIn(IList<Tuple<int, float>> rated_items)
        {
            SetupLoss();

            float user_bias = 0;

            var items = (from pair in rated_items select pair.Item1).ToArray();
            float user_reg_weight = FrequencyRegularization ? (float) (Regularization / Math.Sqrt(items.Length)) : Regularization;

            // compute stuff that will not change
            var y_sum_vector = y.SumOfRows(items);
            double norm_denominator = Math.Sqrt(items.Length);
            for (int f = 0; f < y_sum_vector.Count; f++)
                y_sum_vector[f] = (float) (y_sum_vector[f] / norm_denominator);

            rated_items.Shuffle();
            for (uint it = 0; it < NumIter; it++)
            {
                for (int index = 0; index < rated_items.Count; index++)
                {
                    int item_id = rated_items[index].Item1;

                    double score = global_bias + user_bias + item_bias[item_id];
                    score += item_factors.RowScalarProduct(item_id, y_sum_vector);
                    double sig_score = 1 / (1 + Math.Exp(-score));
                    double prediction = min_rating + sig_score * rating_range_size;
                    float err = (float) (rated_items[index].Item2 - prediction);
                    float gradient_common = compute_gradient_common(sig_score, err);

                    // adjust bias
                    user_bias += BiasLearnRate * LearnRate * ((float) gradient_common - BiasReg * user_reg_weight * user_bias);
                }
            }

            // assign final parameter values to return vector
            var user_vector = new float[NumFactors + 1];
            user_vector[0] = user_bias;
            for (int f = 0; f < NumFactors; f++)
                user_vector[f + 1] = (float) y_sum_vector[f];

            return user_vector;
        }
        /// <summary>Compute parameters (latent factors) for a user represented by ratings</summary>
        /// <returns>a vector of latent factors</returns>
        /// <param name='rated_items'>a list of (item ID, rating value) pairs</param>
        protected virtual float[] FoldIn(IList<Pair<int, float>> rated_items)
        {
            var user_vector = new float[NumFactors];
            user_vector.InitNormal(InitMean, InitStdDev);
            rated_items.Shuffle();
            for (uint it = 0; it < NumIter; it++)
            {
                for (int index = 0; index < rated_items.Count; index++)
                {
                    int item_id = rated_items[index].First;
                    float err = rated_items[index].Second - Predict(user_vector, item_id, false);

                    // adjust factors
                    for (int f = 0; f < NumFactors; f++)
                    {
                        float u_f = user_vector[f];
                        float i_f = item_factors[item_id, f];

                        double delta_u = err * i_f - Regularization * u_f;
                        user_vector[f] += (float) (LearnRate * delta_u);
                    }
                }
            }
            return user_vector;
        }