Example #1
0
        return co (function *() {
            let resources = [];

            for (let i = 0; i < 15; i++) {
                resources.push(yield newResource(++self.inc));
            }

            _.reverse(resources);

            let res = yield request({ uri: self.uri, headers: { Range: `${type}=0-9` } });

            expect(res.statusCode).to.equal(206, util.errMsg(res, 'body'));
            expect(res.headers['accept-ranges']).to.equal(type, util.errMsg(res, 'body'));
            expect(res.headers['content-range']).to.equal(`${type} 0-9/15`, util.errMsg(res, 'body'));
            expect(res.body).to.be.an('array', util.errMsg(res, 'body')).with.length(9, util.errMsg(res, 'body'));
            expect(_.pick(res.body, self.properties)).to.eql(_.pick(_.slice(resources, 0, 9), self.properties), util.errMsg(res, 'body'));

            res = yield request({ uri: self.uri, headers: { Range: `${type}=9-15` } });

            expect(res.statusCode).to.equal(206, util.errMsg(res, 'body'));
            expect(res.headers['accept-ranges']).to.equal(type, util.errMsg(res, 'body'));
            expect(res.headers['content-range']).to.equal(`${type} 9-15/15`, util.errMsg(res, 'body'));
            expect(res.body).to.be.an('array', util.errMsg(res, 'body')).with.length(6, util.errMsg(res, 'body'));
            expect(_.pick(res.body, self.properties)).to.eql(_.pick(_.slice(resources, 9, 15), self.properties), util.errMsg(res, 'body'));

            res = yield request({ uri: self.uri, headers: { Range: `${type}=15-1000` } });
            expect(res.statusCode).to.equal(416, util.errMsg(res, 'body'));
            expect(res.headers['accept-ranges']).to.equal(type, util.errMsg(res, 'body'));
            expect(res.headers['content-range']).to.equal(`${type} */15`, util.errMsg(res, 'body'));
            expect(res.body).to.not.be.an('array', util.errMsg(res, 'body'));
        });
function storeContiguosDataValues(timeIn, valuesIn, callback) {
    var mins = timeIn.getMinutes()
    var secs = timeIn.getSeconds()
    var roundedToHour = timeIn
    roundedToHour.setMinutes(0)
    roundedToHour.setSeconds(0)

    var secondsLeftInThisHour = (60 * (59 - mins)) + (60 - secs);
    var howManyHours = Math.ceil((valuesIn.length - secondsLeftInThisHour) / 3600)
    
    //console.log('  >>  roundedToHour ', roundedToHour , '  > secondsLeftInThisHour ', secondsLeftInThisHour)
    updateValuesInOneChunck(timeIn, _.slice(valuesIn, 0, secondsLeftInThisHour), function (c) {
        //console.log(' c: ', c)
    })
    var leftValues = _.slice(valuesIn, secondsLeftInThisHour)
    emitter.emit('progress', evalProgress(valuesIn.length,leftValues.length))
    if (valuesIn.length > secondsLeftInThisHour) { //spans over
        var nextHourDate = new Date(roundedToHour.getTime() + (3600 * 1000))
        //console.log('  >>  howManyHours ', howManyHours , '  > nextHourDate ', nextHourDate)
        createOneHourChunks(nextHourDate, howManyHours, function (a) {
            //console.log(' Dates: ', JSON.stringify(a))
            _.each(a, function (b) {
                updateValuesInOneChunck(b, _.slice(valuesIn, 0, leftValues), function (c) {
                    //console.log(' c: ', c)
                })
                leftValues = _.slice(leftValues, 3600)
                emitter.emit('progress', evalProgress(valuesIn.length,leftValues.length))
            })
            callback(a)
        })
    } else { // All are in one chunk
        
    }
}
Example #3
0
var crossover = function(a, b) {
  // create child 1
  // choose crossing points
  var cxa1 = _.random(a.length - 1);
  var cxa2 = _.random(a.length - 1);

  var cloneA = _.clone(a, true);
  var cloneB = _.clone(b, true);

  // insert items from parent a crossing point into parent b
  var itemsToInsert = _.slice(cloneA, _.min([cxa1, cxa2]), _.max([cxa1, cxa2]));
  var son = crossoverInsert(cloneB, itemsToInsert);

  // create child 2
  // insert items from parent b crossing point into parent a
  var cxb1 = _.random(b.length - 1);
  var cxb2 = _.random(b.length - 1);

  var cloneA2 = _.clone(a, true);
  var cloneB2 = _.clone(b, true);

  // insert items from parent a crossing point into parent b
  var itemsToInsert2 = _.slice(cloneB, _.min([cxb1, cxb2]), _.max([cxb1, cxb2]));
  var daughter = crossoverInsert(cloneA2, itemsToInsert2);

  return [son, daughter];

};
  render() {
    const newsDefault = slice(this.state.news.items, 0, this.state.showNumberOfPosts);
    const newsMore = slice(this.state.news.items, this.state.showNumberOfPosts);

    return (
      <div className='news' >
        <div className='news-items' >
          <div className='news-items-headline' >
            <span>Nyt fra biblioteket</span>
          </div>
          <div className="news-default" >
            {this.mapNews(newsDefault)}
          </div>
          <div className={`news-more hide`} >
            {this.mapNews(newsMore)}
          </div>
        </div>
        <div className='news-items-link-container' >
          {newsMore.length &&
          (<a className='link show-more' href='#' onClick={this.showAllNews.bind(this)} >Se flere nyheder...</a>) || null
          }
        </div>
      </div>
    );
  }
 _.each(a, function (b) {
     updateValuesInOneChunck(b, _.slice(valuesIn, 0, leftValues), function (c) {
         //console.log(' c: ', c)
     })
     leftValues = _.slice(leftValues, 3600)
     emitter.emit('progress', evalProgress(valuesIn.length,leftValues.length))
 })
Example #6
0
function getZipcode(silicedBarcode) {
    let dropedBarcode = _.dropRight(silicedBarcode);
    if (dropedBarcode.length === 9) {
        return `${_.slice(dropedBarcode, 0, 5).join('')}-${_.slice(dropedBarcode, 5).join('')}`;
    }
    else return dropedBarcode.join('');
}
Example #7
0
  })).then((uris) => {
    // if replace is true, replace current uri when creating new list
    // else just add new components after the index;
    const selectedIndex = replace ? index : index + 1;

    return _.slice(data, 0, selectedIndex).concat(uris).concat(_.slice(data, index + 1));
  })
Example #8
0
    this.data.forEach(line => {
      const words = line.split(' ');

      // Start words
      const start = _.slice(words, 0, options.stateSize).join(' ');
      if (!_.includes(this.startWords, start)) {
        this.startWords.push(start);
      }

      // End words
      const end = _.slice(words, words.length - options.stateSize, words.length).join(' ');
      if (!_.includes(this.endWords, end)) {
        this.endWords.push(end);
      }

      // Build corpus
      for (let i = 0; i < words.length - 1; i++) {
        const curr = _.slice(words, i, i + options.stateSize).join(' ');
        const next = _.slice(words, i + options.stateSize, i + options.stateSize * 2).join(' ');
        if (!next || next.split(' ').length != options.stateSize) {
          continue;
        }

        // Add block to corpus
        if (this.corpus.hasOwnProperty(curr)) {
          if (!_.includes(this.corpus[curr], next)) {
            this.corpus[curr].push(next);
          }
        }
        else {
          this.corpus[curr] = [next];
        }
      }
    });
Example #9
0
    ngramProbability: function (words) {
        var self        = this,
            probability = 0,
            shouldLog   = true,
            gram        = words.join(' '),
            gramClass   = ngramUtil.getGramClass(words.length),
            validGram, precedenceGram;

        switch (gramClass) {
            case ngramUtil.UNIGRAM:
                let mainfreq =
                    !_.has(self.data[ngramUtil.UNIGRAM], gram) ? 0 : self.data[ngramUtil.UNIGRAM][gram];

                probability = (mainfreq + 1) / (self.count[ngramUtil.UNIGRAM] + self.size[ngramUtil.UNIGRAM]);
                break;

            case ngramUtil.BIGRAM:
                precedenceGram = `${words[0]}`;
                validGram      = _.has(self.data[ngramUtil.BIGRAM], gram);

                // Compute probability using Back-off model.
                if (!validGram) {
                    words.forEach(function (word) {
                        probability += self.ngramProbability([word]);
                    });
                    // Stupid back-off's alpha value.
                    probability += Math.log(0.4);
                    shouldLog = false;
                } else {
                    probability = self.data[ngramUtil.BIGRAM][gram] / self.data[ngramUtil.UNIGRAM][precedenceGram];
                }
                break;

            case ngramUtil.TRIGRAM:
                precedenceGram = `${words[0]} ${words[1]}`;
                validGram      = _.has(self.data[ngramUtil.TRIGRAM], gram);

                if (!validGram) {
                    let newGrams = [
                        _.slice(words, 0, 2),
                        _.slice(words, 1)
                    ];

                    // Compute probability using Back-off model.
                    newGrams.forEach(function (newGram) {
                        probability += self.ngramProbability(newGram);
                    });
                    // Stupid back-off's alpha value.
                    probability += Math.log(0.4);
                    shouldLog = false;
                } else {
                    probability = self.data[ngramUtil.TRIGRAM][gram] / self.data[ngramUtil.BIGRAM][precedenceGram];
                }
                break;
        }

        if (shouldLog) return Math.log(probability);
        else return probability;
    },
Example #10
0
/*
 * separates the text into numTokens-1, where the remaining words make up the final token
 * if the number of tokens is greater than the number of " " separated words, the array of 
 * " " separated words is returned without concatenation
 */
function getTokens(text, numTokens){
    var words = _(text).split(' ').compact().value();
    if(words.length <= numTokens) return words;

    var tokens = _.slice(words, 0, numTokens-1);
    var lastToken = _.slice(words, numTokens-1).join(" ");
    tokens.push(lastToken);

    return tokens;
}
Example #11
0
export function stripTail(urn) {
  const parts = urn.split(':');
  if (urn.startsWith('thirdeye:metric:')) {
    return _.slice(parts, 0, 3).join(':');
  }
  if (urn.startsWith('frontend:metric:')) {
    return _.slice(parts, 0, 4).join(':');
  }
  return urn;
}
Example #12
0
export function extractTail(urn) {
  const parts = urn.split(':');
  if (urn.startsWith('thirdeye:metric:')) {
    return _.slice(parts, 3);
  }
  if (urn.startsWith('frontend:metric:')) {
    return _.slice(parts, 4);
  }
  return [];
}
Example #13
0
    api.aggregate(endpoint, cube, params).then((data) => {

        var columns = Utils.buildC3Columns(data, groupFields, series, params.aggregates);
        var types = {};
        var c3Groups = _.map(_.slice(columns, 1), (column) => {return column[0]});
        _.each(_.slice(columns, 1), (column) => {
          types[column[0]] = chartType;
        });

        that.chart = c3.generate({
          bindto: that.wrapper,
          data: {
            names: Utils.buildC3BarNames(data, params.aggregates),
            columns: columns,
            color: function(color, d) {
              var c = d.id || d;
              if ((chartType == 'bar') && !series) {
                c = d.index;
              };
              return Utils.colorScale(c);
            },
            type: chartType || 'bar',
            x: _.first(_.first(columns)),
            groups: [c3Groups],
            types: types,
          },
          point: {
            show: false
          },
          grid: {
            focus: {
              show: false
            }
          },
          axis: {
            x: {
              type: 'category',
              tick: {
                culling: true,
                fit: true
              }
            },
            y: {
              tick: {
                format: d3.format("0,000"),
                culling: true,
                fit: true
              },
              lines: [{value: 0}]
            }
          }
        });

        this.emit('endAggregate', that, data);
      }
Example #14
0
function createSets(count){
  let mockedDataSet = mockDataSet(count);
  let limit = count*0.9;
  let trainingsSet = _.slice(mockedDataSet, 0, limit);
  let testSet = _.slice(mockedDataSet, limit);

  return {
    train: trainingsSet,
    test: testSet
  }
};
      function check(key, expected, server) {
        _.set(config, key, _.isArray(expected) ? _.slice(expected) : expected)
        var fromServer = {high_security: true}
        fromServer[key] = _.isArray(server) ? _.slice(server) : server

        expect(_.get(config, key)).to.deep.equal(expected)
        expect(fromServer).property(key).to.deep.equal(server)

        config.onConnect(fromServer)
        expect(_.get(config, key)).to.deep.equal(expected)
      }
function sherlock(arr) {
    for (let i=0; i < arr.length; ++i) {
        let left  = _.slice(arr, 0, i);
        let right = _.slice(arr, i+1, arr.length);
        console.log("%j: [%s] [%s]", i, left.toString(), right.toString());
        if ( sum(left) === sum(right) ) {
            return i;
        }
    }
    return null;
}
Example #17
0
        .on("end", function() {
            console.log(rawData.length + " items loaded");

            for(var i = 0; i < rawData.length; i++){
                var rawDataSlice = _.slice(rawData, i, i+45);
                xs = _.slice(XS, i, i+45);
                console.log("Items in current slice", rawDataSlice.length);
                processData(rawDataSlice);
                clearGlobals();
                i+= 44;
            }
        });
Example #18
0
File: game.js Project: wmzy/tactic
 /**
  * 分配角色
  */
 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');
 }
Example #19
0
function getP625(freqs, mags){
    // TODO these should be computed only once
    var point6Hz = getClosestIndex(freqs, 0.6);
    var twoPoint5Hz = getClosestIndex(freqs, 2.5);
    var fiveHz = getClosestIndex(freqs, 5);

    console.log(point6Hz, twoPoint5Hz, fiveHz);

    var numerator = average(_.slice(STRENGTH, point6Hz, twoPoint5Hz+1));
    var denominator = average(_.slice(STRENGTH, 0, fiveHz+1));

    return numerator/denominator;
}
Example #20
0
				return request(url + "/members", function(err, res, body) {
					if(err) return callback(err);
					if(res.statusCode != 200)
						return callback("HTTP response code: " + res.statusCode);

					var $ = cheerio.load(body);
					var officerCount = $(".rank_icon[title='Group Officer']").length;
					var modCount = $(".rank_icon[title='Group Moderator']").length;

					ownerCache = members[0];
					officerCache = _.slice(members, 1, officerCount + 1);
					modCache = _.slice(members, officerCount + 1, officerCount + modCount + 1);
					callback(null);
				});
Example #21
0
let newState = (state, action) => {
  let routineName = action.sectionName;
  let previous = slice(state, 0, action.index) || [];
  let current = state[action.index] || {};
  let newValue = {};
  newValue[routineName] = action.anArray;
  if (isEntryEmpty(newValue)) {
    newValue['timestamp'] = null;
  } else {
    newValue['timestamp'] = newValue['timestamp'] || Date.now();
  }
  let after = slice(state, action.index+1, state.length) || [];
  return concat(previous, [{ ...current, ...newValue }], after);
}
Example #22
0
getKeywords().then((sets) => {
  var brain = new deepqlearn.Brain(2, 2); // 3 inputs, 2 possible outputs (0,1)

  let count = 10000;
  let trainingsSet = count ? _.slice(sets.training, 0 , count) : sets.training;

  _.forEach(trainingsSet, (state, index) => {
    console.log(`${Math.round(index/trainingsSet.length*100)} %`);
    var action = brain.forward(state.input); // returns index of chosen action
    var reward = action === state.output ? 1 : 0;
    brain.backward([reward]);
  });

  brain.epsilon_test_time = 0.0; // don't make any more random choices
  brain.learning = false;
  // get an optimal action from the learned policy
  //var action = brain.forward(array_with_num_inputs_numbers);
  var rightCount = 0;

  _.forEach(sets.testing, (state) => {
    var action = brain.forward(state.input);
    if(action === state.output) rightCount += 1;
  });

  console.log('validation accurancy', rightCount/sets.testing.length );
}).catch(console.log);
 function error(code, token) {
     emitter.emit("warning", {
         code: code,
         token: token,
         data: _.slice(arguments, 2)
     });
 }
Example #24
0
      upyun.listDir('/ckeditor/picture/data', function(err, result) {
        var total = result.data.files.length;
        var files = _.slice(result.data.files, start, start + size);
        var list = _.map(files, function(item, i) { return { url:item.name }; });

        res.json({ state: 'SUCCESS', list: list, start: start, total: total });
      });
Example #25
0
      .then(function(user) {

        if( user == null )
          return next("User id not found!");

        if( user.Friends && user.Friends.length ){
          items.Total = user.Friends.length;
          items.Items = _.slice( _.sortBy( user.Friends, function(f){ return f; } ), skip, skip+limit );
        }

        if( items.Items.length < 1 )
          return callback(null, items);

        User.getAll( r.args(items.Items), { index:"UserID" })
        .run()
        .then(function(friends){

          friends = _.sortBy(friends, function(f){ return f.UserID });

          for (var i = 0; i < friends.length; i++) {

            delete friends[i]["Session"];
            delete friends[i]["CreateDate"];
            items.Items[i] = friends[i];
          }
          return callback(null, items);
        });
  })
Example #26
0
	this.addPlayer = function(player) {
		// additionCheck defined in child class!
		if (!(this._currentState instanceof RegistrationOpen)) {
			throw new RegistrationNotOpen();
		}
		if (this.hasRegistered(player)) throw new PlayerAlreadyRegistered();
		if (!this.registrationHook(player, _.slice(this._players), this.actions.RegistrationOpen)) {
			throw new AdditionCheckFailed();
		}

		// Add player
		this._players.push(player);
		this._playersAndKibitzers.push(player);

		// Link player to this game
		player.linkToGame(this);

		// Inform all players
		this.msgToAll({
			topic: 'player_registered',
			msg: player.id
		});			
		return true;
		
	}
Example #27
0
const rangePromise = async function (from, to) {
	return _.map(_.slice(_.keys(CACHE.neighborhoodsById), from, to + 1), function (id) {
		let v = CACHE.neighborhoodsById[id];
		v.id = `${id}`;
		return v;
	});
};
Example #28
0
 /**
  * Convert the separate R, G, B integer values to hex representation,
  * with the format '#RRGGBB'.
  */
 getHexColorValue() {
   let hexRepresentation = _.map(_.slice(this.props.value, 0, 3), (val)=>{
     let hexVal = val.toString(16);
     return hexVal.length === 1 ? '0' + hexVal : hexVal;
   }).join('');
   return '#' + hexRepresentation;
 }
Example #29
0
  process.stdin.on('data', async text => {
    const input = text.toString().trim().split(' ');

    if (input[0] == 'close'){
      logger.warn(`node ${node.username} closing`);
      nodes.map(e => e.close());
    }
    if (input[0] == 'exit'){
      process.exit();
    }

    if (input[0] == 'key'){
      const key = await node.findPublicKey(input[1]);
      console.log(key);
    }

    if (input[0] == 'buckets'){
      logger.warn(`node ${node.username}`);
      node.router.buckets.forEach((bucket, j) => {
        if (bucket.length > 0){
          console.log(j, bucket.filter(e => e !== undefined).map(e => e.username));
        }
      });
    }

    if(input[0] == 'message'){
      const message = _.slice(input, 2).join(' ') || 'hello';
      const response = await node.sendMessage(input[1], message);
      console.log('response', response);
    }

  });
Example #30
0
function sortFive(zipCodeArray){
    let withoutBar=_.slice(zipCodeArray,1,zipCodeArray.length-1);
    let fiveSortArray=_.chunk(withoutBar,5);
    return fiveSortArray.map((element)=>{
         return  element.join('');
    });
}