Example #1
0
    function findChanged(cb) {

        if (!config['supportChanged']) {
            return gulp.src('./tmp/**/*', {base: paths.tmp.dir})
                .pipe(gulp.dest(paths.dist.dir))
                .on('end', function () {
                    delTmp();
                })
        } else {
            var diff = changed('./tmp');
            var tmpSrc = [];

            if (!_.isEmpty(diff)) {

                //如果有reversion
                if (config['reversion'] && config['reversion']['available']) {
                    var keys = _.keys(diff);

                    //先取得 reversion 生成的manifest.json
                    var reversionManifest = require(path.resolve('./tmp/manifest.json'));

                    if (reversionManifest) {
                        reversionManifest = _.invert(reversionManifest);

                        reversionManifest = _.pick(reversionManifest, keys);

                        reversionManifest = _.invert(reversionManifest);

                        _.forEach(reversionManifest, function (item, index) {
                            tmpSrc.push('./tmp/' + item);
                            console.log('[changed:] ' + util.colors.blue(index));
                        });

                        //将新的 manifest.json 保存
                        fs.writeFileSync('./tmp/manifest.json', JSON.stringify(reversionManifest));

                        tmpSrc.push('./tmp/manifest.json');
                    }
                } else {
                    _.forEach(diff, function (item, index) {
                        tmpSrc.push('./tmp/' + index);
                        console.log('[changed:] ' + util.colors.blue(index));
                    });
                }

                return gulp.src(tmpSrc, {base: paths.tmp.dir})
                    .pipe(gulp.dest(paths.dist.dir))
                    .on('end', function () {
                        delTmp();
                    })

            } else {
                console.log('Nothing changed!');
                delTmp();
                cb();
            }
        }

    }
Example #2
0
function condercet(P){

     var sumMatrix = P.dominanceMatrix;
     var pairwise = [];
     var numToName = _.invert(P.candidateMap);
     for(var i=0;i < sumMatrix.length; i++){
        pairwise[i] = [];
	for(var j=0;j < sumMatrix.length;j++){
		pairwise[i].push(sumMatrix[i][j] - sumMatrix[j][i]);	 
        }
     }    

 var isVoteDeltaPositive = function isVoteDeltaPositive(voteDiff){
     return voteDiff >= 0;
 };

 var mapToScoringObjects = function mapToScoringObjects(candidate,index){
    return {
             "name": numToName[index],
	     "winner": _.every(candidate,isVoteDeltaPositive)
           };

 };
     
    return _.chain(pairwise)
               .map(mapToScoringObjects)
               .filter(function(candidate){ return candidate.winner;})
	       .pluck("name")
	       .value();
}
Example #3
0
  constructor(options) {
    REQUIRED_FIELDS.forEach(field => {
      if (!options[field]) {
        throw new ConfigurationError(`Missing configuration field ${field}`);
      }
    });

    validateChannelMapping(options.channelMapping);

    const web = new WebClient(options.token);
    const rtm = new RtmClient(options.token, { dataStore: new MemoryDataStore() });
    this.slack = { web, rtm };

    this.server = options.server;
    this.nickname = options.nickname;
    this.ircOptions = options.ircOptions;
    this.ircStatusNotices = options.ircStatusNotices || {};
    this.commandCharacters = options.commandCharacters || [];
    this.channels = _.values(options.channelMapping);
    this.muteSlackbot = options.muteSlackbot || false;
    this.muteBots = options.muteBots || true;

    const defaultUrl = 'http://api.adorable.io/avatars/48/$username.png';
    // Disable if it's set to false, override default with custom if available:
    this.avatarUrl = options.avatarUrl !== false && (options.avatarUrl || defaultUrl);
    this.channelMapping = {};

    // Remove channel passwords from the mapping and lowercase IRC channel names
    _.forOwn(options.channelMapping, (ircChan, slackChan) => {
      this.channelMapping[slackChan] = ircChan.split(' ')[0].toLowerCase();
    }, this);

    this.invertedMapping = _.invert(this.channelMapping);
    this.autoSendCommands = options.autoSendCommands || [];
  }
    return function (vis, resp) {
      nodes = {};
      links = {};
      lastNode = -1;

      var metric = vis.aggs.bySchemaGroup.metrics[0];
      var buckets = vis.aggs.bySchemaGroup.buckets;
      buckets = arrayToLinkedList(buckets);
      if (!buckets)  {
        return {'slices':{'nodes':[],'links':[]}};
      }

      var firstAgg = buckets[0];
      var aggData = resp.aggregations[firstAgg.id];

      if (!firstAgg._next) {
        notify.error('need more than one sub aggs');
      }

      processEntry(firstAgg, metric, aggData, -1);

      var invertNodes = _.invert(nodes);
      var chart = {
        'slices': {
          'nodes' : _.map(_.keys(invertNodes), function (k) { return {'name':invertNodes[k]}; }),
          'links' : _.map(_.keys(links), function (k) {
            var s = k.split('sankeysplitchar');
            return {'source': parseInt(s[0]), 'target': parseInt(s[1]), 'value': links[k]};
          })
        }
      };

      return chart;
    };
Example #5
0
File: bot.js Project: tcr/slack-irc
/**
 * An IRC bot, works as a middleman for all communication
 * @param {object} options - server, nickname, channelMapping, outgoingToken, incomingURL
 */
function Bot(options) {
  REQUIRED_FIELDS.forEach(function(field) {
    if (!options[field]) {
      throw new errors.ConfigurationError('Missing configuration field ' + field);
    }
  });
  validateChannelMapping(options.channelMapping);

  this.slack = new Slack(options.token);
  this._admin = options.admin;

  this.server = options.server;
  this.nickname = options.nickname;
  this.ircOptions = options.ircOptions;

  this.forward = options.forward;
  this.preserve = options.preserve || [];

  this.channels = _.values(options.channelMapping);

  this.channelMapping = {};

  // Remove channel passwords from the mapping
  _.forOwn(options.channelMapping, function(ircChan, slackChan) {
    this.channelMapping[slackChan] = ircChan.split(' ')[0];
  }, this);

  this.invertedMapping = _.invert(this.channelMapping);

  this.autoSendCommands = options.autoSendCommands || [];
}
Example #6
0
  constructor(options) {
    REQUIRED_FIELDS.forEach(field => {
      if (!options[field]) {
        throw new ConfigurationError(`Missing configuration field ${field}`);
      }
    });

    validateChannelMapping(options.channelMapping);

    this.discord = new discord.Client();

    this.server = options.server;
    this.nickname = options.nickname;
    this.ircOptions = options.ircOptions;
    this.discordEmail = options.discordEmail;
    this.discordPassword = options.discordPassword;
    this.commandCharacters = options.commandCharacters || [];
    this.channels = _.values(options.channelMapping);

    this.channelMapping = {};

    // Remove channel passwords from the mapping and lowercase IRC channel names
    _.forOwn(options.channelMapping, (ircChan, discordChan) => {
      this.channelMapping[discordChan] = ircChan.split(' ')[0].toLowerCase();
    });

    this.invertedMapping = _.invert(this.channelMapping);
    this.autoSendCommands = options.autoSendCommands || [];
  }
Example #7
0
  constructor(options) {
    REQUIRED_FIELDS.forEach(field => {
      if (!options[field]) {
        throw new ConfigurationError(`Missing configuration field ${field}`);
      }
    });

    validateChannelMapping(options.channelMapping);

    const web = new WebClient(options.token);
    const rtm = new RtmClient(options.token, { dataStore: new MemoryDataStore() });
    this.slack = { web, rtm };

    this.server = options.server;
    this.nickname = options.nickname;
    this.ircOptions = options.ircOptions;
    this.ircStatusNotices = options.ircStatusNotices || {};
    this.commandCharacters = options.commandCharacters || [];
    this.channels = _.values(options.channelMapping);
    this.muteSlackbot = options.muteSlackbot || false;

    this.channelMapping = {};

    // Remove channel passwords from the mapping and lowercase IRC channel names
    _.forOwn(options.channelMapping, (ircChan, slackChan) => {
      this.channelMapping[slackChan] = ircChan.split(' ')[0].toLowerCase();
    }, this);

    this.invertedMapping = _.invert(this.channelMapping);
    this.autoSendCommands = options.autoSendCommands || [];
  }
Example #8
0
// compute all the caches/indexes for subgraph match
function SubgraphMatchData(subgraphOuter, subgraphInner, vertexMap, unitOnly) {
  if(subgraphInner) {
    this.outer = subgraphOuter;
    this.inner = subgraphInner;
    this.outerEdges = {};
    this.innerEdges = subgraphInner.allEdges();
    this.vertexMap = vertexMap;
    this.inverseMap = _.invert(vertexMap);
    this.skipThisTime = [];
    this.unitOnly = unitOnly;

    var that = this;
    subgraphOuter.allEdges().forEach(function (edge) {
      var link = edge.link;
      if (link.isOpp) link = link.opposite;
      that.outerEdges[link.name] = that.outerEdges[link.name] || [];
      that.outerEdges[link.name].push(edge);
    });
  } else {
    // clone an existing obj
    var sgMD = subgraphOuter;
    this.outer = sgMD.outer;
    this.inner = sgMD.inner;
    this.outerEdges = _.clone(sgMD.outerEdges);
    //this.innerEdges = sgMD.innerEdges;
    //this.vertexMap = sgMD.vertexMap;
    //this.inverseMap = sgMD.inverseMap;
    //this.skipThisTime = sgMD.skipThisTime;
    this.unitOnly = sgMD.unitOnly;
  }
}
Example #9
0
                return $http.get(url).then(function (resp) {
                    const graph = resp.data;

                    // Build a mapping of buildbot buildername to taskcluster tasklabel for bbb tasks
                    const builderToTask = _.omit(_.invert(_.mapValues(graph, 'task.payload.buildername')), [undefined]);
                    const allLabels = _.keys(graph);

                    const tclabels = [];

                    buildernames.forEach(function (name) {
                        // The following has 2 cases that it accounts for
                        // 1. The name is a taskcluster task label, in which case we pass it on
                        // 2. The name is a buildbot buildername _scheduled_ through bbb, in which case we
                        //    translate it to the taskcluster label that triggers it.
                        name = builderToTask[name] || name;
                        if (allLabels.indexOf(name) !== -1) {
                            tclabels.push(name);
                        }
                    });

                    if (tclabels.length === 0) {
                        return;
                    }

                    return tcactions.load(decisionTaskId).then((results) => {
                        const actionTaskId = slugid();
                        // In this case we have actions.json tasks
                        if (results) {
                            const addjobstask = _.find(results.actions, { name: 'add-new-jobs' });
                            // We'll fall back to actions.yaml if this isn't true
                            if (addjobstask) {
                                return tcactions.submit({
                                    action: addjobstask,
                                    actionTaskId,
                                    decisionTaskId,
                                    taskId: null,
                                    task: null,
                                    input: { tasks: tclabels },
                                    staticActionVariables: results.staticActionVariables,
                                }).then(() => `Request sent to trigger new jobs via actions.json (${actionTaskId})`);
                            }
                        }

                        // Otherwise we'll figure things out with actions.yml
                        const url = queue.buildUrl(queue.getLatestArtifact, decisionTaskId, 'public/action.yml');
                        return $http.get(url).then(function (resp) {
                            let action = resp.data;
                            const template = $interpolate(action);
                            const taskLabels = tclabels.join(',');
                            action = template({
                                action: 'add-tasks',
                                action_args: `--decision-id=${decisionTaskId} --task-labels=${taskLabels}`,
                            });
                            const task = thTaskcluster.refreshTimestamps(jsyaml.safeLoad(action));
                            return queue.createTask(actionTaskId, task).then(() => `Request sent to trigger new jobs via actions.yml (${actionTaskId})`);
                        });
                    });
                });
Example #10
0
  it('should trigger a changeScore method on estimateChanger utility with score number value', function() {
    this.estimator.setState({menuOpen:true});
    var scores = TestUtils.scryRenderedDOMComponentsWithTag(this.estimator, 'button');
    var newScore = scores[scores.length - 1]; // Last score would be 'XL'

    TestUtils.Simulate.click(newScore);
    sinon.assert.calledOnce(this.stub.changeScore);
    sinon.assert.calledWith(this.stub.changeScore, [1,1], parseInt(_.invert(this.estimator.ESTIMATE_HASH)['XL'], 10));
  });
Example #11
0
 var getExtension = function (element) {
     if (!_REPRESENTATION_TO_EXTENSION_MAP) {
         _REPRESENTATION_TO_EXTENSION_MAP = _.invert(libraryActions.EXTENSION_TO_REPRESENTATION_MAP);
     }
     
     var representation = element.getPrimaryRepresentation();
         
     return representation && _REPRESENTATION_TO_EXTENSION_MAP[representation.type];
 };
Example #12
0
/**
 * Create an Error object from a status object
 * @private
 * @param {grpc~StatusObject} status The status object
 * @return {Error} The resulting Error
 */
function createStatusError(status) {
  let statusName = _.invert(constants.status)[status.code];
  let message = `${status.code} ${statusName}: ${status.details}`;
  let error = new Error(message);
  error.code = status.code;
  error.metadata = status.metadata;
  error.details = status.details;
  return error;
}
Example #13
0
  function set_content_type(name, value) {
    let duplicate = _.invert(_.get(N, 'shared.content_type', {}))[value];

    if (typeof duplicate !== 'undefined') {
      throw new Error(`Duplicate content type id=${value} for ${name} and ${duplicate}`);
    }

    _.set(N, 'shared.content_type.' + name, value);
  }
Example #14
0
					async.map(_.range(infoCount), unitsync.getInfoKey, function(e, keys){
						async.parallel(_.mapValues(_.pick(_.invert(keys), ['shortName', 'description']), function(idx){
							return _.partial(unitsync.getInfoValueString, parseInt(idx));
						}), function(e, info){
							getOptions(_.partial(unitsync.getSkirmishAIOptionCount, i), function(e, options){
								acc[info.shortName] = _.extend(_.omit(info, 'shortName'), { options: options });
								done(null, acc);
							});
						});
					});
  function checkResults(error, scoresForCandidates) {
    var candidates = _.keys(scoresForCandidates);
    var scores = _.values(scoresForCandidates);
    t.ok(candidates.length > 0, 'There is at least one candidate.');
    t.ok(candidates.every(isString), 'candidates are strings.');
    t.ok(scores.every(isNumber), 'scores are numbers.');

    var sortedCandidatesForScores = _.invert(scoresForCandidates);
    console.log(JSON.stringify(sortedCandidatesForScores, null, '  '));
  }
Example #16
0
/**
 * Sorts the ksys on an object
 * @param  {Object} obj     Object that has keys to be sorted
 * @param  {Object} options Optional parameter specifying orders for the function
 * @return {Object}         Object with keys sorted
 */
function sort(obj, options) {

  var opts = _.extend({ order: 'asc', property: false, keys: getKeys }, options);

  var sorted = {};
  var keys = [];
  var key;

  if(opts.property && opts.property !== false) {

    if(opts.property === true) {
      var inverted = _.invert(obj);
      keys = sortKeys(inverted, opts);

      for (var index in keys) {
        key = keys[index];
        sorted[inverted[key]] = key;
      }

    } else {

      var pairs = _.pairs(obj);
      var expanded = [];
      var keys = {};
      for (var i = 0; i < pairs.length; i++) {
        key = pairs[i][1][opts.property];
        keys[key] = pairs[i][0];
        expanded.push(pairs[i][1]);
      }

      expanded = _.sortBy(expanded, opts.property);

      if(opts.order.toLowerCase() === 'desc') {
        expanded.reverse();
      }

      for (var i = 0; i < expanded.length; i++) {
        var value = expanded[i][opts.property];
        sorted[keys[value]] = expanded[i];
      }
    }

  } else {

    keys = sortKeys(obj, opts);
    for (var index in keys) {
      key = keys[index];
      sorted[key] = obj[key];
    }

  }

  return sorted;
};
Example #17
0
File: paste.js Project: boothym/iD
    function doPaste() {
        d3.event.preventDefault();

        var baseGraph = context.graph(),
            mouse = context.mouse(),
            projection = context.projection,
            viewport = geoExtent(projection.clipExtent()).polygon();

        if (!geoPointInPolygon(mouse, viewport)) return;

        var extent = geoExtent(),
            oldIDs = context.copyIDs(),
            oldGraph = context.copyGraph(),
            newIDs = [];

        if (!oldIDs.length) return;

        var action = actionCopyEntities(oldIDs, oldGraph);
        context.perform(action);

        var copies = action.copies();
        var originals = _.invert(_.mapValues(copies, 'id'));
        for (var id in copies) {
            var oldEntity = oldGraph.entity(id),
                newEntity = copies[id];

            extent._extend(oldEntity.extent(oldGraph));

            // Exclude child nodes from newIDs if their parent way was also copied.
            var parents = context.graph().parentWays(newEntity),
                parentCopied = false;
            for (var i = 0; i < parents.length; i++) {
                if (originals[parents[i].id]) {
                    parentCopied = true;
                    break;
                }
            }

            if (!parentCopied) {
                newIDs.push(newEntity.id);
            }
        }

        // Put pasted objects where mouse pointer is..
        var center = projection(extent.center()),
            delta = [ mouse[0] - center[0], mouse[1] - center[1] ];

        context.perform(actionMove(newIDs, delta, projection));
        context.enter(modeMove(context, newIDs, baseGraph));
    }
Example #18
0
    return slide.children.some((child) => {
      if (!child.type || !invert(ElementTypes)[child.type]) {
        cb(new Error("Slide child must have a valid type"));

        return true;
      }

      if (!child.id || !child.props) {
        cb(new Error("Invalid slide child"));

        return true;
      }

      return false;
    });
Example #19
0
 const handleSingle = (instance) => {
   // Check that the url group has a defined mapping
   if (mappingList[url]) {
     const mapping = invertMap ? invert(mappingList[url]) : mappingList[url];
     const newObj = {};
     forIn(instance, (value, key) => {
       if (mapping[key]) {
         newObj[mapping[key]] = value;
       } else {
         newObj[key] = value;
       }
     });
     return newObj;
   }
   return instance;
 };
Example #20
0
 return this.transformFields(this.props.sections, field => {
   // Add the message to the field definition if the field doesn't
   // already have one.
   if(field.composite) {
     // Merge together all errors
     const compositeMapping = _.invert(field.composite)
     let combinedMessage = _(compositeMapping).map((msgs, extCode, internalField) => {
       return messages[extCode]
     }).compact().flatten().value()
     field.error = _.uniq(combinedMessage).join('; ')
     return field;
   }
   else {
     field.error = _.get(messages, field.code)
     return field;
   }
 });
Example #21
0
gameModel.methods.find_round_winner = function( round_number){
   cards_of_round =  [];
   self = this 
   _.forEach(self.playerSequence, function(player){
        cards_of_round.push(self.rounds[round_number][player])
   })
   console.log("model", cards_of_round)
   winning_card = find_winner(cards_of_round, this.trump);

   player_by_cards = _.invert(self.rounds[round_number]) 
   winner = player_by_cards[winning_card]
   this.round_winner[round_number] = winner
   this.rotate_player_sequence(winner)
   this.currentScore[winner] += 1
   this.currentRound += 1
   this.save()
   console.log("Winner: " + winner + "Winning card" + winning_card )
}
Example #22
0
IRCHandler.prototype.who = function(client, message) {
	if (!message.who || !message.channel) {
		return false;
	}

	var users = [],
		prefixes = _.invert(client.internal.capabilities.modes.prefixmodes);

	networkManager.addTab(client, message.channel, 'channel');
	// we'll update our internal channels cause we might be reconnecting after inactivity

	_.each(message.who, function(u) {
		var split = u.prefix.split('@'),
			mode = u.mode.replace(/[a-z0-9]/i, ''),
			user = {};

		user.username = split[0];
		user.hostname = split[1];
		user.nickname = u.nickname;
		user.modes = {};

		for (var i = 0, len = mode.length; i < len; i++) {
			var prefix = mode.charAt(i);
			user.modes[prefix] = prefixes[prefix];
		}
		// set the modes
		// normal for loop here cause we're just iterating a string, other cases I would use
		// _.each()

		user.prefix = eventManager.getPrefix(client, user).prefix;
		// set the current most highest ranking prefix

		users.push(user);
	});

	channelManager.insertUsers(client._id, message.channel, users, true)
		.then(function(inserts) {
			rpcHandler.push(client.internal.userId, 'channelUsers', inserts);
			// burst emit these instead of letting the oplog tailer handle it, it's too heavy
		});
};
Example #23
0
	/**
	 * Binds event handlers to the document for tracking a pending multi-select
	 * in response to a mousedown event occurring in a rendered block.
	 *
	 * @param {string} uid UID of the block where mousedown occurred.
	 *
	 * @return {void}
	 */
	onSelectionStart( uid ) {
		if ( ! this.props.isSelectionEnabled ) {
			return;
		}

		const boundaries = this.nodes[ uid ].getBoundingClientRect();

		// Create a uid to Y coördinate map.
		const uidToCoordMap = mapValues( this.nodes, ( node ) =>
			node.getBoundingClientRect().top - boundaries.top );

		// Cache a Y coördinate to uid map for use in `onPointerMove`.
		this.coordMap = invert( uidToCoordMap );
		// Cache an array of the Y coördinates for use in `onPointerMove`.
		// Sort the coördinates, as `this.nodes` will not necessarily reflect
		// the current block sequence.
		this.coordMapKeys = sortBy( Object.values( uidToCoordMap ) );
		this.selectionAtStart = uid;

		window.addEventListener( 'mousemove', this.onPointerMove );
		// Capture scroll on all elements.
		window.addEventListener( 'scroll', this.onScroll, true );
		window.addEventListener( 'mouseup', this.onSelectionEnd );
	}
Example #24
0
        STATIC: 'static'
    },
    PUNC: {
        INNER: '~',
        INSTANCE: '#',
        STATIC: '.'
    }
};

// For backwards compatibility, this enum must use lower-case keys
var scopeToPunc = exports.scopeToPunc = {
    'inner': SCOPE.PUNC.INNER,
    'instance': SCOPE.PUNC.INSTANCE,
    'static': SCOPE.PUNC.STATIC
};
var puncToScope = exports.puncToScope = _.invert(scopeToPunc);

var DEFAULT_SCOPE = SCOPE.NAMES.STATIC;
var SCOPE_PUNC = _.values(SCOPE.PUNC);
var SCOPE_PUNC_STRING = '[' + SCOPE_PUNC.join() + ']'; // ~#.
var REGEXP_LEADING_SCOPE = new RegExp('^(' + SCOPE_PUNC_STRING + ')');
var REGEXP_TRAILING_SCOPE = new RegExp('(' + SCOPE_PUNC_STRING + ')$');

var DESCRIPTION = '(?:(?:[ \\t]*\\-\\s*|\\s+)(\\S[\\s\\S]*))?$';
var REGEXP_DESCRIPTION = new RegExp(DESCRIPTION);
var REGEXP_NAME_DESCRIPTION = new RegExp('^(\\[[^\\]]+\\]|\\S+)' + DESCRIPTION);

function nameIsLongname(name, memberof) {
    var regexp = new RegExp('^' + escape(memberof) + SCOPE_PUNC_STRING);

    return regexp.test(name);
 /**
  * Fetch the current environment name.
  *
  * @returns {String|False}
  * @private
  */
 function _getEnv() {
     return _.invert(_envs)[_env] || '';
 }
Example #26
0
gameModel.methods.get_player_from_socket_id = function(socket_id){
    return _.invert(this.playerId)[socket_id];
}
    out += ' title=\"' + title + '\"';
  }
  return (out + '>' + text + '</a>');
};

const markedOptions = {
  sanitize: true,
  breaks: true,
  highlight: function (code) {
    return hljs.highlightAuto(code).value;
  },
  renderer: mdRenderer
};


const inversedEmojiCharacters = _.invert(_.mapValues(emojiCharacters, (e) => e.character));

const emojiVariants = _.map(Object.keys(inversedEmojiCharacters), function(name) {
  return name.replace(/\+/g, '\\+');
});

const emojiRegexp = new RegExp('(' + emojiVariants.join('|') + ')', 'gi');

const processText = function(text) {
  let markedText = marked(text, markedOptions);

  // need hack with replace because of https://github.com/Ranks/emojify.js/issues/127
  const noPTag = markedText.replace(/<p>/g, '<p> ');

  let emojifiedText = emojify
    .replace(noPTag.replace(emojiRegexp, (match) => ':' + inversedEmojiCharacters[match] + ':'));
    var combineData = function(countries, cities, tzData, windowsZones){
        var selectables = [];
        var timezoneMapping = {};
        var timezonesFound = {};

        var saveSelectable = function(key, name, fullName, tz, country, commonTz, sortInfo, poly){
            var tokens = fullName.toLowerCase().replace(re, '').split(' ');
            sortInfo = sortInfo !== undefined ? sortInfo : {};
            tokens = _.chain(tokens).union(getAbbrs(tz)).sortBy().value();
            var rv = {};
            if (poly !== undefined){
                rv = {
                    'k': key,
                    'd': fullName,
                    'z': tz,
                    'P': tokens.join(' '),
                    'sortinfo': sortInfo
                };
            }
            else{
                rv = {
                    'k': key,
                    'd': fullName,
                    'z': tz,
                    'T': tokens.join(' '),
                    'sortinfo': sortInfo
                };
            }
            if (name != fullName){
                rv.n = name;
            }
            if (country !== undefined){
                rv.c = country;
            }
            if (commonTz){
                rv.C = 1;
            }
            rv.s = score(rv);

            selectables.push(rv);
            };

        var getAbbrs = function(tz){
            var zone = tzData.zones[timezoneMapping[tz]];
            var abbrs = zone.split('|')[1].split(' ');
            var tzName = zone.split('|')[0];
            var abbrOffsetIndex = zone.split('|')[3].slice(-2);
            var returnVals = [];
            for (var i=0;i<abbrOffsetIndex.length; i++){
                returnVals.push(abbrs[parseInt(abbrOffsetIndex[i], 16)].toLowerCase());
            }
            return returnVals;
        };

        var score = function(item){
            var itemScore = 0;
            var isCanonical = function(fullName, abbrList){
                var words = fullName.trim().split(' +');
                var canonAbbr = "";
                if (words.length === 1){
                    canonAbbr = words[0].toLowerCase();
                }
                else{
                    for (var i=0;i < words.length; i++){
                        canonAbbr += words[i][0].toLowerCase();
                    }
                }
                if (abbrList.indexOf(canonAbbr) > -1){
                    return true;
                }
                return false;
            };
            if (item.hasOwnProperty('C')){
                itemScore += 5;
            }
            if (item.hasOwnProperty('T')){
                if (isCanonical(item.d, item.T.split(' '))){
                    itemScore += 5;
                }
            }
            else if (item.hasOwnProperty('P')){
                if (isCanonical(item.d, item.P.split(' '))){
                    itemScore += 5;
                }
            }
            if (item.hasOwnProperty('sortinfo') && Object.keys(item.sortinfo).length !== 0){
                if(item.sortinfo.city.isCapital){
                    itemScore += 1;
                }
                itemScore += Math.log(Math.max(item.sortinfo.city.population, 1)) / 50.0;
            }
            return -itemScore;
        };

        for (var i=0; i < tzData.zones.length; i++){
            var tz = tzData.zones[i].split('|')[0];
            if(!timezoneMapping.hasOwnProperty(tz)) {
                timezoneMapping[tz] = i;
            }
        }
        var reverseTzMap = _.invert(timezoneMapping);

        for (i=0; i < tzData.links.length; i++){
            var split = tzData.links[i].split('|');
            var target = split[0];
            var tz2 = split[1];
            timezoneMapping[tz2] = timezoneMapping[target];
        }


        for(var city in cities.english ){
            var keyName = (cities.english[city].country.toLowerCase() + ":" + cities.english[city].name + ':' + (cities.english[city].state || '')).replace(/\:+$/, '').toLowerCase() ;
            keyName = keyName.replace(' ', '-')
            .replace('_', '-')
            .replace('\'', '')
            .replace(',', '')
            .replace('(', '')
            .replace(')', '');
            var displayParts = [countries[cities.english[city].country].name];
            if (cities.english[city].hasOwnProperty('state') && cities.english[city].state !== undefined){
                displayParts.push(cities.english[city].state);
            }
            displayParts.push(cities.english[city].name);
            saveSelectable(keyName, cities.english[city].name, displayParts.join(', '), cities.english[city].timezone, cities.english[city].country, false, {city: cities.english[city]});
            timezonesFound[cities.english[city].timezone] = 1;
        }

        for(city in cities.poly ){
            var polyKeyName = (cities.poly[city].country.toLowerCase() + ":" + cities.poly[city].name + ':' + (cities.poly[city].state || '')).replace(/\:+$/, '').toLowerCase() ;
            polyKeyName = polyKeyName.replace(' ', '-')
            .replace('_', '-')
            .replace('\'', '')
            .replace(',', '')
            .replace('(', '')
            .replace(')', '');
            var polyDisplayParts = [countries[cities.poly[city].country].name];
            if (cities.poly[city].hasOwnProperty('state') && cities.poly[city].state !== undefined){
                polyDisplayParts.push(cities.poly[city].state);
            }
            polyDisplayParts.push(cities.poly[city].name);
            saveSelectable(polyKeyName, cities.poly[city].name, polyDisplayParts.join(', '), cities.poly[city].timezone, cities.poly[city].country, false, {city: cities.poly[city]}, true);
            timezonesFound[cities.poly[city].timezone] = 1;
        }

        for (var name in timezoneMapping){
            if (!timezonesFound.hasOwnProperty(name) && (name.toLowerCase().indexOf('/') === -1 || name.toLowerCase().indexOf('etc/') === 0)){
                var key = name.toLowerCase()
                .replace('_', '-')
                .replace('/', ':')
                .replace(',', '')
                .replace('\'', '');
                saveSelectable(key, name.split("/").slice(1).join('/'), name, name, undefined, false);
            }
        }

        for (var wName in windowsZones) {
            var wKey = wName.toLowerCase().split(' ').join('_')
            .replace('(', '')
            .replace(')', '')
            .replace(',', '');
            saveSelectable(wKey, wName, wName, windowsZones[wName], undefined, true);
        }


        var sortedSelectables = _.sortBy(selectables, ['s',
        function(p){
            return p.d.toLowerCase();
        }]);

        _.forEach(selectables, function(n){
            delete n.sortinfo;
        });

        return {
            'tzmap': reverseTzMap,
            'selectables': sortedSelectables
        };

    };
Example #29
0
    startIsLong = start instanceof Long
    endIsLong   = end instanceof Long;

    if (!startIsLong && endIsLong ) start = Long.fromNumber(start, false), startIsLong = true;
    if (!endIsLong && startIsLong ) end = Long.fromNumber(end, false), endIsLong = true;


    return ( startIsLong && endIsLong ) 
        ? ( end.subtract(start).toInt() ) / sample
        : ( end - start ) / sample

    debug("arguments for getDuration were weird. start: %d, end: %d, sample: %d", start, end, sample)

    return 0;
}

var BLOCK_TYPES = {
        0: 'STREAMINFO',
        1: 'PADDING',
        2: 'APPLICATION',
        3: 'SEEKTABLE',
        4: 'VORBIS_COMMENT',
        5: 'CUESHEET',
        6: 'PICTURE',
        127: 'invalid'
    }
  , TYPES = _.invert(BLOCK_TYPES)


Example #30
0
import $ from 'jquery';
import _ from 'lodash';
import Promise from 'bluebird';
import keyMap from 'ui/utils/key_map';
const reverseKeyMap = _.mapValues(_.invert(keyMap), _.ary(_.parseInt, 1));

/**
 * Simulate keyboard events in an element. This allows testing the way that
 * elements respond to keyboard input.
 *
 * # sequence style
 * keyboard events occur in a sequence, this array of events describe that sequence.
 *
 * ## event
 * an object with a type property, or a string which will be turned into a single press
 *
 * ## event types
 * ### press
 * represents a key press
 *   - `key`: the key for the button pressed
 *   - `events`: optional list of events that occur before this press completes
 *
 * ### wait
 * represents a pause in a sequence
 *   - `ms`: the number of milliseconds that the pause takes
 *
 * ### repeat
 * represents a key being repeated because it is held down. Should only exist as a
 * sub event of `press` events.
 *   - `count`: the number of times the repeat occurs
 *