Пример #1
0
let shuffleDiscardPile = () => {
  deck = _.shuffle(discardPile);

  discardPile = [];

  discardPile.push(deck.pop());

  return true;
};
Пример #2
0
Middleware.prototype.getNextQuestion = function(req, res, next) {
  var _this = this;

  if (!this.usersAvailable()) {
    return null;
  }

  var solution = this.getRandomUser();
  this.deleteUser(solution);

  console.log("solution", solution);

  var otherUsers = this.getRandomUsers(this.userCount);
  if (!_.contains(otherUsers, solution)) {
    otherUsers[0]= solution;
    otherUsers = _.shuffle(otherUsers);
  }

  var otherUserRecords = _.filter(this.allUsers, function(user) {
    return _.contains(otherUsers, user.screen_name);
  });

  // function getNextUser(index, callback) {
  //   if (otherUsers.length == index) {
  //     callback();
  //   }

  //   _this.twitter.getUserById(otherUsers[index], function(userData) {
  //     otherUserRecords.push(userData);
  //     getNextUser(index+1, callback);
  //   });
  // }

  console.log("others", otherUsers);

  function buildQuestion(tweets) {
    var questionTweets = _this.twitter.getRandomTweets(tweets, _this.tweetCount);

    req.question = {
      solutionId: solution,
      otherUsers: otherUserRecords,
      tweets: questionTweets
    };

    next();
  }

  // console.log(this.twitter.loadTwitterJSON());
  // async data loading
  // _this.twitter.getUsersByIds(otherUsers, function(data) {  
  //   console.log(data);  
  //   otherUserRecords = data;
  _this.twitter.getTweetsByUserId(solution, _this.tweetPoolCount, buildQuestion);
  // });

};
Пример #3
0
 func: function(user, channel, message, args) {
     var replies = [
         'Yummy!',
         'Thanks, ' + user + '!',
         'My favorite!',
         'Can I have another?',
         'Tasty!'
     ];
     irc_client.say(channel, _.shuffle(replies)[0]);
 }
Пример #4
0
function createGameBoardArray(numPairs){
  // Creates an array of size 2n containing pairs of values in random order
  var array = [];
  var intPairs = parseInt(numPairs);
  var array2 = (_.range(1, (intPairs+1)));
  var array3 = (_.range(1, (intPairs+1)));
  array = array2.concat(array3);
  array = _.shuffle(array);
  return array;
}
Пример #5
0
function generateTiles() {
    var tiles = _.shuffle(fixture.slice(0));
    for (var i = 0; i < tiles.length; i++) {
        _tiles.push(_.extend({}, tiles[i], {
            id: i,
            flipped: false,
            matched: false
        }));
    }
}
Пример #6
0
 return Object.values(matrix).map(row => {
   const vars = columns.length === 0
     ? row
     : pick(row, columns)
   const keys = Object.keys(vars)
   let vals = Object.values(vars)
   vals = shuffle(vals)
   const res = fromPairs(zip(keys, vals))
   return { ...row, ...res }
 })
Пример #7
0
 build() {
   for (let tileType of Object.keys(this.tileConfig.tileTypes)) {
     let tileInfo = this.tileConfig.tileTypes[tileType];
     for (let i=0; i<tileInfo.quantity; i++) {
       this.addTile(tileType, tileInfo);
     }
   }
   this.tilesUnplayed = _.shuffle(this.tilesUnplayed);
   this.addTile(this.tileConfig.tileStart, this.tileConfig.tileTypes[this.tileConfig.tileStart]);
 }
Пример #8
0
  new Game(req.body).save(function(err, game){

    var squares = _.range(game.numSquares);
    squares = squares.concat(squares);
    game.squareData = _.shuffle(squares);
    game.save();
    var response = {  _id: game._id, numSquares: game.numSquares };

    res.send(response);
  });
Пример #9
0
Peers.prototype.listRandomConnected = function(options) {
	options = options || {};
	const peerList = Object.keys(self.peersManager.peers)
		.map(key => self.peersManager.peers[key])
		.filter(peer => peer.state === Peer.STATE.CONNECTED);
	const shuffledPeerList = _.shuffle(peerList);
	return options.limit
		? shuffledPeerList.slice(0, options.limit)
		: shuffledPeerList;
};
            TileCtrl.getTiles(Tile.REGULAR, nbRegular, function(regulars){
                randomTiles = _.concat(randomTiles, regulars);
                randomTiles = _.shuffle(randomTiles);

                var coordoneArray = getCoordArray(nbPlayer);
                coordoneArray.forEach(function(coor){
                    randomTilePick.push(buildTileP(randomTiles.shift(), coor));
                });
                return cb(randomTilePick);
            });
TxProposal._create.multiple_outputs = function(txp, opts) {
  txp.outputs = _.map(opts.outputs, function(output) {
    return _.pick(output, ['amount', 'toAddress', 'message']);
  });
  txp.outputOrder = _.shuffle(_.range(txp.outputs.length + 1));
  txp.amount = txp.getTotalAmount();
  try {
    txp.network = Bitcore.Address(txp.outputs[0].toAddress).toObject().network;
  } catch (ex) {}
};
Пример #12
0
		.then((body) => {
			var array = JSON.parse(body);
			var categories = [];
			_.shuffle(array).forEach(category => {
				if (categories.indexOf(category.category_id) > -1 || categories.length > columns - 1) {
				} else {
					categories.push(category.category_id)
				}
			})
			return categories;
		})
Пример #13
0
module.exports = function sample (typeSchema, n) {

  // Default `n` to 2
  n = _.isUndefined(n) ? 2 : n;

  // Validate `n`
  if (n < 1 || !_.isNumber(n)) {
    throw new Error('rttc.sample() expects `n` (2nd argument) to be a number >= 1 indicating the number of sample values to generate.');
  }

  // Dehydrate the type schema to avoid circular recursion
  var dehydratedTypeSchema = dehydrate(typeSchema);

  // Configure type schema iterator
  var generateSampleVal = buildSchemaIterator(
    function onFacetDict(facetDictionary, parentKeyOrIndex, callRecursive){
      return _.reduce(facetDictionary, function (memo, val, key) {
        var facet = callRecursive(val, key);
        memo[key] = facet;
        return memo;
      }, {});
    },
    function onPatternArray(patternArray, parentKeyOrIndex, iterateRecursive){
      var pattern = iterateRecursive(patternArray[0], 0);
      return [ pattern ];
    },
    function onGenericDict(schema, parentKeyOrIndex){
      return {};
    },
    function onGenericArray(schema, parentKeyOrIndex){
      return [];
    },
    function onOther(schema, parentKeyOrIndex){
      // Pick a random example
      var example = _.sample(typeInfo(schema).getExamples());
      return example;
    }
  );

  // Generate some (unique) sample values
  var samples = _.reduce(_.range(n), function (samplesSoFar, i) {
    var newSample = generateSampleVal(dehydratedTypeSchema);
    var isUnique = _.reduce(samplesSoFar, function checkUniqueness(isUnique, existingSample){
      return isUnique && !isEqual(existingSample, newSample, typeSchema);
    }, true);
    if (isUnique) {
      samplesSoFar.push(newSample);
    }
    return samplesSoFar;
  }, []);

  // Scramble them and return.
  return _.shuffle(samples);
};
Пример #14
0
  shuffle(callback) {
    if (!this.hasOwnProperty('tracksCount'))
      return this.findTracksCount(this.getNextTrack.bind(this));

    var indexesToSearch = [];
    for (var i = 0; i < this.tracksCount; i++)
      indexesToSearch.push(i);

    this.indexesToSearch = shuffle(indexesToSearch);
    callback();
  }
Пример #15
0
    it('always returns fields in alphabetical order', async () => {
      const letters = 'ambcdfjopngihkel'.split('');
      const sortedLetters = sortBy(letters);

      stubDeps({
        fieldsFromFieldCaps: shuffle(letters.map(name => ({ name })))
      });

      const fieldNames = (await getFieldCapabilities()).map(field => field.name);
      expect(fieldNames).toEqual(sortedLetters);
    });
Пример #16
0
 slots = slots.map(function (slot) {
   var _slot = _.shuffle(slot);
   var _featureCounter = {};
   return _slot.filter(function (item) {
     if (!_featureCounter.hasOwnProperty(item.feature)) {
       _featureCounter[item.feature] = 0;
     }
     _featureCounter[item.feature] += 1;
     return (_featureCounter[item.feature] <= maxItems);
   });
 });
Пример #17
0
MutateData.prototype.string = function(str) {
  var mutator = str || this.data;
  var split = mutator.split('');
  var passes = _.random(1, this.config.string.randomisationPasses);
  var i;

  for (i = 0; i < passes; i++) {
    split.splice(_.random(0, split.length), 0, this.config.string.sampleSet.split('')[_.random(0, this.config.string.sampleSet.length)]);
  }

  return _.shuffle(split).join('');
};
Пример #18
0
csv_parse(contents, {columns: true}, function(err, output) {
  const reduced = output.map(function(row) {
    return _.pick(row, ['NUMBER', 'STREET', 'CITY', 'POSTCODE']);
  });

  const randomized = _.shuffle(reduced);

  const shortened = randomized.slice(0, count);

  process.stdout.write('module.exports.data=');
  console.log(JSON.stringify(shortened));
});
Пример #19
0
base.absolutePuller = function (categoryId, total){
    var category = _.find(this.data.categories, {id: categoryId});

    if (!category){
        throw new Error('Tree Puller - Failed to find category');
    }

    var takeAmount = category.questions.length < total ? total : category.questions.length;
    var questions = prioritizer(questions, {prioritizers: this.config.prioritizers});

    return _.shuffle(_.first(questions, takeAmount));
};
Пример #20
0
      connectionsService.getConnections(10).then(function(result) {

        result.values.forEach(function(connection, array, index) {
          if (connection.pictureUrl) {
            that.cards.push(new PhotoCard(connection), new InfoCard(connection));
            that.connections.push(connection);
          }
        });
        that.cards = _.shuffle(that.cards);
        $timeout(that.deal, 0); //Add to end of browser queue so we've already rendered the cards

      }, function(error) {
Пример #21
0
const CheckWordsReducer = function (state = initialState, action) {

  switch (action.type) {
    case Action.API_GET_CHECK_WORDS_SUCCESS: {
     return {...state, words: action.words, initialWords: _.cloneDeep(action.words) };
     }

    case Action.CLEAR_WORDS: {
      return {...state, words: []}
    }

    case Action.SHOW_ANSWER: {
      var newWord = action.word;
      newWord.checked = true;
      return {...state, words: replaceWord(state.words, newWord, action.word.id)};
    }

    case Action.TOGGLE_ANSWER: {
      var newWord = action.word;
      newWord.checked = !action.word.checked;
      return{...state, words: replaceWord(state.words, newWord, action.word.id)};
    }

    case Action.SHUFFLE: {
      return {...state, words: _.shuffle(state.words)};
      }

    case Action.REMOVE_CHECKED:{
      return {...state, words: _.filter(state.words, (w) =>(!w.checked))}
    }

    case Action.TOGGLE_ALL_ANSWERS: {
      var newWords = [];
      var show = _.findIndex(state.words, ['checked', false]) != -1;

      _.forEach(state.words, function (w) {
        w.checked = show;
        newWords.push(w);
      });

      return {...state, words: newWords}
    }

    case Action.RETRY:{
      return {...state, words: _.cloneDeep(state.initialWords)}
    }

    default: {
      /* Return original state if no actions were consumed. */
      return state;
    }
  }
}
Пример #22
0
  constructor() {
     super()
     this.state = {
       letters: Array(9).fill(null),
       isGameWon: false
     }

     this.state.word = _.sample(words).split('')
     this.state.letters = _.shuffle(this.state.word)
     // decomment to style the modal
    //  this.state.letters = this.state.word
   }
Пример #23
0
 /**
  * 分配角色
  */
 assignRoles() {
   // 随机分配身份
   const roles = _.shuffle(this.roles);
   _.forEach(this.players, p => {
     p.role = roles.pop();
   });
   // 主公排在第一位
   const li = _.findIndex(this.players, ['role', 'monarch']);
   this.players = _.slice(this.players, li).concat(_.slice(this.players, 0, li));
   _.forEach(this.players, (p, i) => {p.seatIndex = i;});
   this.emit('roleAssigned');
 }
 test(title, () => _.range(100).forEach(() => {
   try {
     ScopeResolver.validateRoles(_.shuffle(roles));
   } catch (e) {
     if (!errorCode) {
       assume(e).not.exists('unexpected error');
     }
     assume(e.code).equals(errorCode, 'unexpected err.code');
     return;
   }
   assume(errorCode).false('expected an error');
 }));
Пример #25
0
		QuizResult.findOne({user: req.user._id, quiz: quiz._id, completed: false}).exec(function(err, quizResult){
			if (err){ return next(err) }

			if (!quizResult){

				quizResult = new QuizResult()


				quizResult.user = req.user._id
				quizResult.quiz = quiz._id
				quizResult.startDate = new Date()
				quizResult.totalQuizTime = 0

				var questionIds = _.map(quiz.questions, function(q){ return q._id })

				// randomize question order here...
				if (quiz.randomize){
					questionIds = _.shuffle(questionIds)
				}

				// fill in question ids
				_.each(questionIds, function(qId){
					quizResult.quizQuestions.push({
						questionId: qId
					})
				})

				// if no pre/post questions defined, flip completed flag to ignore them
				if (!quiz.preQuestions || quiz.preQuestions.length === 0){
					quizResult.preQuestionsCompleted = true
				} else {
					_.each(quiz.preQuestions, function(q){
						quizResult.preQuestions.push({questionId: q._id})
					})
				}

				if (!quiz.postQuestions || quiz.postQuestions.length === 0){
					quizResult.postQuestionsCompleted = true
				} else {
					_.each(quiz.postQuestions, function(q){
						quizResult.postQuestions.push({questionId: q._id})
					})
				}

				quizResult.save(function(err){
					if (err){ return next(err) }
				
					send(quiz, quizResult)
				})
			} else {
				send(quiz, quizResult)
			}
		})
Пример #26
0
 .then(rows => {
   const santas = _.shuffle(rows);
   const kids = arrayRotate(_.cloneDeep(santas), 1);
   console.log("Santas:", santas);
   console.log("Kids", kids);
   let result = [];
   for (let i = 0; i < santas.length; i++) {
     result.push({ santa_user_id: santas[i].id, kid_user_id: kids[i].id, org_id: 1 });
   }
   console.log("Pairs:", result);
   // return dbHelper.insertSantaKidPairs(result);
 })
Пример #27
0
    _.forEach(teams, function (t) {
        const spieleT = getSpieleByTeam(t, spiele);

        if (spieleT.length < spieleTeam.length) {
            team = t;
            spieleTeam = getSpieleByTeam(team, spiele);
        } else if (spieleT.length === spieleTeam.length) {
            //Randomly choose one
            team = _.head(_.shuffle([team, t]));
            spieleTeam = getSpieleByTeam(team, spiele);
        }
    });
Пример #28
0
    shuffleQuizData() {
        console.log("shuffle", this.quizData)
        if (this.quizData) {
            var data =  _.shuffle(this.quizData);
            console.log(data);
            return data
        } else {
            console.log("no quiz data");
            return false;
        }

    }
Пример #29
0
			function (results, next) {
				tids = results.tagTids.concat(results.searchTids);
				tids = tids.filter(function (_tid) {
					return parseInt(_tid, 10) !== parseInt(tid, 10);
				});
				tids = _.shuffle(_.uniq(tids));

				if (stop !== -1 && tids.length < stop - start + 1) {
					getCategoryTids(tid, uid, next);
				} else {
					next(null, []);
				}
			},
Пример #30
0
  arrayOf: value => {
    const [typeKey, meta] = value.type;
    const gens = typeMap[typeKey](meta, value);
    const shuffled = _.shuffle(gens);

    return [
      _.reduce(shuffled, (acc0, gen0) =>
        gen.bind(acc0, acc =>
          gen.map(rnd => acc.concat(rnd), gen0)
        )
      , gen.return([]))
    ];
  },