Ejemplo n.º 1
0
    _.map(match, function (value, matchKey) {
        if (_.isArray(value)) {
            duplicateArray = _.where(value, {
                dest: 'dest',
                match: 'duplicate'
            });

            var duplicateNewIndexArray = _.uniq(_.pluck(duplicateArray, 'src_id'));
            var duplicateBaseIndexArray = _.uniq(_.pluck(duplicateArray, 'dest_id'));

            if (matchKey === 'social_history') {
                //console.log(match);
                //console.log(newRecord.social_history[0]);
                //console.log(baseRecord.social_history[4]);

            }

            var attributionRecord = _.filter(baseRecord[matchKey], function (object, objectIndex) {
                if (_.contains(duplicateBaseIndexArray, objectIndex.toString())) {
                    return true;
                } else {
                    return false;
                }
            });

            //Update Source attribution.
            async.each(attributionRecord,
                function (attribution, callback) {
                    record.duplicateEntry(matchKey, username, attribution._id, recordID, function (err) {
                        if (err) {
                            callback(err);
                        } else {
                            callback(null);
                        }
                    });
                },
                function (err) {
                    if (err) {
                        console.log(err);
                        //callback(err);
                    } else {
                        //console.log("updating source attribution - success");
                        //callback();
                    }
                });

            //Remove Duplicates from Entry List.
            var returnRecord = _.filter(newCloneRecord[matchKey], function (object, objectIndex) {
                if (_.contains(duplicateNewIndexArray, objectIndex.toString())) {
                    return false;
                } else {
                    return true;
                }
            });

            //Remove Duplicates from Match List.
            //use duplicate new index array to go through matches, and remove.
            var returnMatch = _.filter(match[matchKey], function (object, objectInex) {
                if (_.contains(duplicateNewIndexArray, object.src_id)) {
                    return false;
                } else {
                    return true;
                }
            });

            //console.log(returnMatch);

            //console.log(returnRecord);

            newCloneRecord[matchKey] = returnRecord;

            if (returnMatch === undefined) {
                returnMatch = [];
            }

            if (returnRecord === undefined) {
                returnRecord = [];
            }

            newMatch[matchKey] = returnMatch;

        } else {
            if (value.match === 'duplicate' && matchKey === 'demographics') {

                var attributionRecord = baseRecord[matchKey];

                async.each(attributionRecord, function (attribution, callback) {
                    record
                        .duplicateEntry(matchKey, username, attribution._id, recordID, function (err) {
                            if (err) {
                                callback(err);
                            } else {
                                callback(null);
                            }
                        });
                }, function (err) {
                    if (err) {
                        //callback(err);
                        console.log("err: " + err);
                    } else {
                        //callback();
                    }
                });

                delete newCloneRecord[matchKey];
                //delete newMatch[matchKey];
            } else if (matchKey === 'demographics') {
                newMatch[matchKey] = value;
            }

        }
    });
Ejemplo n.º 2
0
/**
 * Filter group patients to only include current memberships.
 *
 * A membership is current if todays date is between the from and to date.
 *
 * @param {array} groupPatients - list of group memberships.
 * @returns {array} - current group memberships.
 */
function filterGroupPatientsByCurrent(groupPatients) {
  return _.filter(groupPatients, function(x) {
    return x.current;
  });
}
Ejemplo n.º 3
0
  app.get('/test', function (req, res) {
    var test = _.filter(tests, function (t) {
      return req.query.js == t.file;
      // return t.originalUrl == req.path;
    });

    // if we do not have this test, 404?
    if (test.length == 0) {
      return res.status(404).send('Test not found.');
    } else {
      test = test[0];
    }

    // array of stylesheets to include in test page
    var stylesheets = options.stylesheets;

    // array of javascript files to include in test page
    var references = options.referenceTags ? utils.getDependencies(test.abs) : [];

    // determine if we want to generate coverage reports
    var coverage = typeof req.query.coverage !== 'undefined';

    // module name, used if this is a requirejs project
    var moduleName = (function () {
      if (options.requirejs) {
        return path.relative(options.modulesRelativeTo || options.root, test.abs).replace(/\\/g, '/').replace(/\.js$/, '');
      } else {
        return null;
      }
    }());

    // render the output of the http request
    var render = function (injectHTMLPath) {
      res.render('test', {
        modules: moduleName || '',
        injectHTML: injectHTMLPath,
        test: test,
        deps: references.js,
        stylesheets: stylesheets,
        coverage: coverage,
        phantom: req.query.phantom
      });
    };

    var injectHTML = options.injectHTML || '';

    // if we support reference tags, handle any found *.html and *.css reference tags
    if (options.referenceTags) {
      stylesheets = stylesheets.concat(_.map(references.css, utils.getDependencyUri));

      references.html.forEach(function (reference) {
        injectHTML += fs.readFileSync(reference);
      });
    }

    // look for a *.inject.html, if we find one, inject it
    try {
      // we do not check if the file exists, as that would result in two I/O hits
      // instead, just try to read it, if it throws an error, then ignore the error
      injectHTML += fs.readFileSync(test.abs.replace(/\.js$/, '.inject.html'));
    } catch (ex) {
      // no .inject.html exists, most likely, so move on
      // empty
    }

    // if the test has an inject URL, request it and inject it
    if (options.injectServer) {
      var injectUrl = options.injectServer + '?file=' + test.file; // TODO: sanitize the injectUrl

      request(injectUrl, function (err, resp, body) {
        if (err) {
          grunt.log.error('Inject server request failed', err);
          if (typeof body !== 'string') {
            body = '';
          }
        }

        render(injectHTML + body);
      });
    } else {
      // no inject url, so we have all the inject HTML we need, most tests go here, just render the response
      render(injectHTML);
    }
  });
 function getCurrentPlugins() {
   var plugins = grunt.config('localplugins') || [];
   return _.filter(plugins, '__isCurrent');
 }
Ejemplo n.º 5
0
export function filterOn(applications, constraint) {
  const unaccepted = _.filter(applications, (o) => (o[PMD.STATUS] === 0));
  const ret = _.filter(unaccepted, (o) =>
    (o[constraint[CONSTRAINT.ENTITY]] !== constraint[CONSTRAINT.ATTRIBUTE]));
  return ret;
}
      edit.load(session, {gameId, statusCodes: [200]}, (err, data) => {
        if (err) {
          return done(err);
        }
        expect(data).to.be.an('object');
        expect(data.gameplay).to.be.an('object');
        expect(data.properties).to.be.an('object');

        let properties = _.filter(data.properties, p => {
          switch (p.location.name) {
            case 'Chur':
            case 'Hinwil':
            case 'Trin':
            case 'Locarno':
            case 'Zermatt':
            case 'Grindelwald':
              return true;
          }
        });
        // Just check basics
        expect(properties.length).to.be(6);
        properties = _.sortBy(properties, p => {
          return p.location.name;
        });
        for (let i = 0; i < properties.length; i++) {
          properties[i].pricelist.priceRange           = 5;
          properties[i].pricelist.positionInPriceRange = i;
        }
        async.each(properties,
          function (p, cb) {
            edit.saveProperty(session, {gameId, statusCodes: [200]}, p, cb);
          },
          function (err) {
            if (err) {
              return done(err);
            }

            // Now we can test what we want...
            edit.savePositionInPricelist(session, {gameId, statusCodes: [200]}, properties, err => {
              if (err) {
                return done(err);
              }

              // Load again, new data must fit
              edit.load(session, {gameId, statusCodes: [200]}, (err, data) => {
                if (err) {
                  return done(err);
                }

                properties = _.filter(data.properties, p => {
                  switch (p.location.name) {
                    case 'Chur':
                    case 'Hinwil':
                    case 'Trin':
                    case 'Locarno':
                    case 'Zermatt':
                    case 'Grindelwald':
                      return true;
                  }
                });

                expect(properties.length).to.be(6);
                properties = _.sortBy(properties, p => {
                  return p.location.name;
                });
                for (let i = 0; i < properties.length; i++) {
                  expect(properties[i].pricelist.priceRange).to.be(5);
                  expect(properties[i].pricelist.positionInPriceRange).to.be(i);
                }

                done();
              });
            });
          });
      });
Ejemplo n.º 7
0
function isSubscribed(event, subscriber, subscriptions) {
  return !_.isEmpty(_.filter(subscriptions[event], subscriber));
};
Ejemplo n.º 8
0
 .then((f) => _.filter(f));
Ejemplo n.º 9
0
Archivo: save.js Proyecto: boothym/iD
    function save(changeset, tryAgain) {

        var osm = context.connection(),
            loading = uiLoading(context).message(t('save.uploading')).blocking(true),
            history = context.history(),
            origChanges = history.changes(actionDiscardTags(history.difference())),
            localGraph = context.graph(),
            remoteGraph = coreGraph(history.base(), true),
            modified = _.filter(history.difference().summary(), {changeType: 'modified'}),
            toCheck = _.map(_.map(modified, 'entity'), 'id'),
            toLoad = withChildNodes(toCheck, localGraph),
            conflicts = [],
            errors = [];

        if (!osm) return;

        if (!tryAgain) {
            history.perform(actionNoop());  // checkpoint
        }

        context.container().call(loading);

        if (toCheck.length) {
            osm.loadMultiple(toLoad, loaded);
        } else {
            upload();
        }


        function withChildNodes(ids, graph) {
            return _.uniq(_.reduce(ids, function(result, id) {
                var entity = graph.entity(id);
                if (entity.type === 'way') {
                    try {
                        var cn = graph.childNodes(entity);
                        result.push.apply(result, _.map(_.filter(cn, 'version'), 'id'));
                    } catch (err) {
                        /* eslint-disable no-console */
                        if (typeof console !== 'undefined') console.error(err);
                        /* eslint-enable no-console */
                    }
                }
                return result;
            }, _.clone(ids)));
        }


        // Reload modified entities into an alternate graph and check for conflicts..
        function loaded(err, result) {
            if (errors.length) return;

            if (err) {
                errors.push({
                    msg: err.responseText,
                    details: [ t('save.status_code', { code: err.status }) ]
                });
                showErrors();

            } else {
                var loadMore = [];
                _.each(result.data, function(entity) {
                    remoteGraph.replace(entity);
                    toLoad = _.without(toLoad, entity.id);

                    // Because loadMultiple doesn't download /full like loadEntity,
                    // need to also load children that aren't already being checked..
                    if (!entity.visible) return;
                    if (entity.type === 'way') {
                        loadMore.push.apply(loadMore,
                            _.difference(entity.nodes, toCheck, toLoad, loadMore));
                    } else if (entity.type === 'relation' && entity.isMultipolygon()) {
                        loadMore.push.apply(loadMore,
                            _.difference(_.map(entity.members, 'id'), toCheck, toLoad, loadMore));
                    }
                });

                if (loadMore.length) {
                    toLoad.push.apply(toLoad, loadMore);
                    osm.loadMultiple(loadMore, loaded);
                }

                if (!toLoad.length) {
                    checkConflicts();
                }
            }
        }


        function checkConflicts() {
            function choice(id, text, action) {
                return { id: id, text: text, action: function() { history.replace(action); } };
            }
            function formatUser(d) {
                return '<a href="' + osm.userURL(d) + '" target="_blank">' + d + '</a>';
            }
            function entityName(entity) {
                return utilDisplayName(entity) || (utilDisplayType(entity.id) + ' ' + entity.id);
            }

            function compareVersions(local, remote) {
                if (local.version !== remote.version) return false;

                if (local.type === 'way') {
                    var children = _.union(local.nodes, remote.nodes);

                    for (var i = 0; i < children.length; i++) {
                        var a = localGraph.hasEntity(children[i]),
                            b = remoteGraph.hasEntity(children[i]);

                        if (a && b && a.version !== b.version) return false;
                    }
                }

                return true;
            }

            _.each(toCheck, function(id) {
                var local = localGraph.entity(id),
                    remote = remoteGraph.entity(id);

                if (compareVersions(local, remote)) return;

                var action = actionMergeRemoteChanges,
                    merge = action(id, localGraph, remoteGraph, formatUser);

                history.replace(merge);

                var mergeConflicts = merge.conflicts();
                if (!mergeConflicts.length) return;  // merged safely

                var forceLocal = action(id, localGraph, remoteGraph).withOption('force_local'),
                    forceRemote = action(id, localGraph, remoteGraph).withOption('force_remote'),
                    keepMine = t('save.conflict.' + (remote.visible ? 'keep_local' : 'restore')),
                    keepTheirs = t('save.conflict.' + (remote.visible ? 'keep_remote' : 'delete'));

                conflicts.push({
                    id: id,
                    name: entityName(local),
                    details: mergeConflicts,
                    chosen: 1,
                    choices: [
                        choice(id, keepMine, forceLocal),
                        choice(id, keepTheirs, forceRemote)
                    ]
                });
            });

            upload();
        }


        function upload() {
            if (conflicts.length) {
                conflicts.sort(function(a,b) { return b.id.localeCompare(a.id); });
                showConflicts();
            } else if (errors.length) {
                showErrors();
            } else {
                var changes = history.changes(actionDiscardTags(history.difference()));
                if (changes.modified.length || changes.created.length || changes.deleted.length) {
                    osm.putChangeset(changeset, changes, uploadCallback);
                } else {        // changes were insignificant or reverted by user
                    d3.select('.inspector-wrap *').remove();
                    loading.close();
                    context.flush();
                    cancel();
                }
            }
        }


        function uploadCallback(err, changeset) {
            if (err) {
                errors.push({
                    msg: err.responseText,
                    details: [ t('save.status_code', { code: err.status }) ]
                });
                showErrors();
            } else {
                history.clearSaved();
                success(changeset);
                // Add delay to allow for postgres replication #1646 #2678
                window.setTimeout(function() {
                    d3.select('.inspector-wrap *').remove();
                    loading.close();
                    context.flush();
                }, 2500);
            }
        }


        function showConflicts() {
            var selection = context.container()
                .select('#sidebar')
                .append('div')
                .attr('class','sidebar-component');

            loading.close();

            selection.call(uiConflicts(context)
                .list(conflicts)
                .on('download', function() {
                    var data = JXON.stringify(changeset.update({ id: 'CHANGEME' }).osmChangeJXON(origChanges)),
                        win = window.open('data:text/xml,' + encodeURIComponent(data), '_blank');
                    win.focus();
                })
                .on('cancel', function() {
                    history.pop();
                    selection.remove();
                })
                .on('save', function() {
                    for (var i = 0; i < conflicts.length; i++) {
                        if (conflicts[i].chosen === 1) {  // user chose "keep theirs"
                            var entity = context.hasEntity(conflicts[i].id);
                            if (entity && entity.type === 'way') {
                                var children = _.uniq(entity.nodes);
                                for (var j = 0; j < children.length; j++) {
                                    history.replace(actionRevert(children[j]));
                                }
                            }
                            history.replace(actionRevert(conflicts[i].id));
                        }
                    }

                    selection.remove();
                    save(changeset, true);
                })
            );
        }


        function showErrors() {
            var selection = uiConfirm(context.container());

            history.pop();
            loading.close();

            selection
                .select('.modal-section.header')
                .append('h3')
                .text(t('save.error'));

            addErrors(selection, errors);
            selection.okButton();
        }


        function addErrors(selection, data) {
            var message = selection
                .select('.modal-section.message-text');

            var items = message
                .selectAll('.error-container')
                .data(data);

            var enter = items.enter()
                .append('div')
                .attr('class', 'error-container');

            enter
                .append('a')
                .attr('class', 'error-description')
                .attr('href', '#')
                .classed('hide-toggle', true)
                .text(function(d) { return d.msg || t('save.unknown_error_details'); })
                .on('click', function() {
                    var error = d3.select(this),
                        detail = d3.select(this.nextElementSibling),
                        exp = error.classed('expanded');

                    detail.style('display', exp ? 'none' : 'block');
                    error.classed('expanded', !exp);

                    d3.event.preventDefault();
                });

            var details = enter
                .append('div')
                .attr('class', 'error-detail-container')
                .style('display', 'none');

            details
                .append('ul')
                .attr('class', 'error-detail-list')
                .selectAll('li')
                .data(function(d) { return d.details || []; })
                .enter()
                .append('li')
                .attr('class', 'error-detail-item')
                .text(function(d) { return d; });

            items.exit()
                .remove();
        }

    }
  getInitialState () {
  	return {activeIndex: 0};
  },

  componentDidMount() {
		// this.showProgressHUD();
	},

	onResponderRelease (index){
		this.setState ({activeIndex : index});
	},

	render() {

		const {props} = this;
		const virtuals = _.filter(props.account.PaymentMethods, (m) => m.Type == 3)
		const banks = _.filter(props.account.PaymentMethods, (m) => m.Type == 2)
		const debits = _.filter(props.account.PaymentMethods, (m) => m.Type == 1)

		let paymentCards = [
			{
				title: "VIRTUAL BALANCE",
				type: "virtual_balance",
				backgroundColor: "#ff5d58",
				balance: (virtuals.length > 0 && virtuals[0].Balance ? numeral(numeral().unformat(virtuals[0].Balance.AccountBalance)).format('0,0.00') : ''),
				unit: (virtuals.length > 0 ? virtuals[0].Currency : 'USD'),
				number_of_cards: virtuals.length,
				img_src: require('../../../assets/images/home/virtual_balance.png'),
				padding_top: (screen_height-60)/3,
				is_active: false,
				index: 0
Ejemplo n.º 11
0
 function extractFirstPost(posts) {
     return _.filter(posts, {id: 1})[0];
 }
Ejemplo n.º 12
0
 exec.stderr.on("data", (stderr) => {
     filter(split(stderr, "\n"), (l) => !isEmpty(l)).forEach((stderr) => debug({stderr}));
 });
Ejemplo n.º 13
0
 exec.stdout.on("data", (stdout) => {
     filter(split(stdout, "\n"), (l) => !isEmpty(l)).forEach((stdout) => debug({stdout}));
 });
Ejemplo n.º 14
0
 var parseCountries = function(data) {
   $scope.countries = _.sortBy(_.filter(_.get(data, 'data.feed.countries'), {
     hasAddressFields: true
   }), 'descr');
 };
Ejemplo n.º 15
0
  render: function() {
    let nonLandsatLayers = _.filter(this.props.layers, l => {return ! l.isLandsat});
    let showNEXLayers = nonLandsatLayers.length > 0;
    return (
    <div>
      <Input type="checkbox" label="Snap to layer extent" checked={this.state.autoZoom} onChange={this.handleAutoZoom} />
      <PanelGroup defaultActiveKey="1" accordion={true} onSelect={this.handlePaneSelect}>
        <Panel header="Single Layer" eventKey="1" id={1}>
          <SingleLayer
            ref="single"
            rootUrl={this.props.rootUrl}
            layers={this.props.layers}
            activeLayerId={this.props.activeLayerId}
            showLayer={this.showLayer(1)}
            showLayerWithBreaks={this.showLayerWithBreaks(1)}
            showExtent={this.showExtent(1)} />
        </Panel>

        <Panel header="Change Detection" eventKey="2" id={2}>
          <DiffLayer
            ref="diff"
            rootUrl={this.props.rootUrl}
            layers={this.props.layers}
            showLayer={this.showLayer(2)}
            showLayerWithBreaks={this.showLayerWithBreaks(2)}
            showExtent={this.showExtent(2)} />
        </Panel>

        { showNEXLayers ?
          <Panel header="Layer to Layer Change Detection" eventKey="3" id={3}>
            <DiffLayers
              ref="layerDiff"
              rootUrl={this.props.rootUrl}
              layers={nonLandsatLayers}
              showLayer={this.showLayerWithBreaks(3)}
              showLayerWithBreaks={this.showLayerWithBreaks(3)}
              showExtent={this.showExtent(3)}
              showMaxState={this.props.showMaxState}
              hideMaxState={this.props.hideMaxState}
              showMaxAverageState={this.props.showMaxAverageState}
              hideMaxAverageState={this.props.hideMaxAverageState} />
          </Panel>
          : null
        }

        { showNEXLayers ?
          <Panel header="Average by State" eventKey="4" id={4}>
            <AverageByState
              ref="averageByState"
              rootUrl={this.props.rootUrl}
              layers={nonLandsatLayers}
              showLayerWithBreaks={this.showLayerWithBreaks(4)}
              showStateAverage={this.showStateAverage(4)}
              showExtent={this.showExtent(4)} />
          </Panel>
          : null
        }

        { showNEXLayers ?
          <Panel header="Average Change by State" eventKey="5" id={5}>
            <AverageDiffByState
              ref="averageDiffByState"
              rootUrl={this.props.rootUrl}
              layers={nonLandsatLayers}
              showLayerWithBreaks={this.showLayerWithBreaks(5)}
              showStateDiffAverage={this.showStateDiffAverage(5)}
              showExtent={this.showExtent(5)} />
          </Panel>
          : null
        }

      </PanelGroup>
    </div>)
  }
function findMethod(metabase, cls, method, args, isInstance, node, nodefail) {
	var entry = metabase.classes[cls],
		methods = _.clone(entry && entry.methods), // clone so we don't end up copying superclass methods into global metabase in-memory
		argcount = args.length;

	// search for super classes
	if (!methods[method]) {
		entry = metabase.classes[entry.superClass];
		while(entry) {
			entry.methods && Object.keys(entry.methods).forEach(function(name){
				if (!(name in methods)) {
					methods[name] = entry.methods[name];
				}
			});
			entry = metabase.classes[entry.superClass];
		}
	}

	// match up arg count as a first filtering mechanism
	// TODO Don't we need to handle varargs too? Looks like we don't record varargs in metabase
	var result = _.filter(methods[method], function(m){
		return m.args.length == argcount && isInstance == m.instance;
	});

	if (!result || result.length == 0) {
		return undefined;
	}

	if (result && result.length == 1) {
		return result[0];
	}
	
	// Try matching up arg types to disambiguate further
	var refined = _.filter(result, function(m){
		for (var i = 0, j = m.args.length; i < j; i++) {
			if (!typeMatches(m.args[i], args[i])) {
				return false;
			}
		}
		return true;
	});
	
	if (refined && refined.length == 1) {
		return refined[0];
	}
	
	var msg = "can't disambiguate arguments for method "+method.yellow,
		help = '  The following method signatures are available:\n\n'.yellow,
		guide = '';
	result.forEach(function(m) {
		guide += '\tHyperloop.method('+util.sanitizeSymbolName(cls).toLowerCase()+', ';
		guide += '\''+method+'(';
		var argt = [];
		m.args.forEach(function(arg) {
			argt.push(arg.type);
		});
		guide += argt.join(',');
		guide += ')\')\n';
	});
	help += guide.red.bold;
	nodefail(node, msg, help);
}
Ejemplo n.º 17
0
  return new Promise( function( resolve ) {
    var assertions       = this.options.assertions,
        entries          = {},
        offenders        = {},
        fulfilledPromise = _.filter( results, function( promise ) {
          return promise.isFulfilled();
        } ),
        fulFilledMetrics = fulfilledPromise.length && fulfilledPromise[ 0 ].value().json.metrics,
        entry,
        metric;

    _.each( fulFilledMetrics, function( value, key ) {
      if (
        typeof value !== 'undefined' &&
        typeof value !== 'string'
      ) {
        entries[ key ] = {
          values  : [],
          sum     : 0,
          min     : 0,
          max     : 0,
          median  : undefined,
          average : undefined
        };
      }
    } );

    // process all runs
    _.each( results, function( promise ) {
      if ( promise.isFulfilled() ) {
        this.grunt.log.ok( 'Phantomas execution successful.' );

        var promiseValue = promise.value(),
            metric;

        for ( metric in promiseValue.json.metrics ) {
          if (
            typeof promiseValue.json.metrics[ metric ] !== 'string' &&
            typeof entries[ metric ] !== 'undefined'
          ) {
            entries[ metric ].values.push( promiseValue.json.metrics[ metric ] );
          }
        }

        offenders = _.reduce( promiseValue.json.offenders, function( old, value, key ) {
          old[ key ] = _.uniq( ( old[ key ] || [] ).concat( value ) );

          return old;
        }, offenders );
      } else {
        this.grunt.log.error(
          'Phantomas execution not successful -> ' + promise.error()
        );
      }
    }, this );

    /**
     * Avoiding deep nesting for 'calculate stats'
     *
     * @param  {Number}  element element
     * @return {Boolean}
     */
    function filterEntryValues( element ) {
      return element !== null;
    }

    /**
     * Avoiding deep nesting for 'calculate stats'
     *
     * @param  {Number} a value A
     * @param  {Number} b value B
     * @return {Number}   sorting value
     */
    function sortEntryValues ( a, b ) {
      return a - b;
    }

    // calculate stats
    for ( metric in entries ) {
            entry = entries[ metric ];

      if ( typeof entry.values[ 0 ] !== 'string' ) {
        entry.values = entry.values
                        .filter( filterEntryValues )
                        .sort( sortEntryValues );
      }

      if ( entry.values.length === 0 ) {
        continue;
      }

      entry.min = entry.values.slice( 0, 1 ).pop();
      entry.max = entry.values.slice( -1 ).pop();

      if ( typeof entry.values[ 0 ] === 'string' ) {
        continue;
      }

      for ( var j = 0, len = entry.values.length++; j<len; j++ ) {
        entry.sum += entry.values[ j ];
      }

      entry.average = + ( len && ( entry.sum / len ).toFixed( 2 ) );
      entry.median = + ( ( (len % 2 === 0) ?
                      ( ( entry.values[ len >> 1 ] + entry.values[ len >> 1 + 1 ] ) / 2 ) :
                      entry.values[ len >> 1 ] ).toFixed( 2 ) );

      // pushed failed assertion
      // depending on median
      // to failedAssertions sum up
      if (
        typeof this.options.assertions[ metric ] !== 'undefined' &&
        _.indexOf( this.failedAssertions, metric ) === -1 &&
        (
          this.options.assertions[ metric ].type === '>' ||
          this.options.assertions[ metric ].type === '<'
        ) &&
        typeof this.options.assertions[ metric ].value === 'number'
      ) {
        if (
          this.options.assertions[ metric ].type === '>' &&
          entry.median > this.options.assertions[ metric ].value
        ) {
          this.failedAssertions.push( metric );
        }

        if (
          this.options.assertions[ metric ].type === '<' &&
          entry.median < this.options.assertions[ metric ].value
        ) {
          this.failedAssertions.push( metric );
        }
      }
    }

    resolve( {
      assertions       : assertions,
      metrics          : entries,
      offenders        : offenders
    } );
  }.bind( this ) );
Ejemplo n.º 18
0
var getActions = function (room) {
    return _.filter(_home.actions, function (action) {
        return action.room === room;
    });
};
Ejemplo n.º 19
0
HTMLRenderer.prototype.addResult = function(suite, test, result) {
  //console.log("add result", suite, test.name(), result)
  //this.resultList[suite].push({ suite: suite, test: test, result: result || {} })
  this.resultList.push({ suite: suite, test: test, result: result || {} });

  var columnHeads = this.columnHeads;
  var rows = this.rows;
  var resultList = this.resultList;

  // setup/update the comments in our Hands On Table
  //renderCellComments(rows, columnHeads, this.resultList, this.handsOnTable);

  var container = d3.select(".step-3-results");
  // rerender all the columns
  var columns = container.selectAll(".column")
    .data(columnHeads);

  function slugifyColumnHeader(name) {
    return name.toLowerCase().replace(/[^a-z0-9]/i, function(s) {
      var c = s.charCodeAt(0);
      if (c == 32) return "-";
      if (c >= 65 && c <= 90) s.toLowerCase();
      return c.toString(16).slice(-4);
    });
  }

  var columnsEnter = columns.enter().append("div").classed("column", true);
  // render the column header
  columnsEnter.append("div").classed("column-header", true)
    .text(function(d) { return d; } )
    .attr("title", function(d,i){
      return "Column " + i;
    })
    .attr("id", function(d) { return slugifyColumnHeader(d); });

  // Want to separate out tests that failed and tests that passed here

  // Summarize testsPassed.length, and then append all failed tests like normal

  // var passedResults = _.filter(resultList, function(d){
  //   return d.result.passed;
  // });

  var failedResults = _.filter(resultList, function(d) {
    return !d.result.passed;
  });

  //console.log("Passed list", passedResults)
  //console.log("Failed list", failedResults)

  /*
  var testsPassed = columnsEnter.append("h4")

  testsPassed.html("<div class='icon icon-check'></div> " + passedResults.length + " tests passed ")
  */

  var tests = columns.selectAll(".test")
    .data(function(column) {
      return failedResults.map(function(d) {
        return { test: d.test, result: d.result, suite: d.suite, column: column};
      });
    });


  var testsEnter = tests.enter().append("div")
    .attr("class", function(d) {
      return "test";// + (d.test.active ? " active" : "" )
    });

  testsEnter.append("div").classed("passfail", true);
  testsEnter.append("div").classed("summary", true)
    .on("mouseover", function(d) {
      var infoBtn = d3.select(this.parentNode).select(".info-btn");
      infoBtn.classed("opaque", false);
    })
    .on("mouseout", function(d) {
      var infoBtn = d3.select(this.parentNode).select(".info-btn");
      if (!infoBtn.classed("nonopaque")) infoBtn.classed("opaque", true);
    })
    .on("click", function(d) {
      var infoBtn = d3.select(this.parentNode).select(".info-btn");
      var infoWrapper = d3.select(this.parentNode).select(".info-wrapper");
      var isCollapsed = infoWrapper.classed("collapsed");
      var isOpaque = infoBtn.classed("nonopaque");
      infoWrapper.classed("collapsed", !isCollapsed);
      infoBtn.classed("nonopaque", !isOpaque);
    });
  testsEnter.append("div")
    .attr("class", "info-btn fa fa-info-circle opaque")
    .on("mouseover", function(d) {
      var infoBtn = d3.select(this.parentNode).select(".info-btn");
      infoBtn.classed("opaque", false);
    })
    .on("mouseout", function(d) {
      var infoBtn = d3.select(this.parentNode).select(".info-btn");
      if (!infoBtn.classed("nonopaque")) infoBtn.classed("opaque", true);
    });
  testsEnter.append("button").classed("filter-btn", true)
    .html("<i class='fa fa-filter'></i> Filter");
  var infoWrapper = testsEnter.append("div").classed("info-wrapper collapsed", true);
  infoWrapper.append("div").classed("description", true)
    .html(function(d) { return d.test.description();});
  infoWrapper.append("div").classed("conclusion", true)
    .text(function(d) { return d.test.conclusion();});
  infoWrapper.append("div").classed("visualization", true);

  var that = this;
  var filterResults = function (d) {
    that.renderFingerPrint({ test: d.test.name(), column: d.column });
    that.filterGrid({ highlightCells: d.result.highlightCells, column: d.column });
  };
  var clearFilteredResults = function(d) {
    that.renderFingerPrint();
    that.filterGrid();
  };
  that.clearFilteredResults = clearFilteredResults;

  tests.select(".filter-btn").on("click", function(d) {
    var isFiltered = d3.select(this.parentNode).classed("filtered");
    if (isFiltered) {
      d3.selectAll(".test").classed("filtered", false);
      d3.selectAll(".filter-btn").classed("nonopaque", false);
      clearFilteredResults(d);
      that.renderFingerPrint();
      d3.selectAll("#grid").classed("filtered-cells", false);
    } else {
      d3.selectAll(".test").classed("filtered", false);
      d3.selectAll(".filter-btn").classed("nonopaque", false);
      d3.select(this.parentNode).classed("filtered", true);
      d3.select(this).classed("nonopaque", true);
      filterResults(d);
      that.renderFingerPrint({ test: d.test.name(), column: d.column });
      d3.selectAll("#grid").classed("filtered-cells", true);
    }
  })
  .on("mouseover", function (d) {
    var isFiltered = d3.selectAll(".filtered")[0].length > 0;
    if (!isFiltered) that.renderFingerPrint({ test: d.test.name(), column: d.column });
  })
  .on("mouseout", function(d) {
    var isFiltered = d3.selectAll(".filtered")[0].length > 0;
    if (!isFiltered) that.renderFingerPrint();
  });

  tests.select("div.passfail").html(function(d) {
    var passFailIconHtml = "";
    var currentResultsColumn = d.column;
    var columnWise = d.result.columnWise;
    if (columnWise) {
      if (columnWise[currentResultsColumn] === 0) {
        passFailIconHtml += "<i class=\"fa fa-check-circle-o pass-icon\"></i>";
      } else if (columnWise[currentResultsColumn] > 0) {
        passFailIconHtml += "<i class=\"fa fa-flag-o fail-icon\"></i>";
      } else {
        passFailIconHtml += "<div class='icon icon-neutral'></div>";
      }
    }
    return passFailIconHtml;
  });

  tests.sort(function(a,b) {
    var aColumn = a.column;
    var aColumnWise = a.result.columnWise || {}; // not gauranteed to exist
    var bColumn = b.column;
    var bColumnWise = b.result.columnWise || {}; // not gauranteed to exist
    var aNum = aColumnWise[aColumn] || 0;
    var bNum = bColumnWise[bColumn] || 0;
    return bNum - aNum;
  });

  tests.select("div.summary").html(function(d) {
    var column = d.column;
    var name = d.test.name();
    var columnWise = d.result.columnWise || {}; // not gauranteed to exist
    var num = columnWise[column] || 0;
    var string = name + ": " + util.percent(num / rows.length);
    return string;
  }).classed("interesting", function(d) {
    var column = d.column;
    var columnWise = d.result.columnWise || {}; // not gauranteed to exist
    var num = columnWise[column] || 0;
    return !!num;
  })
  .attr("title", function(d){
    return d.test.description();
  });
  d3.selectAll("div.summary")
    .each(function() {
      d3.select(this.parentNode)
        .classed("hidden", false);
    });
  d3.selectAll("div.summary:not(.interesting)")
    .each(function() {
      d3.select(this.parentNode)
        .classed("hidden", true);
    });

  d3.selectAll("div.column")
    .each(function() {
      var totalTests = d3.select(this).selectAll(".test")[0].length;
      var hiddenTests = d3.select(this).selectAll(".test.hidden")[0].length;
      if (totalTests === hiddenTests) {
        d3.select(this).classed("hidden", true);
      } else {
        d3.select(this).classed("hidden", false);
      }
    });

  tests.select("div.conclusion").html(function(d) {
    return d.test.conclusion ? d.test.conclusion(d.result) : "";
  });

  /*
  var handsOnTable = this.handsOnTable
  tests.select("div.fingerprint").each(function(d) {
    if(!d.result.highlightCells || !d.result.highlightCells.length) return;
    var that = this;
    drawFingerPrint(d, handsOnTable, that);
  })
  */
};
Ejemplo n.º 20
0
 const shouldStopAnimation = () => {
   return !filter(stepperStyle, needContinue).length;
 };
Ejemplo n.º 21
0
 peterHFS.get('@Exam.'+examid, function(err, exam) {
     if(err) return reject(new errors.data.MongoDBError('find exam error : ', err));
     //过滤paper
     targetExam = exam;
     resolve(_.filter(exam['[papers]'], (paper) => paper.grade == gradeName));
 });
Ejemplo n.º 22
0
export function operationSplit(selectedIDs, context) {
    var vertices = _.filter(selectedIDs, function(entityId) {
        return context.geometry(entityId) === 'vertex';
    });

    var entityId = vertices[0],
        action = actionSplit(entityId);

    if (selectedIDs.length > 1) {
        action.limitWays(_.without(selectedIDs, entityId));
    }


    var operation = function() {
        var annotation;

        var ways = action.ways(context.graph());
        if (ways.length === 1) {
            annotation = t('operations.split.annotation.' + context.geometry(ways[0].id));
        } else {
            annotation = t('operations.split.annotation.multiple', {n: ways.length});
        }

        var difference = context.perform(action, annotation);
        context.enter(modeSelect(context, difference.extantIDs()));
    };


    operation.available = function() {
        return vertices.length === 1;
    };


    operation.disabled = function() {
        var reason;
        if (_.some(selectedIDs, context.hasHiddenConnections)) {
            reason = 'connected_to_hidden';
        }
        return action.disabled(context.graph()) || reason;
    };


    operation.tooltip = function() {
        var disable = operation.disabled();
        if (disable) {
            return t('operations.split.' + disable);
        }

        var ways = action.ways(context.graph());
        if (ways.length === 1) {
            return t('operations.split.description.' + context.geometry(ways[0].id));
        } else {
            return t('operations.split.description.multiple');
        }
    };


    operation.id = 'split';
    operation.keys = [t('operations.split.key')];
    operation.title = t('operations.split.title');


    return operation;
}
Ejemplo n.º 23
0
	grunt.registerMultiTask('webfont', 'Compile separate SVG files to webfont', function() {

		/**
		 * Winston to Grunt logger adapter.
		 */
		var logger = {
			warn: function() {
				grunt.log.warn.apply(null, arguments);
			},
			error: function() {
				grunt.warn.apply(null, arguments);
			},
			log: function() {
				grunt.log.writeln.apply(null, arguments);
			},
			verbose: function() {
				grunt.verbose.writeln.apply(null, arguments);
			}
		};

		var allDone = this.async();
		var params = this.data;
		var options = this.options();
		var md5 = crypto.createHash('md5');

		/*
		 * Check for `src` param on target config
		 */
		this.requiresConfig([this.name, this.target, 'src'].join('.'));

		/*
		 * Check for `dest` param on either target config or global options object
		 */
		if (_.isUndefined(params.dest) && _.isUndefined(options.dest)) {
			logger.warn('Required property ' + [this.name, this.target, 'dest'].join('.')
				+ ' or ' + [this.name, this.target, 'options.dest'].join('.') + ' missing.');
		}

		if (options.skip) {
			completeTask();
			return;
		}

		// Source files
		var files = _.filter(this.filesSrc, isSvgFile);
		if (!files.length) {
			logger.warn('Specified empty list of source SVG files.');
			completeTask();
			return;
		}

		// path must be a string, see https://nodejs.org/api/path.html#path_path_extname_path
		if (typeof options.template !== 'string') {
			options.template = '';
		}

		// Options
		var o = {
			logger: logger,
			fontBaseName: options.font || 'icons',
			destCss: options.destCss || params.destCss || params.dest,
			dest: options.dest || params.dest,
			relativeFontPath: options.relativeFontPath,
			addHashes: options.hashes !== false,
			addLigatures: options.ligatures === true,
			template: options.template,
			syntax: options.syntax || 'bem',
			templateOptions: options.templateOptions || {},
			stylesheet: options.stylesheet || path.extname(options.template).replace(/^\./, '') || 'css',
			htmlDemo: options.htmlDemo !== false,
			htmlDemoTemplate: options.htmlDemoTemplate,
			htmlDemoFilename: options.htmlDemoFilename,
			styles: optionToArray(options.styles, 'font,icon'),
			types: optionToArray(options.types, 'eot,woff,ttf'),
			order: optionToArray(options.order, wf.fontFormats),
			embed: options.embed === true ? ['woff'] : optionToArray(options.embed, false),
			rename: options.rename || path.basename,
			engine: options.engine || 'fontforge',
			autoHint: options.autoHint !== false,
			codepoints: options.codepoints,
			codepointsFile: options.codepointsFile,
			startCodepoint: options.startCodepoint || wf.UNICODE_PUA_START,
			ie7: options.ie7 === true,
			normalize: options.normalize === true,
			optimize: options.optimize === false ? false : true,
			round: options.round !== undefined ? options.round : 10e12,
			fontHeight: options.fontHeight !== undefined ? options.fontHeight : 512,
			descent: options.descent !== undefined ? options.descent : 64,
			version: options.version !== undefined ? options.version : false,
			cache: options.cache || path.join(__dirname, '..', '.cache'),
			callback: options.callback,
			customOutputs: options.customOutputs,
			execMaxBuffer: options.execMaxBuffer || 1024 * 200
		};

		o = _.extend(o, {
			fontName: o.fontBaseName,
			relativeFontPath: o.relativeFontPath || path.relative(o.destCss, o.dest),
			destHtml: options.destHtml || o.destCss,
			fontfaceStyles: has(o.styles, 'font'),
			baseStyles: has(o.styles, 'icon'),
			extraStyles: has(o.styles, 'extra'),
			files: files,
			glyphs: []
		});

		o.hash = getHash();
		o.fontFilename = template(options.fontFilename || o.fontBaseName, o);
		o.fontFamilyName = template(options.fontFamilyName || o.fontBaseName, o);

		// “Rename” files
		o.glyphs = o.files.map(function(file) {
			return o.rename(file).replace(path.extname(file), '');
		});

		// Check or generate codepoints
		// @todo Codepoint can be a Unicode code or character.
		var currentCodepoint = o.startCodepoint;
		if (!o.codepoints) o.codepoints = {};
		if (o.codepointsFile) o.codepoints = readCodepointsFromFile();
		o.glyphs.forEach(function(name) {
			if (!o.codepoints[name]) {
				o.codepoints[name] = getNextCodepoint();
			}
		});
		if (o.codepointsFile) saveCodepointsToFile();

		// Check if we need to generate font
		var previousHash = readHash(this.name, this.target);
		logger.verbose('New hash:', o.hash, '- previous hash:', previousHash);
		if (o.hash === previousHash) {
			logger.verbose('Config and source files weren’t changed since last run, checking resulting files...');
			var regenerationNeeded = false;

			var generatedFiles = wf.generatedFontFiles(o);
			if (!generatedFiles.length){
				regenerationNeeded = true;
			}
			else {
				generatedFiles.push(getDemoFilePath());
				generatedFiles.push(getCssFilePath());

				regenerationNeeded = _.some(generatedFiles, function(filename) {
					if (!filename) return false;
					if (!fs.existsSync(filename)) {
						logger.verbose('File', filename, ' is missed.');
						return true;
					}
					return false;
				});
			}
			if (!regenerationNeeded) {
				logger.log('Font ' + chalk.cyan(o.fontName) + ' wasn’t changed since last run.');
				completeTask();
				return;
			}
		}

		// Save new hash and run
		saveHash(this.name, this.target, o.hash);
		async.waterfall([
			createOutputDirs,
			cleanOutputDir,
			generateFont,
			generateWoff2Font,
			generateStylesheet,
			generateDemoHtml,
			generateCustomOutputs,
			printDone
		], completeTask);

		/**
		 * Call callback function if it was specified in the options.
		 */
		function completeTask() {
			if (o && _.isFunction(o.callback)) {
				o.callback(o.fontName, o.types, o.glyphs, o.hash);
			}
			allDone();
		}

		/**
		 * Calculate hash to flush browser cache.
		 * Hash is based on source SVG files contents, task options and grunt-webfont version.
		 *
		 * @return {String}
		 */
		function getHash() {
			// Source SVG files contents
			o.files.forEach(function(file) {
				md5.update(fs.readFileSync(file, 'utf8'));
			});

			// Options
			md5.update(JSON.stringify(o));

			// grunt-webfont version
			var packageJson = require('../package.json');
			md5.update(packageJson.version);

			// Templates
			if (o.template) {
				md5.update(fs.readFileSync(o.template, 'utf8'));
			}
			if (o.htmlDemoTemplate) {
				md5.update(fs.readFileSync(o.htmlDemoTemplate, 'utf8'));
			}

			return md5.digest('hex');
		}

		/**
		 * Create output directory
		 *
		 * @param {Function} done
		 */
		function createOutputDirs(done) {
			mkdirp.sync(o.destCss);
			mkdirp.sync(o.dest);
			done();
		}

		/**
		 * Clean output directory
		 *
		 * @param {Function} done
		 */
		function cleanOutputDir(done) {
			var htmlDemoFileMask = path.join(o.destCss, o.fontBaseName + '*.{' + o.stylesheet + ',html}');
			var files = glob.sync(htmlDemoFileMask).concat(wf.generatedFontFiles(o));
			async.forEach(files, function(file, next) {
				fs.unlink(file, next);
			}, done);
		}

		/**
		 * Generate font using selected engine
		 *
		 * @param {Function} done
		 */
		function generateFont(done) {
			var engine = require('./engines/' + o.engine);
			engine(o, function(result) {
				if (result === false) {
					// Font was not created, exit
					completeTask();
					return;
				}

				if (result) {
					o = _.extend(o, result);
				}

				done();
			});
		}

		/**
		 * Converts TTF font to WOFF2.
		 *
		 * @param {Function} done
		 */
		function generateWoff2Font(done) {
			if (!has(o.types, 'woff2')) {
				done();
				return;
			}

			// Read TTF font
			var ttfFontPath = wf.getFontPath(o, 'ttf');
			var ttfFont = fs.readFileSync(ttfFontPath);

			// Remove TTF font if not needed
			if (!has(o.types, 'ttf')) {
				fs.unlinkSync(ttfFontPath);
			}

			// Convert to WOFF2
			var woffFont = ttf2woff2(ttfFont);

			// Save
			var woff2FontPath = wf.getFontPath(o, 'woff2');
			fs.writeFile(woff2FontPath, woffFont, done);
		}

		/**
		 * Generate CSS
		 *
		 * @param {Function} done
		 */
		function generateStylesheet(done) {
			o.relativeFontPath = normalizePath(o.relativeFontPath);

			// Generate font URLs to use in @font-face
			var fontSrcs = [[], []];
			o.order.forEach(function(type) {
				if (!has(o.types, type)) return;
				wf.fontsSrcsMap[type].forEach(function(font, idx) {
					if (font) {
						fontSrcs[idx].push(generateFontSrc(type, font));
					}
				});
			});

			// Convert them to strings that could be used in CSS
			var fontSrcSeparator = option(wf.fontSrcSeparators, o.stylesheet);
			fontSrcs.forEach(function(font, idx) {
				// o.fontSrc1, o.fontSrc2
				o['fontSrc'+(idx+1)] = font.join(fontSrcSeparator);
			});
			o.fontRawSrcs = fontSrcs;

			// Convert codepoints to array of strings
			var codepoints = [];
			_.each(o.glyphs, function(name) {
				codepoints.push(o.codepoints[name].toString(16));
			});
			o.codepoints = codepoints;

			// Prepage glyph names to use as CSS classes
			o.glyphs = _.map(o.glyphs, classnameize);

			// Read JSON file corresponding to CSS template
			var templateJson = readTemplate(o.template, o.syntax, '.json', true);
			if (templateJson) o = _.extend(o, JSON.parse(templateJson.template));

			// Now override values with templateOptions
			if (o.templateOptions) o = _.extend(o, o.templateOptions);

			// Generate CSS
			var ext = path.extname(o.template) || '.css';  // Use extension of o.template file if given, or default to .css
			o.cssTemplate = readTemplate(o.template, o.syntax, ext);
			var cssContext = _.extend(o, {
				iconsStyles: true
			});

			var css = renderTemplate(o.cssTemplate, cssContext);

			// Fix CSS preprocessors comments: single line comments will be removed after compilation
			if (has(['sass', 'scss', 'less', 'styl'], o.stylesheet)) {
				css = css.replace(/\/\* *(.*?) *\*\//g, '// $1');
			}

			// Save file
			fs.writeFileSync(getCssFilePath(), css);

			done();
		}

		/**
		 * Gets the codepoints from the set filepath in o.codepointsFile
		 */
		function readCodepointsFromFile(){
			if (!o.codepointsFile) return {};
			if (!fs.existsSync(o.codepointsFile)){
				logger.verbose('Codepoints file not found');
				return {};
			}

			var buffer = fs.readFileSync(o.codepointsFile);
			return JSON.parse(buffer.toString());
		}

		/**
		 * Saves the codespoints to the set file
		 */
		function saveCodepointsToFile(){
			if (!o.codepointsFile) return;
			var codepointsToString = JSON.stringify(o.codepoints, null, 4);
			try {
				fs.writeFileSync(o.codepointsFile, codepointsToString);
				logger.verbose('Codepoints saved to file "' + o.codepointsFile + '".');
			} catch (err) {
				logger.error(err.message);
			}
		}

		/*
		 * Prepares base context for templates
		 */
		function prepareBaseTemplateContext() {
			var context = _.extend({}, o);
			return context;
		}

		/*
		 * Makes custom extends necessary for use with preparing the template context
		 * object for the HTML demo.
		 */
		function prepareHtmlTemplateContext() {

			var context = prepareBaseTemplateContext();

			var htmlStyles;

			// Prepare relative font paths for injection into @font-face refs in HTML
			var relativeRe = new RegExp(_s.escapeRegExp(o.relativeFontPath), 'g');
			var htmlRelativeFontPath = normalizePath(path.relative(o.destHtml, o.dest));
			var _fontSrc1 = o.fontSrc1.replace(relativeRe, htmlRelativeFontPath);
			var _fontSrc2 = o.fontSrc2.replace(relativeRe, htmlRelativeFontPath);

			_.extend(context, {
				fontSrc1: _fontSrc1,
				fontSrc2: _fontSrc2,
				fontfaceStyles: true,
				baseStyles: true,
				extraStyles: false,
				iconsStyles: true,
				stylesheet: 'css'
			});

			// Prepares CSS for injection into <style> tag at to of HTML
			htmlStyles = renderTemplate(o.cssTemplate, context);
			_.extend(context, {
				styles: htmlStyles
			});

			return context;
		}

		/*
		 * Iterator function used as callback by looping construct below to
		 * render "custom output" via mini configuration objects specified in
		 * the array `options.customOutputs`.
		 */
		function generateCustomOutput(outputConfig) {

			// Accesses context
			var context = prepareBaseTemplateContext();
			_.extend(context, outputConfig.context);

			// Prepares config attributes related to template filepath
			var templatePath = outputConfig.template;
			var extension = path.extname(templatePath);
			var syntax = outputConfig.syntax || '';

			// Renders template with given context
			var template = readTemplate(templatePath, syntax, extension);
			var output = renderTemplate(template, context);

			// Prepares config attributes related to destination filepath
			var dest = outputConfig.dest || o.dest;

			var filepath;
			var destParent;
			var destName;

			if (path.extname(dest) === '') {
				// If user specifies a directory, filename should be same as template
				destParent = dest;
				destName = path.basename(outputConfig.template);
				filepath = path.join(dest, destName);
			}
			else {
				// If user specifies a file, that is our filepath
				destParent = path.dirname(dest);
				filepath = dest;
			}

			// Ensure existence of parent directory and output to file as desired
			mkdirp.sync(destParent);
			fs.writeFileSync(filepath, output);
		}

		/*
		 * Iterates over entries in the `options.customOutputs` object and,
		 * on a config-by-config basis, generates the desired results.
		 */
		function generateCustomOutputs(done) {

			if (!o.customOutputs || o.customOutputs.length < 1) {
				done();
				return;
			}

			_.each(o.customOutputs, generateCustomOutput);
			done();
		}

		/**
		 * Generate HTML demo page
		 *
		 * @param {Function} done
		 */
		function generateDemoHtml(done) {
			if (!o.htmlDemo) {
				done();
				return;
			}

			var context = prepareHtmlTemplateContext();

			// Generate HTML
			var demoTemplate = readTemplate(o.htmlDemoTemplate, 'demo', '.html');
			var demo = renderTemplate(demoTemplate, context);

			mkdirp(getDemoPath(), function(err) {
				if (err) {
					logger.log(err);
					return;
				}
				// Save file
				fs.writeFileSync(getDemoFilePath(), demo);
				done();
			});

		}

		/**
		 * Print log
		 *
		 * @param {Function} done
		 */
		function printDone(done) {
			logger.log('Font ' + chalk.cyan(o.fontName) + ' with ' + o.glyphs.length + ' glyphs created.');
			done();
		}


		/**
		 * Helpers
		 */

		/**
		 * Convert a string of comma separated words into an array
		 *
		 * @param {String} val Input string
		 * @param {String} defVal Default value
		 * @return {Array}
		 */
		function optionToArray(val, defVal) {
			if (val === undefined) {
				val = defVal;
			}
			if (!val) {
				return [];
			}
			if (typeof val !== 'string') {
				return val;
			}
			return val.split(',').map(_.trim);
		}

		/**
		 * Check if a value exists in an array
		 *
		 * @param {Array} haystack Array to find the needle in
		 * @param {Mixed} needle Value to find
		 * @return {Boolean} Needle was found
		 */
		function has(haystack, needle) {
			return haystack.indexOf(needle) !== -1;
		}

		/**
		 * Return a specified option if it exists in an object or `_default` otherwise
		 *
		 * @param {Object} map Options object
		 * @param {String} key Option to find in the object
		 * @return {Mixed}
		 */
		function option(map, key) {
			if (key in map) {
				return map[key];
			}
			else {
				return map._default;
			}
		}

		/**
		 * Find next unused codepoint.
		 *
		 * @return {Integer}
		 */
		function getNextCodepoint() {
			while (_.includes(o.codepoints, currentCodepoint)) {
				currentCodepoint++;
			}
			return currentCodepoint;
		}

		/**
		 * Check whether file is SVG or not
		 *
		 * @param {String} filepath File path
		 * @return {Boolean}
		 */
		function isSvgFile(filepath) {
			return path.extname(filepath).toLowerCase() === '.svg';
		}

		/**
		 * Convert font file to data:uri and remove source file
		 *
		 * @param {String} fontFile Font file path
		 * @return {String} Base64 encoded string
		 */
		function embedFont(fontFile) {
			// Convert to data:uri
			var dataUri = fs.readFileSync(fontFile, 'base64');
			var type = path.extname(fontFile).substring(1);
			var fontUrl = 'data:application/x-font-' + type + ';charset=utf-8;base64,' + dataUri;

			// Remove font file
			fs.unlinkSync(fontFile);

			return fontUrl;
		}

		/**
		 * Append a slash to end of a filepath if it not exists and make all slashes forward
		 *
		 * @param {String} filepath File path
		 * @return {String}
		 */
		function normalizePath(filepath) {
			if (!filepath.length) return filepath;

			// Make all slashes forward
			filepath = filepath.replace(/\\/g, '/');

			// Make sure path ends with a slash
			if (!_s.endsWith(filepath, '/')) {
				filepath += '/';
			}

			return filepath;
		}

		/**
		 * Generate URL for @font-face
		 *
		 * @param {String} type Type of font
		 * @param {Object} font URL or Base64 string
		 * @return {String}
		 */
		function generateFontSrc(type, font) {
			var filename = template(o.fontFilename + font.ext, o);

			var url;
			if (font.embeddable && has(o.embed, type)) {
				url = embedFont(path.join(o.dest, filename));
			}
			else {
				url = o.relativeFontPath + filename;
				if (o.addHashes) {
					if (url.indexOf('#iefix') === -1) {  // Do not add hashes for OldIE
						// Put hash at the end of an URL or before #hash
						url = url.replace(/(#|$)/, '?' + o.hash + '$1');
					}
				}
			}

			var src = 'url("' + url + '")';
			if (font.format) src += ' format("' + font.format + '")';

			return src;
		}

		/**
		 * Reat the template file
		 *
		 * @param {String} template Template file path
		 * @param {String} syntax Syntax (bem, bootstrap, etc.)
		 * @param {String} ext Extention of the template
		 * @return {Object} {filename: 'Template filename', template: 'Template code'}
		 */
		function readTemplate(template, syntax, ext, optional) {
			var filename = template
				? path.resolve(template.replace(path.extname(template), ext))
				: path.join(__dirname, 'templates/' + syntax + ext)
			;
			if (fs.existsSync(filename)) {
				return {
					filename: filename,
					template: fs.readFileSync(filename, 'utf8')
				};
			}
			else if (!optional) {
				return grunt.fail.fatal('Cannot find template at path: ' + filename);
			}
		}

		/**
		 * Render template with error reporting
		 *
		 * @param {Object} template {filename: 'Template filename', template: 'Template code'}
		 * @param {Object} context Template context
		 * @return {String}
		 */
		function renderTemplate(template, context) {
			try {
				var func = _.template(template.template);
				return func(context);
			}
			catch (e) {
				grunt.fail.fatal('Error while rendering template ' + template.filename + ': ' + e.message);
			}
		}

		/**
		 * Basic template function: replaces {variables}
		 *
		 * @param {Template} tmpl Template code
		 * @param {Object} context Values object
		 * @return {String}
		 */
		function template(tmpl, context) {
			return tmpl.replace(/\{([^\}]+)\}/g, function(m, key) {
				return context[key];
			});
		}

		/**
		 * Prepare string to use as CSS class name
		 *
		 * @param {String} str
		 * @return {String}
		 */
		function classnameize(str) {
			return _s.trim(str).replace(/\s+/g, '-');
		}

		/**
		 * Return path of CSS file.
		 *
		 * @return {String}
		 */
		function getCssFilePath() {
			var cssFilePrefix = option(wf.cssFilePrefixes, o.stylesheet);
			return path.join(o.destCss, cssFilePrefix + o.fontBaseName + '.' + o.stylesheet);
		}

		/**
		 * Return path of HTML demo file or `null` if its generation was disabled.
		 *
		 * @return {String}
		 */
		function getDemoFilePath() {
			if (!o.htmlDemo) return null;
			var name = o.htmlDemoFilename || o.fontBaseName;
			return path.join(o.destHtml, name + '.html');
		}

		/**
		 * Return path of HTML demo file or `null` if feature was disabled
		 */
		function getDemoPath() {
			if (!o.htmlDemo) return null;
			return o.destHtml;
		}

		/**
		 * Save hash to cache file.
		 *
		 * @param {String} name Task name (webfont).
		 * @param {String} target Task target name.
		 * @param {String} hash Hash.
		 */
		function saveHash(name, target, hash) {
			var filepath = getHashPath(name, target);
			mkdirp.sync(path.dirname(filepath));
			fs.writeFileSync(filepath, hash);
		}

		/**
		 * Read hash from cache file or `null` if file don’t exist.
		 *
		 * @param {String} name Task name (webfont).
		 * @param {String} target Task target name.
		 * @return {String}
		 */
		function readHash(name, target) {
			var filepath = getHashPath(name, target);
			if (fs.existsSync(filepath)) {
				return fs.readFileSync(filepath, 'utf8');
			}
			return null;
		}

		/**
		 * Return path to cache file.
		 *
		 * @param {String} name Task name (webfont).
		 * @param {String} target Task target name.
		 * @return {String}
		 */
		function getHashPath(name, target) {
			return path.join(o.cache, name, target, 'hash');
		}
	});
Ejemplo n.º 24
0
 var todos = _.flatten(_.map(diff, function (file) {
   var addedLines = _.filter(file.lines, "add");
   var lineTodos = _.map(addedLines, lineToTodoMapper(file.to, sha, conf));
   // keep only those with required field
   return _.filter(lineTodos, "title");
 }));
Ejemplo n.º 25
0
router.get('/cards', function(req, res) {
  var validColors = ['W','U','G','R','B','C'];
  var filteredCards = allCards;
  var color = req.query.color;
  var type = req.query.type;
  var subType = req.query.subtype;
  var cmc = req.query.cmc;

  // Card Color
  if (color) {
    if (validColors.indexOf(color) === -1) {
      return res.end('Invalid color');
    }
    filteredCards = _.filter(filteredCards, c => {
      if ('colorIdentity' in c) {
        // card has a color
        return c.colorIdentity.indexOf(color) !== -1;
      } else if (color === 'C') {
        // colorless card
        return true;
      }

      return false;
    });
  }
  
  // Card Type
  if (type) {
    filteredCards = _.filter(filteredCards, c => 'types' in c && c.types.indexOf(type) !== -1);
  }

  // Card Subtype. e.g. Dragon
  if (subType) {
    filteredCards = _.filter(filteredCards, c => 'subtypes' in c && c.subtypes.indexOf(subType) !== -1);
  }

  // Converted Mana Cost
  if (cmc) {
    cmc = parseInt(cmc, 10);
    filteredCards = _.filter(filteredCards, c => 'cmc' in c && c.cmc === cmc);
  }

  // map to set
  filteredCards = _.map(filteredCards, c => {
    if ('printings' in c) {
      var firstSet = c.printings[0];
      c.firstPrinted = parseInt(moment(_.find(allSets, { code: firstSet }).releaseDate, 'YYYY-MM-DD').format('x'), 10);
    }
    
    // prune some heavy properties
    delete c['rulings'];
    delete c['legalities'];

    return c;
  });
  
  res.json({
    request: {
      color: color,
      type: type,
      subType: subType,
      cmc: cmc
    },
    count: filteredCards.length,
    data: _.orderBy(filteredCards, 'firstPrinted')
  });

});
Ejemplo n.º 26
0
// TODO Better heuristic for code vs words detection

// Simple heuristic to detect if a title is really a title or some valid code
// String → Boolean
function isCode (string) {
  // If symbols are more than 20% of the code, it may be code more than human text
  var symbols = _.filter(string, isSymbol);

  return symbols.length / string.length > 0.20;
}
Ejemplo n.º 27
0
/**
 * Filter group patients by group type.
 *
 * @param {array} groupPatients - list of group memberships.
 * @param {string} groupType - type of group.
 * @returns {array} - memberships of groups of the specified type.
 */
function filterGroupPatientsByType(groupPatients, groupType) {
  return _.filter(groupPatients, function(x) {
    return x.group.type === groupType;
  });
}
Ejemplo n.º 28
0
  Handlebars.registerHelper('partial', function(name, context) {
    if(!Array.isArray(assemble.partials)) {
      assemble.partials = [assemble.partials];
    }

    var filepath = _.first(_.filter(assemble.partials, function(fp) {
      return path.basename(fp, path.extname(fp)) === name;
    }));

    // Process context, using YAML front-matter,
    // grunt config and Assemble options.data
    var pageObj = yfm.extract(filepath) || {};
    var metadata = pageObj.context || {};

    // `context`           = the given context (second parameter)
    // `metadata`          = YAML front matter of the partial
    // `opts.data[name]`   = JSON/YAML data file defined in Assemble options.data with a basename
    //                       matching the name of the partial, e.g {{partial 'foo'}} => foo.json
    // `this`              = YAML front matter of _either_ the "inheriting" page, or a block
    //                       expression wrapping the helper
    // `opts`              = Custom properties defined in Assemble options
    // `grunt.config.data` = Data from grunt.config.data (e.g. pkg: grunt.file.readJSON('package.json'))

    // omit pages and pagination properties from opts and this contexts to avoid processing templates
    // unintentionally
    // see https://github.com/helpers/handlebars-helper-partial/issues/3
    // we do this omit at least twice, so wrap in function for DRYness
    var removePageContent = function(target) {
      return _.omit(target, 'pages', 'pagination');
    };

    // now remove page content from this and opts before creating new context
    context = _.extend({}, 
                       grunt.config.data, 
                       removePageContent(opts), 
                       removePageContent(this), 
                       opts.data[name], 
                       metadata, 
                       context);

    // process any templates inside context property values
    context = grunt.config.process(context);

    // look up this partial name from the partials registered with Handlebars
    var template = Handlebars.partials[name];

    // Check if this partial has already been compiled, whether via this helper, another helper or
    // via the native {{>partial}} mechanism.  If so, reuse the compiled partial.
    // see https://github.com/helpers/handlebars-helper-partial/issues/1
    var fn;  
    if (!_.isFunction(template)) {

        // not compiled, so we can compile it safely
        fn = Handlebars.compile(template);
    }
    else {

        // already compiled, just reuse it
        fn = template;
    }

    var output = fn(context).replace(/^\s+/, '');

    // Prepend output with the filepath to the original partial
    var include = opts.include || opts.data.include || {};
    if(include.origin === true) {
      output = '<!-- ' + filepath + ' -->\n' + output;
    }

    return new Handlebars.SafeString(output);
  });
Ejemplo n.º 29
0
  onEmailInsert(callback) {
    this.emitter.on('on-email-insert', (inputText) => { return this.displayEmail(callback(this, inputText))});
  },

  displayEmail(emails) {
    this.atomEmailerView.displayFetchedEmail(emails);
  },

  onEmailSubmit(callback) {
    this.emitter.on('on-submit-email', callback(this));
  },

  fetchEmail(_this, inputText) {
    if(_this.settings.hasOwnProperty('sentEmails')){
      return _.filter(_this.settings.sentEmails, function(email){
        return email.startsWith(inputText);
      });
    }
    return [];
  },

  sendEmail (_this) {
    return function sendEmailClosure(to) {
      editor = atom.workspace.getActiveTextEditor();
      selectedText = editor.getSelectedText();
      var transporter = nodemailer.createTransport(_this.settings.url);
      var mailOptions = {
        from: '<*****@*****.**>', // sender address
        to: to, // list of receivers
        subject: 'Hello from Atom ✔', // Subject line
        text: selectedText // plaintext body
  it("should add a manifest doc for each example", function() {
    var manifestDocs = _.filter(docs, { docType: 'example-manifest' });
    expect(manifestDocs.length).toEqual(1);

  });