コード例 #1
0
 return regeneratorRuntime.wrap(function sessionCreated$(context$1$0) {
     while (1) switch (context$1$0.prev = context$1$0.next) {
     case 0:
         publicId = R.hash(guid);
         nickname = "Anonymous" + _.random(0, 999999);
         context$1$0.next = 4;
         return this.setNickname(guid, nickname);
     case 4:
         context$1$0.next = 6;
         return this.getStore("/users");
     case 6:
         users = context$1$0.sent;
         users[publicId] = true;
         context$1$0.next = 10;
         return this.setStore("/users", users);
     case 10:
         context$1$0.next = 12;
         return this.postEvent("presence", nickname + " has joined.");
     case 12:
     case "end":
         return context$1$0.stop();
     }
 }, sessionCreated, this);
コード例 #2
0
ファイル: init.js プロジェクト: dulumao/hichat
 _.each(users, function (user) {
   //
   CommonChat.user_ids.push(user.id);
   //
   var user_id = user.id;
   var num     = _.random(1, 3);
   var max     = user.contact_ids.length;
   var i       = 0;
   if (num > max) num = max;
   for (i; i < num; i++) {
     var contact_id = user.contact_ids[i];
     var exist      = _.some(chats, function (chat) {
       var ids = chat.user_ids;
       if (ids === 2) {
         if (ids[0] === user_id && ids[1] === contact_id) return true;
         if (ids[0] === contact_id && ids[1] === user_id) return true;
       }
       return false;
     });
     if (exist) continue;
     chats.push({user_ids: [user_id, contact_id]});
   }
 });
コード例 #3
0
    it('should support middleware', async () => {
      const historyItem = _.random(1, 100);

      await scheduleTask({
        taskType: 'sampleTask',
        interval: '30m',
        params: { historyItem },
      });

      await retry.try(async () => {
        expect((await historyDocs()).length).to.eql(1);

        const [task] = (await currentTasks()).docs;

        expect(task.attempts).to.eql(0);
        expect(task.state.count).to.eql(1);

        expect(task.params).to.eql({
          superFly: 'My middleware param!',
          originalParams: { historyItem },
        });
      });
    });
コード例 #4
0
ファイル: discovery.js プロジェクト: Mattgic/hubiquitus-core
exports.start = function (params, done) {
  if (locked || started) {
    var msg = locked ? 'busy' : 'already started';
    return logger.makeLog('warn', 'hub-38', 'attempt to start discovery while ' + msg + ' !');
  }

  locked = true;

  localInfos.host = properties.netInfo.ip;
  localInfos.port = params.port || _.random(3000, 60000);
  localSock = dgram.createSocket('udp4');
  localSock.on('message', onMessage);

  if (params.addr) {
    var mcastAddr = url.parse(params.addr);
    mcastInfos.host = mcastAddr.hostname;
    mcastInfos.port = mcastAddr.port || 5555;
    mcastSock = dgram.createSocket('udp4');
    mcastSock.on('message', onMessage);
  }

  if (!mcastSock) {
    localSock.bind(localInfos.port, localInfos.host, onStart);
  } else {
    async.parallel([
      function (done) { localSock.bind(localInfos.port, localInfos.host, done); },
      function (done) { mcastSock.bind(mcastInfos.port, mcastInfos.host, done); }
    ], onStart);
  }

  function onStart() {
    started = true;
    locked = false;
    logger.makeLog('trace', 'hub-22', 'discovery started !');
    done && done();
  }
};
コード例 #5
0
ファイル: schema.js プロジェクト: caller9/raml-mocker
        _numberMocker: function (schema, floating) {
            var ret = null;
            /**
             * TODO:
             * minimum and exclusiveMinimum
             */
            if (schema.multipleOf) {
                var multipleMin = 1;
                var multipleMax = 5;

                if (schema.maximum !== undefined) {
                    if ((schema.maximum === schema.multipleOf && !schema.exclusiveMaximum) || (schema.maximum > schema.multipleOf)) {
                        multipleMax = Math.floor(schema.maximum / schema.multipleOf);
                    } else {
                        multipleMin = 0;
                        multipleMax = 0;
                    }
                }
                ret = schema.multipleOf * _.random(multipleMin, multipleMax, floating);
            } else {
                var minimum = schema.minimum || -99999999999;
                var maximum = schema.maximum || 99999999999;
                var gap = maximum - minimum;
                /**
                 *  - min: 0.000006
                 *  - max: 0.000009
                 */
                var minFloat = this._getMinFloat(minimum);
                minFloat = minFloat;
                if (minFloat < this._getMinFloat(maximum)) {
                    minFloat = this._getMinFloat(maximum);
                }
                var maxFloat = minFloat + _.random(0, 2);
                var littleGap = this._toFloat(_.random(0, gap, floating), _.random(minFloat, maxFloat)) / 10;
                ret = this._toFloat(_.random(minimum, maximum, floating), _.random(minFloat, maxFloat));
                if (ret === schema.maximum && schema.exclusiveMaximum) {
                    ret -= littleGap;
                }
                if (ret === schema.minimum && schema.exclusiveMinimum) {
                    ret += littleGap;
                }
            }
            return ret;
        },
コード例 #6
0
ファイル: utils.js プロジェクト: cryptobuks/tandem
exports.generateRandomStyleSheet = function (maxRules, maxDeclarations) {
    if (maxRules === void 0) { maxRules = 10; }
    if (maxDeclarations === void 0) { maxDeclarations = 20; }
    function createKeyFramesRule() {
        return " @keyframes " + generateRandomChar() + " {" +
            Array.from({ length: lodash_1.random(1, maxRules) }).map(function (v, i) { return Math.round(Math.random() * 100); }).sort().map(function (v) {
                return createKeyframeRule(v);
            }).join(" ") +
            "}";
    }
    function createKeyframeRule(perc) {
        return " " + perc + "% {" +
            Array.from({ length: lodash_1.random(1, maxDeclarations) }).map(function (v) {
                return " " + generateRandomChar() + ": " + generateRandomText(2) + ";";
            }).join("") +
            "}";
    }
    function createStyleRule() {
        return " ." + generateRandomChar() + " {" +
            Array.from({ length: lodash_1.random(1, maxDeclarations) }).map(function (v) {
                return " " + generateRandomChar() + ": " + generateRandomText(2) + ";";
            }).join("") +
            "}";
    }
    function createMediaRule() {
        return " @media " + generateRandomChar() + " {" +
            Array.from({ length: lodash_1.random(1, maxRules) }).map(function (v) {
                return lodash_1.sample([createStyleRule, createKeyFramesRule])();
            }).join(" ") +
            "}";
    }
    var randomStyleSheet = Array
        .from({ length: lodash_1.random(1, maxRules) })
        .map(function (v) { return lodash_1.sample([createStyleRule, createMediaRule, createKeyFramesRule])(); }).join(" ");
    return randomStyleSheet;
};
コード例 #7
0
ファイル: segmented_fetch.js プロジェクト: Adaptavist/kibana
      beforeEach(function () {
        totalTime = 0;
        totalHits = 0;
        maxHits = 0;
        maxScore = 0;
        aggregationKeys = [];

        queueSpy = sinon.spy(SegmentedFetch.prototype, '_processQueue');
        completeSpy = sinon.spy(SegmentedFetch.prototype, '_processQueueComplete');

        for (var i = 0; i < _.random(3, 6); i++) {
          queue.push('test-' + i);
        }

        sinon.stub(SegmentedFetch.prototype, '_extractQueue', function () {
          this.queue = queue.slice(0);
        });

        searchStrategy.getSourceStateFromRequest.returns(Promise.resolve({
          body: {
            size: 10
          }
        }));
      });
コード例 #8
0
  app.get('/netproj/getExcel', checkLogin, function (req, res) {
    var _tmpFileName = req.session.user.name + _.now() + _.random(0, 9999);
    NetprojService.getAll(function (err, netprojs) {
      if (err) {
        console.log(err);
        netprojs = [];
      }

      var data = NetprojService.getDataForExcel(netprojs);

      var buffer = xlsx.build([{name: _tmpFileName, data: data}]);

      fs.writeFile(path.join(__dirname, "../../public/excel/", _tmpFileName), buffer, function (err) {
        if (err) console.log(err);
        res.download(path.join(__dirname, "../../public/excel/", _tmpFileName), "网络部项目.xlsx", function (err) {
          if (err) console.log(err);
          fse.remove(path.join(__dirname, "../../public/excel/", _tmpFileName), function (err) {
            if (err) console.log(err)
          });
        });
      });

    });
  });
コード例 #9
0
ファイル: index.js プロジェクト: kyohei8/NoC-pixijs
const generateBox = (e) => {
  if(pressed){
    const { x, y } = e.data.global;
    const d = _.random(4);
    switch (d) {
      case 0:
        boxes.push(new Polygon(renderer, world, x, y));
        break;
      case 1:
        boxes.push(new Box(renderer, world, x, y));
        break;
      case 2:
        boxes.push(new Circle(renderer, world, x, y));
        break;
      case 3:
        boxes.push(new MultiShape(renderer, world, x, y));
        break;
      case 4:
        pairs.push(new Pair(renderer, world, x, y));
        break;
      default:
    }
  }
};
コード例 #10
0
function _createReceptionsForDoctor (doctor, date) {
  var receptions = [];
  //for (var i = 0; i<doctor.receptions.length; i++){
  //  doctor.receptions   [i].isBusy=_.random(3) > 2;
  //}
  for (var i = 9; i <= 18; i += 2) {
    var startTime = moment(date);
    startTime.hour(i);
    startTime.minute(0);
    startTime.millisecond(0);

    //var reception = _.each(doctor.receptions, function () { // eslint-disable-line no-loop-func
    //  //return moment(o.date).isSame(startTime.toDate());
    //  return _.random(3) > 2;
    //});

    if (_.random(4) > 2) {
      receptions.push({
        _id: '',
        time: startTime.toDate(),
        isBusy: true,
        isCurrentUser: false //req.user._id == reception.user
      });
    } else {
      receptions.push({
        _id: '',
        time: startTime.toDate(),
        isBusy: false,
        isCurrentUser: false
      });
    }
  }
  //var doctorClone = __.clone(doctor);
  doctor.receptions = receptions;
  return doctor;
}
コード例 #11
0
    it('is called with event and value on item click', () => {
      const randomIndex = _.random(options.length - 1)
      const randomResult = options[randomIndex]
      wrapperMount(<Search results={options} minCharacters={0} onResultSelect={spy} />)

      // open
      openSearchResults()
      searchResultsIsOpen()

      wrapper
        .find('SearchResult')
        .at(randomIndex)
        .simulate('click', nativeEvent)

      spy.should.have.been.calledOnce()
      spy.should.have.been.calledWithMatch(
        {},
        {
          minCharacters: 0,
          result: randomResult,
          results: options,
        },
      )
    })
コード例 #12
0
ファイル: hit_sort_fn.js プロジェクト: TinLe/kibana
  var runSortTest = function (dir, sortOpts) {
    var groupSize = _.random(10, 30);
    var total = sortOpts.length * groupSize;

    var hits = new Array(total);
    sortOpts = sortOpts.map(function (opt) {
      if (_.isArray(opt)) return opt;
      else return [opt];
    });
    var sortOptLength = sortOpts.length;

    for (var i = 0; i < hits.length; i++) {
      hits[i] = {
        _source: {},
        sort: sortOpts[i % sortOptLength]
      };
    }

    hits.sort(createHitSortFn(dir))
    .forEach(function (hit, i, hits) {
      var group = Math.floor(i / groupSize);
      expect(hit.sort).to.eql(sortOpts[group]);
    });
  };
コード例 #13
0
ファイル: allpaths.js プロジェクト: ankur123/FunStuff
 function insertHere( node, directon ) {
     node[ directon ] = new TreeNode( _.random ( 1, 5 ) );
 }
コード例 #14
0
ファイル: random.js プロジェクト: jobiaj/lodash-understanding
//Produces a random number between min and max (inclusive). If only one argument is provided a number between 0 and the given number is returned. If floating is true, or either min or max are floats, a floating-point number is returned instead of an integer.

var lodash = require('lodash');
console.log(lodash.random(0,5)) //produce a random integr bw 0-5
console.log(lodash.random(5, true)); //a floating-point number between 0 and 5
console.log(lodash.random(1.2, 5,2)); //a floating-point number between 1.2 and 5.2

コード例 #15
0
module.exports.randSipReq = function () {
    return SIP_REQS[lodash.random(11)];
};
コード例 #16
0
module.exports.randomPort2 = function() {
    return lodash.random(6000, 65535);
};
コード例 #17
0
 return () => _.random(min, max);
コード例 #18
0
ファイル: markers.js プロジェクト: Hendrick/kibana
 _.times(5, function () {
   var num = _.random(0, 100);
   var randColor = markerLayer._legendQuantizer(0);
   expect(randColor).to.equal(color);
 });
コード例 #19
0
ファイル: index.js プロジェクト: broguinn/bacon-workshop
function makeData() {
  return JSON.stringify({
    comments: _.times(_.random(3),
                i => _.times(_.random(1, 5), rw).join(' '))
  })
}
コード例 #20
0
ファイル: crossover.js プロジェクト: ypt/group-optimizer
 _.each(membersToReinsert, function(memberId){
   // randomly choose a group to re-insert the member
   var i = _.random(newSet.length - 1);
   newSet[i].push(memberId);
 });
コード例 #21
0
ファイル: utilsSpec.js プロジェクト: Alippok/ATMTechTest
function getRandomValueToMock( array ) {
  const maximum = ( array.length - 1 );
  const randomValue = _.random( 0, maximum );

  return array[ randomValue ];
}
コード例 #22
0
 return () => base + _.random(0, 24 * 60 * 60 * 1000);
コード例 #23
0
ファイル: index.js プロジェクト: broguinn/bacon-workshop
 i => _.times(_.random(1, 5), rw).join(' '))
コード例 #24
0
 getAreaTransitionData() {
   const areas = random(6, 10);
   return range(areas).map((area) => {
     return {x: area, y: random(2, 10)};
   });
 }
コード例 #25
0
ファイル: connector.js プロジェクト: nagykacsa/diploma
      function _handler(err, res, body) {
        if (err) {
          if (config.num_retries === 0) {
            return callback(err);
          }

          var ebck = config.ebackoff;

          config.num_retries--;
          config.ebackoff *= 2;
          self.log.debug('Waiting %d milliseconds before retrying...', ebck);

          return _.delay(function () {
            self._request(segments, method, callback, query, payload, data, headers, pipe, config);
          }, ebck);
        }

        switch (res.statusCode) {
        case 200:
          if (pipe) {
            pipe.end(new Buffer(body, 'binary'));
          } else {
            callback(err, body);
          }
          break;

        case 202:
        case 429:
          var wait = res.headers['retry-after'] * 1000 + _.random(0, 10000);
          self.log.debug('Status: %d, Retry-After: %d', res.statusCode, res.headers['retry-after']);
          self.log.debug('Waiting %d milliseconds before retrying...', wait);
          _.delay(function () {
            self._request(segments, method, callback, query, payload, data, headers, pipe, config);
          }, wait);
          break;

        case 301:
          opts.url = res.headers.location;
          // request(opts, _handler);
          self.queue.push({
            opts: opts,
            handler: _handler
          });
          break;

        case 302:
        	if(getUrl){
        		callback(res.headers.location);
        	} else {
        		request.get(res.headers.location, callback).pipe(pipe);
        	}
          break;

        case 400:
        case 403:
        case 404:
        case 405:
        case 409:
        case 412:
          callback(new Error(JSON.stringify(body)));
          break;

        case 401:
          //First check if stale access tokens still exist, and only then refresh.
          //Prevents multiple refreshes.
          if (self.isAuthenticated()) {
            self.log.debug('Access token expired. Refreshing...');
            self._revokeAccess();
            var tokenParams = {
                client_id: self.client_id,
                client_secret: self.client_secret,
                grant_type: 'refresh_token',
                refresh_token: self.refresh_token
              },
              authUrl = 'https://www.box.com/api/oauth2/token';

            request.post({
              url: authUrl,
              form: tokenParams,
              json: true
            }, function (err, res, body) {
              if (err) {
                return callback(err);
              }
              if (res.statusCode === 200) {
                self.log.debug('New tokens received.');
                self._setTokens(body);
                self._request(segments, method, callback, query, payload, data, headers, pipe, config);
              } else {
                callback(new Error(JSON.stringify(body)));
              }
            });
          } else {
            self.ready(function () {
              self._request(segments, method, callback, query, payload, data, headers, pipe, config);
            });
          }
          break;

        default:
          callback(err, body);
        }
      }
コード例 #26
0
 return range(areas).map((area) => {
   return {x: area, y: random(2, 10)};
 });
コード例 #27
0
 return _.times(n, () => (time += _.random(1, 60 * 60 * 1000)));
コード例 #28
0
 getStyles() {
   const colors = ["red", "orange", "gold", "tomato", "magenta", "purple"];
   return {
     fill: colors[random(0, 5)]
   };
 }
コード例 #29
0
ファイル: gameReducer.js プロジェクト: edast/dices
 dice: Array.from({length: state.numOfDice}, () => _.random(1, 6))
コード例 #30
0
module.exports.randomPort = function () {
    return lodash.random(1025, 65535);
};