makeNick: function() { var nouns = ["alien", "apparition", "bat", "blood", "bogeyman", "boogeyman", "boo", "bone", "cadaver", "casket", "cauldron", "cemetery", "cobweb", "coffin", "corpse", "crypt", "darkness", "dead", "demon", "devil", "death", "eyeball", "fangs", "fear", "fiend", "fog", "gastly", "gengar", "ghost", "ghoul", "goblin", "grave", "gravestone", "grim", "grimreaper", "gruesome", "haunter", "headstone", "hobgoblin", "hocuspocus", "howl", "jack-o-lantern", "mausoleum", "midnight", "mist", "monster", "moon", "mummy", "night", "nightmare", "ogre", "owl", "phantasm", "phantom", "poltergeist", "pumpkin", "scarecrow", "scream", "shadow", "skeleton", "skull", "specter", "spider", "spine", "spirit", "spook", "tarantula", "tomb", "tombstone", "troll", "vampire", "werewolf", "witch", "witchcraft", "wraith", "zombie"]; var adjectives = ["bloodcurdling", "chilling", "creepy", "cold", "crying", "dark", "devilish", "dreadful", "eerie", "evil", "frightening", "frightful", "ghastly", "ghostly", "ghoulish", "gory", "grisly", "hair-raising", "haunted", "horrible", "horrifying", "macabre", "morbid", "mysterious", "ominous", "otherworldly", "repulsive", "revolting", "scary", "shadowy", "shocking", "sinister", "spine-chilling", "spooky", "spoopy", "startling", "supernatural", "terrible", "terrifying", "unearthly", "unnerving", "wicked"]; return ucwords(_.sample(adjectives)) + ucwords(_.sample(nouns)); }
var colourFromFingerPrint = function ( fingerprint ) { // For a while I wanted to highlight different names with different colours but quickly realized that terminals don't support enough of them. Oh well! I'll leave this for the future. d = mapping[ fingerprint ]; if ( d ) { var d = mapping[ fingerprint ]; return chalk[ d[0] ][ d[1] ]; } var cfg, cbg, retries = 0; do { cfg = _.sample( fg, 1 )[ 0 ]; cbg = _.sample( bg, 1 )[ 0 ]; retries += 1; } while ( _.contains( combinations, cfg + cbg ) && retries < 5 ); // TODO: make sure that BG and FG are different colours ... and don't look terrible combinations.push( cfg + cbg ); mapping[ fingerprint ] = [ cfg, cbg ]; return chalk[ cfg ][ cbg ]; };
it("should not be problem to edit profile", function(done) { var middle = ['von', 'fan', 'de', 'es', 'gra', 'du', 'pro', 'ensta', 'repla', 'zoro', 'ok', 'fon', 'fona', 'soro', 'let']; var name = 'Griber '+_.sample(middle)+' John'; var bio = 'My name is ... ' + name; var phone = '+1-202-555-0129'; var email = '*****@*****.**'; var url = 'http://'+_.sample(middle)+'.com'; return ClientV1.Account.editProfile(session, {email: email, fullName: name}) .then(function(account) { should(account).be.an.instanceOf(ClientV1.Account); should(account.params.fullName).be.an.String() should(account.params.fullName).be.equal(name) return account.editProfile({ phoneNumber: phone, biography: bio, externalUrl: url }) }) .then(function(account) { should(account).be.an.instanceOf(ClientV1.Account); should(account.params.phoneNumber).be.empty(); should(account.params.biography).not.be.empty(); should(account.params.biography).be.equal(bio); should(account.params.externalUrl).be.equal(url); done(); }); });
execute: function(unit, dTime) { if (unit.health <= 0 || unit.template.disabled) { return; } if (VectorDistance(unit.position, this.targetPosition) < 1.0 && !this.hasReachedWaypoint) { this.hasReachedWaypoint = true; // Get a random waypoint nearby and travel to it if (unit.connectedNodeList.length === 0) { // log("[Wander] Error: No nodes found!"); } else { var me = this; var newPoint = _.sample(me.waypoints); setTimeout(function() { me.targetPosition = newPoint; me.hasReachedWaypoint = false; }, _.sample(_.range(this.options.minWaitTime, this.options.maxWaitTime)) * 1000); // log("[Wander] Traveling to node "+randomNode.id+"..."); } } //unit.steeringForce = unit.steeringBehaviour.Wander(); unit.TravelToPosition(this.targetPosition); }
var next = function(){ if(t.loading || t.waiting) return console.log("next", t.id) if(t.history.length > 1 && Math.random() <= t.backPropability){ t.history.pop(); t.currentUrl = t.history.pop(); }else{ if(!t.currentUrl){ var entryPoint = _.sample(_.where(t.crawler.db, {entryPoint:true})) if(entryPoint) t.currentUrl = entryPoint.url }else if(t.crawler.db[t.currentUrl].target.length){ t.currentUrl = _.sample(t.crawler.db[t.currentUrl].target) }else if(t.history.length > 1){ t.history.pop(); t.currentUrl = t.history.pop(); } } if(t.currentUrl){ var d = t.minDelay + Math.floor(Math.random()*(t.maxDelay - t.minDelay)); if(_.last(t.history) !== t.currentUrl) t.history.push(t.currentUrl) t.history = _.last(t.history, t.historyLimit) t.waiting = true; setTimeout(()=>{t.waiting = false;t.load()}, d) } }
_.each(repo.channels, function(channel) { // Pick a random branch to pester people about if (_.random(0,1)) { var b = _.sample(deletion, 1)[0]; if (!b) return; say(channel, [ "Branch", b.name, formatStats(b.stats), "is horribly out of date,", b.stats.behind, "commits behind master, and 0 commits ahead. Please spare its life and delete it" ].join(' ') ); } else { var b = _.sample(rebase, 1)[0]; if (!b) return; say(channel, [ "Rebase branch", b.name, "Its behind master", formatStats(b.stats) ].join(' ') ); } if (rebase.length == 0 && deletion.length == 0) { if (! _.random(0,100)) { // 1 in 100 say(channel, ["Team superstars! All your branches on", repo.name, "are up to date, Keep being awesome !"].join(' ')); } } });
reset: function () { var start = { x: _.sample(_.range(this.options.size)), y: _.sample(_.range(this.options.size)) }; this.body = [start]; },
app.get('/presentation', function(req, res) { var presentationImages = _und.sample(slideImages, 4); var presentationPrompt = _und.sample(prompts, 1); res.render('presentation', { title: 'Presentation | Keynote Karaoke', slidesPrompt: presentationPrompt, slides: presentationImages }); });
app.get('/search/:word?', function (req, res) { var searchWord = req.params.word; console.log(searchWord); var results = _.find(words, function (word) { return word.name == searchWord; }); var resObj = {}; resObj.title = 'My Word'; resObj.year = new Date().getFullYear(); // if no word was passed back in search, then grab a random word and return a special message if (searchWord == null || searchWord == "") { var randomWord = _.sample(words); resObj.word = randomWord.name resObj.img = randomWord.img; resObj.letter = randomWord.letter; resObj.msg = "We couldn't find a word that matches your search, but here's a cool word we like!"; } else if (results) { // just bring back a random matching result if there's more than one if (_.isArray(results)) { results = _.sample(results); } resObj.word = results.name; resObj.img = results.img; resObj.letter = results.letter; resObj.msg = ""; } else { // if no matching words, grab a word that starts with that letter var sameFirstLetter = _.find(words, function (word) { return word.name.charAt(0) == searchWord.charAt(0); }); if (sameFirstLetter && !_.isArray(sameFirstLetter)) { resObj.word = sameFirstLetter.name; resObj.msg = "We couldn't find a word that matches your search, but here's a word that starts with the same letter!"; } else if (_.isArray(sameFirstLetter)) { // if there's more than one word returned, grab a random word from that list sameFirstLetter = _.sample(sameFirstLetter); resObj.word = sameFirstLetter.name; resObj.msg = "We couldn't find a word that matches your search, but here's a word that starts with the same letter!"; } else { // if no match then grab a random word and return a special message var randomWord = _.sample(words); resObj.word = randomWord.name resObj.msg = "We couldn't find a word that matches your search, but here's a cool word we like!"; } } //res.send(JSON.stringify(resObj)); res.render('myword', resObj); });
_.times(3, function (i) { var blackCard = _.sample(valentineBlackCards).text; var whiteCardA = _.sample(valentineDeck.whiteCards).text; var whiteCardB = null; while (!whiteCardB || whiteCardB == whiteCardA) { whiteCardB = _.sample(valentineDeck.whiteCards).text; } var valentineText = blackCard.split('______'); valentineText.splice(0, 0, '<span class="inserted">' + whiteCardA + '</span>'); valentineText.splice(-1, 0, '<span class="inserted">' + whiteCardB + '</span>'); cards.push(valentineText.join('')); });
generate: function( numberOfOptions ) { var visualCaptchaSession = this.session[ this.namespace ], imageValues = []; // Avoid the next IF failing if a string with a number is sent numberOfOptions = parseInt( numberOfOptions, 10 ); // If it's not a valid number, default to 5 if ( ! numberOfOptions || ! _.isNumber(numberOfOptions) || isNaN(numberOfOptions) ) { numberOfOptions = 5; } // Set the minimum numberOfOptions to four if ( numberOfOptions < 4 ) { numberOfOptions = 4; } // Shuffle all imageOptions this.imageOptions = _.shuffle( this.imageOptions ); // Get a random sample of X images visualCaptchaSession.images = _.sample( this.imageOptions, numberOfOptions ); // Set a random value for each of the images, to be used in the frontend visualCaptchaSession.images.forEach( function( image, index ) { var randomValue = crypto.randomBytes( 20 ).toString( 'hex' ); imageValues.push( randomValue ); visualCaptchaSession.images[ index ].value = randomValue; }); // Select a random image option, pluck current valid image option visualCaptchaSession.validImageOption = _.sample( _.without( visualCaptchaSession.images, visualCaptchaSession.validImageOption ) ); // Select a random audio option, pluck current valid audio option visualCaptchaSession.validAudioOption = _.sample( _.without( this.audioOptions, visualCaptchaSession.validAudioOption ) ); // Set random hashes for audio and image field names, and add it in the frontend data object visualCaptchaSession.frontendData = { values: imageValues, imageName: this.getValidImageOption().name, imageFieldName: crypto.randomBytes( 20 ).toString( 'hex' ), audioFieldName: crypto.randomBytes( 20 ).toString( 'hex' ) }; },
Sponsor.find({}).then(function (sponsors) { req.base = {}; extend(true, req.base, base); req.base.sponsors = _.sample(sponsors, 10); req.base.allSponsors = sponsors; next(); });
function newRound(gameId) { var game = getGame(gameId); game.nonburrito = _.sample(game.nonburritos); if (game.state === 'roleReview' || game.state === 'heist' || game.state === 'teamVote') { if (game.currentRound) { if (game.currentRound.teamAccepted) { game.heistCount++; game.attemptCount = 0; } else { game.attemptCount++; if (game.attemptCount > 4) { game.currentRound.completed = true; game.currentRound.heistSuccessful = false; game.heistHistory[game.heistCount].heistSuccessful = game.currentRound.heistSuccessful; game.heistHistory[game.heistCount].team = game.currentRound.team; game.heistHistory[game.heistCount].completed = true; game.minorityHeistWins++; game.heistCount++; game.attemptCount = 0; } } game.roundHistory.push(game.currentRound); _.each(game.seats, function(seat) { seat.isOnTeam = false; seat.hasTeamVoted = false; seat.teamVote = false; seat.hasHeistVoted = false; seat.heistVote = false; }); cycleLeader(gameId); game.currentRound = null; } if (game.minorityHeistWins >= 3) { game.minorityVictory = true; visitor.event("Game", "renegades win").send(); finishGame(gameId); } else if (game.majorityHeistWins >= 3) { game.state = 'lastDitch'; } else { var leader = _.find(game.seats, function(seat) { return seat.isLeader === true; }); game.currentRound = { heist: game.heistCount, attempt: game.attemptCount, teamSize: game.heistTeamSizes[game.heistCount], team: [], teamVotes: [], heistVotes: [], teamAccepted: false, heistSuccessful: true, completed: false, leader: leader }; game.state = 'teamBuild'; } } }
spawnPlayer: function() { var protestor = _.sample(this.getProtestors(), 1)[0]; if (!protestor) { // Player is taking over th beagle carrier. Last remaining hope! protestor = this.getBeagleCarrier()[0]; } if (!protestor) { // Game over man! this.eventable.emit("gameover"); return; } this.player = new entities.Player({ existing: protestor }); if (!this.indicator) { this.indicator = new entities.PlayerIndicator({ image: Images.indicator, follow: this.player }); this.entities.add(this.indicator); } else { this.indicator.follow = this.player; } this.entities.add(this.player); protestor.kill(); console.log("Added new player", this.player.hex); },
Quiz.prototype.getNewQuestion = function () { this.question = _.sample(this.quizdata[this.lang].entries); while (this.question.solved === true) { this.question = _.sample(this.quizdata[this.lang].entries); } this.question.solved = false; this.questiontime = moment(); this.questioncounter += 1; this.hintcount = 0; this.debug('%j', this.question); this.channel.say('[%s] The question no. %s is:', ircC.bold('QUIZ'), ircC.bold(this.questioncounter)); this.channel.say('[%s] %s', ircC.bold('QUIZ'), this.getQuestionString()); this.startHints(); };
self._getResults(words, function(results){ var orderedResults = []; var err = false; // note: results not gauranteed to be in order for (var i = 0; i < words.length; i++) { var word = words[i]; for (var j = 0; j < results.length; j++) { if (results[j].length > 0) { if (results[j][0].word == word) { orderedResults[i] = _.sample(results[j]); continue; } } else { err = true; } } } if (err) callback(err, null); else if (!self._videoEnabled) callback(null, orderedResults); else self._concatonateVideo(orderedResults, outputFile, callback); });
create: function(){ var user = {}; user.name = _.sample(['Thomas', 'Edi', 'Jonas', 'Sascha', 'Jeremy', 'Batiste', 'Andy', 'Sebastian']); user.email = user.name.toLowerCase() + '@local.ch'; user.password = '******'; return user; }
WordMachine.prototype.randWords = function(text) { var words = _.uniq(_cleanText(text).split(/\s+/)); // Number of exclusion words should be 0 - n var numRandWords = Math.floor(Math.random() * (words.length + 1)); this.logger.debug("Selecting %d out of %d unique words", numRandWords, words.length); return _.sample(words, numRandWords); };
returnJobSample: (jobs, numberOfJobs) => { let filterJobs = _.filter(jobs, (job) => { //TODO: Need to do further filtering to ensure that the //user's saved job does not show up in slack let jobTitle = job.title.toLowerCase(); return jobTitle.indexOf('lead') === -1 && jobTitle.indexOf('senior') === -1 && jobTitle.indexOf('manager') === -1 && jobTitle.indexOf('sr.') === -1 && jobTitle.indexOf('principal') === -1; }); console.log("# of filtered jobs:", filterJobs.length); //Format job data for Slack message attachment let attachments = _.map(filterJobs, (job) => { return { title: `:computer: ${job.title}`, text: `:office: ${job.company} - ${job.location} \n :link: ${job.link}`, callback_id: `clickSaveJobs`, attachment_type: `default`, actions: [ {name: `saveJob`, text: `Save`, value: job.id, type: `button`, style: `default`} ] }; }); let sample = _.sample(attachments, numberOfJobs); return sample; }
add: function (req) { var params = req.data; var his_player_id = params.his_player_id; var his_player = _.find(board.players, function (pl) { return (pl.name == his_player_id); }); var result = false; var response = {}; var entity_name = params.name; var exist_entity = _.some(board.all_entities(), function (ent) { return ent.name == entity_name }); if (his_player && !exist_entity) { params.vulnerabilities = _.sample(rules.all_vulnerabilities(), 3); var new_entity = new entities.Entity(params); result = his_player.add_entity(new_entity); if (result) { var ent_t_apts = utils.transform_obj_to_name(new_entity, 'aptitudes'); var response_data = utils.transform_obj_to_name(ent_t_apts, 'vulnerabilities'); } response = {result: result, data: response_data}; } app.io.broadcast('entity:add', response); },
const getSample = (input) => { if(_.isArray(input)){ return _.sample(input); } else { return input; } }
.end(function(err) { if (err) { throw err; } request('http://localhost:1337') .get('/hello') .set('Host', 'http://localhost:1337') .set('x-forwarded-for', chance.ip()) .set('user-agent', random_ua.generate()) .set('referrer', _.sample(referrer)) .end(function(err) { if (err) { throw err; } request('http://localhost:1337') .get('/world') .set('Host', 'http://localhost:1337') .set('x-forwarded-for', chance.ip()) .set('user-agent', random_ua.generate()) .set('referrer', _.sample(referrer)) .end(function(err) { if (err) { throw err; } setTimeout(function() { done(); }, Math.round(Math.random() * (3000 - 500)) + 500); }); }); });
function(data) { // Array of peers on DHT network data.map(function(p) { // Don't connect to our PeerId, or any eliminated peers var myPeerId; if(chord._localNode) { myPeerId = chord.getPeerId; } if (p !== myPeerId && eliminatedPeers.indexOf(p) === -1) { console.log('Peer', p); peers.push(p); } }); var randomPeer = _.sample(_.compact(peers)); if (randomPeer) { // Join an existing chord network console.log('Joining', randomPeer); chord.join(randomPeer, join); } else if (eliminatedPeers.length !== 0) { console.log('Fatal: Unable to join any of the existing peers. Failing.'); } else { // Create a new chord network console.log('Creating new network'); chord.create(create); } }
_.each(_.groupBy(module.get('Timetable'), 'LessonType'), function (groups) { var uniqueClassNos = _.uniq(_.pluck(groups, 'ClassNo')); var randomClassNo = _.sample(uniqueClassNos); var isDraggable = _.size(uniqueClassNos) > 1; var sameType = new LessonCollection(); _.each(_.groupBy(groups, 'ClassNo'), function (lessonsData) { var sameGroup = new LessonCollection(); _.each(lessonsData, function (lessonData) { var lesson = new LessonModel(_.extend({ color: color, display: true, isDraggable: isDraggable, ModuleCode: module.id, ModuleTitle: module.get('ModuleTitle'), sameGroup: sameGroup, sameType: sameType }, lessonData)); lessons.add(lesson); sameGroup.add(lesson); sameType.add(lesson); if (!selectedLessonsByType[lessonData.LessonType] && lessonData.ClassNo === randomClassNo) { this.timetable.add(lesson); } }, this); }, this); }, this);
peerManager.getSeedPeers(seedConfiguration, function(err, seeds){ if (err) { callback(err, null); } var seed = _.sample(seeds); callback(null, seed); });
async.forEach(_.range(1, businessCount + 1), function (nr, cb) { var data = { "name": moniker.choose() + " b" + nr, "type": _.random(1, 3), "telephoneNumber": chance.phone(), "picture": "assets/i/business-logo-" + _.random(1, 3) + ".png", "description": chance.paragraph({sentences: 3}), "businessHours": _.random(1, 5) + ":00-" + _.random(9, 12) + ":00", "website": chance.url({path: "/"}), "isVerified": true, "isVerificationFeePaid": true, "isSubscriptionExpired": false, "braintreeAccountId": "fake_business_" + nr }; var tmpAddress = _.sample(addresses); _.extend(data, tmpAddress); if (nr === 10) { data.isVerified = false; data.isVerificationFeePaid = false; data.braintreeAccountId = undefined; } BusinessService.create(data, function (err, business) { testData["business" + nr] = business; cb(err); }); }, callback);
.then(function(response){ var all_todos = response.json.todos; self.all = all_todos self.last = _.last(all_todos) self.random = _.sample(all_todos) deferred.resolve(self); })
}, function (allGiftCards, cb) { var cards = _.sample(allGiftCards, 10); async.forEach(cards, function (giftCard, cb) { var amount = _.random(Math.floor(giftCard.quantity * 0.4), Math.floor(giftCard.quantity * 0.8)) || 1; GiftCardService.redeem(giftCard.currentQRCode, amount, giftCard.businessId, cb); }, cb); }
var request_suggestions = function(services, data, cb) { // TODO: Log final response var Request = loopback.getModel('request'); services = _.filter(services, function(service) { return service.subscriptions().length > 0 }) services = _.sample(services, 5) var subscriptions = _.map(services, function(service) { return _.sample(service.subscriptions()) }) var person = data.person; var location = data.location; Request.create({body: data, personId: person.id, locationId: location.id}, function(err, requestInstance) { async.map(subscriptions, function(subscription, cb) { request.post(subscription.callback_url, {json: data}, function(err, response, body) { if(!err && response.statusCode != 200) { err = "HTTP status code must be 200, it was: " + response.statusCode; } requestInstance.responses.create({'subscriptionId': subscription.id, body: body, error: err}, function(err, response) { cb(null, response); }); }); }, function(err, responses) { return_response(request, responses, cb); }); }); }
getRandomVulnerablePlayer: function () { var vulnerablePlayers = []; vulnerablePlayers = _.filter(this._players, function (player){ return player.getVulnerability(); }); return _.sample(vulnerablePlayers); },