Example #1
0
AddressService.prototype._processTransaction = function(tx, opts) {

  var self = this;

  var _opts = { block: opts.block };

  var outputOperations = tx.outputs.map(function(output, index) {
    return self._processOutput(tx, output, index, _opts);
  });

  outputOperations = lodash.compact(lodash.flattenDeep(outputOperations));
  assert(outputOperations.length % 2 === 0 &&
    outputOperations.length <= tx.outputs.length * 2,
    'Output operations count is not reflective of what should be possible.');

  var inputOperations = tx.inputs.map(function(input, index) {
    return self._processInput(tx, input, index, _opts);
  });

  inputOperations = lodash.compact(lodash.flattenDeep(inputOperations));

  assert(inputOperations.length % 2 === 0 &&
    inputOperations.length <= tx.inputs.length * 2,
    'Input operations count is not reflective of what should be possible.');

  outputOperations = outputOperations.concat(inputOperations);
  return outputOperations;

};
Example #2
0
 it('should have domain between min and max values', function () {
   const min = _.min(_.flattenDeep(graphData));
   const max = _.max(_.flattenDeep(graphData));
   const domain = checkDomain(min, max);
   expect(domain[0]).to.be.lessThan(0);
   expect(domain[1]).to.be.greaterThan(0);
   checkRange();
 });
Example #3
0
/**
                              * Prints a banner with a border around it containing the given message. The
                              * following options are supported:
                              *
                              * type Options = {
                              *   // A function to apply to each line of text to decorate it
                              *   chalkFunction: (string: message) => string;
                              *   // The total width (max line length) of the banner, including margin and
                              *   // padding (default = 80)
                              *   width: number;
                              *   // How much leading space to prepend to each line (default = 0)
                              *   marginLeft: number;
                              *   // How much trailing space to append to each line (default = 0)
                              *   marginRight: number;
                              *   // Space between the top banner border and the text (default = 0)
                              *   paddingTop: number;
                              *   // Space between the bottom banner border and the text (default = 0)
                              *   paddingBottom: number;
                              *   // Space between the left banner border and the text (default = 2)
                              *   paddingLeft: number;
                              *   // Space between the right banner border and the text (default = 2)
                              *   paddingRight: number;
                              * };
                              */
function formatBanner(message, options) {
  options = options || {};
  _.defaults(options, {
    chalkFunction: _.identity,
    width: 80,
    marginLeft: 0,
    marginRight: 0,
    paddingTop: 0,
    paddingBottom: 0,
    paddingLeft: 2,
    paddingRight: 2 });


  var width = options.width;
  var marginLeft = options.marginLeft;
  var marginRight = options.marginRight;
  var paddingTop = options.paddingTop;
  var paddingBottom = options.paddingBottom;
  var paddingLeft = options.paddingLeft;
  var paddingRight = options.paddingRight;

  var horizSpacing = marginLeft + paddingLeft + paddingRight + marginRight;
  // 2 for the banner borders
  var maxLineWidth = width - horizSpacing - 2;
  var wrap = wordwrap(maxLineWidth);
  var body = wrap(message);

  var left = spaces(marginLeft) + VERTICAL_LINE + spaces(paddingLeft);
  var right = spaces(paddingRight) + VERTICAL_LINE + spaces(marginRight);
  var bodyLines = _.flattenDeep([
  arrayOf('', paddingTop),
  body.split('\n'),
  arrayOf('', paddingBottom)]).
  map(function (line) {
    var padding = spaces(Math.max(0, maxLineWidth - line.length));
    return left + options.chalkFunction(line) + padding + right;
  });

  var horizontalBorderLine = repeatString(
  HORIZONTAL_LINE,
  width - marginLeft - marginRight - 2);

  var top =
  spaces(marginLeft) +
  TOP_LEFT +
  horizontalBorderLine +
  TOP_RIGHT +
  spaces(marginRight);
  var bottom =
  spaces(marginLeft) +
  BOTTOM_LEFT +
  horizontalBorderLine +
  BOTTOM_RIGHT +
  spaces(marginRight);
  return _.flattenDeep([top, bodyLines, bottom]).join('\n');
}
Example #4
0
// explode built-in fs methods to `fs-more`
// sync.__proto__ = node_fs;


// Process specified wildcard glob patterns or filenames against a
// callback, excluding and uniquing files in the result set.
function processPatterns(patterns, fn) {

  // Filepaths to return.
  var result = [];
  // Iterate over flattened patterns array.
  _.flattenDeep(patterns).forEach(function(pattern) {
    // If the first character is ! it should be omitted
    var exclusion = pattern.indexOf('!') === 0;
    // If the pattern is an exclusion, remove the !
    if (exclusion) {
      pattern = pattern.slice(1);
    }
    // Find all matching files for this pattern.
    var matches = fn(pattern);

    if (exclusion) {
      // If an exclusion, remove matching files.
      result = _.difference(result, matches);
    } else {
      // Otherwise add matching files.
      result = _.union(result, matches);
    }
  });

  return result;
};
Example #5
0
function querybucketTotals(transactions) {
  var buckets = [];
  var bucketNames = _.uniq(
    _.flattenDeep(
      transactions.map(t => {
        return t.bucket
      })
      )
    );

  if(!_.isEmpty(bucketNames)) {
    bucketNames.forEach(b => {
      var amounts = _.filter(transactions, 
      {
        "bucket": [b]
      });

      var totalAmount = _.round(_.sum(amounts.map(t => {return t.amount})));

      buckets.push({
        "name": b,
        "value": totalAmount
      });
    })
  }

  return buckets;
}
    generateMarkdown(taserReports) {
        if( !taserReports ) {
            throw new Error('Cannot generate markdown without taser reports');
        }

        if( !(taserReports instanceof Array) ) {
            throw new Error('Expected taser reports to be an Array');
        }

        let markdownReport = [];

        for( let i = 0; i < taserReports.length; i++ ) {
            let problem = taserReports[i].problem;
            let reports = taserReports[i].reports;

            if( reports === undefined ) {
                markdownReport.push(reportError(problem));
                continue;
            }

            markdownReport.push(problemReportHeader(problem));

            for( let j = 0; j < reports.length; j++ ) {
                markdownReport.push(problemReportBody(reports[j]));
            }
        }

        // Each report section returns an array of its content, flatten all content and join with a newline
        return _
            .flattenDeep(markdownReport)
            .join('\n');
    }
Example #7
0
function formatIncomingStudy(study) {
    let dirtyRoBs = _.filter(study.riskofbiases, (rob) => {
            return rob.active === true;
        }),
        domains = _.flattenDeep(
            _.map(dirtyRoBs, (riskofbias) => {
                return _.map(riskofbias.scores, (score) => {
                    return Object.assign({}, score, {
                        riskofbias_id: riskofbias.id,
                        author: riskofbias.author,
                        final: riskofbias.final,
                        domain_name: score.metric.domain.name,
                        domain_id: score.metric.domain.id,
                    });
                });
            })
        ),
        riskofbiases = d3
            .nest()
            .key((d) => {
                return d.metric.domain.name;
            })
            .key((d) => {
                return d.metric.name;
            })
            .entries(domains),
        finalRoB = _.find(dirtyRoBs, { final: true });

    return Object.assign({}, study, {
        riskofbiases,
        final: _.has(finalRoB, 'scores') ? finalRoB.scores : [],
    });
}
Example #8
0
function formatOutgoingRiskOfBias(state, riskofbias) {
    let riskofbias_id = state.config.riskofbias.id,
        author,
        final,
        scores = _.flattenDeep(
            _.map(state.study.riskofbiases, (domain) => {
                return _.map(domain.values, (metric) => {
                    return _.omit(
                        _.find(metric.values, (score) => {
                            if (score.riskofbias_id == riskofbias_id) {
                                author = author || score.author;
                                final = final || score.final;
                            }
                            return score.riskofbias_id == riskofbias_id;
                        }),
                        ['riskofbias_id', 'author', 'final', 'domain_id', 'domain_name']
                    );
                });
            })
        );
    return Object.assign(
        {},
        {
            author,
            final,
            scores,
            active: true,
            pk: parseInt(riskofbias_id),
            study: parseInt(state.config.study.id),
        },
        riskofbias
    );
}
 var findState = function(previousState,currentElement){
   if(hasEpsilon(previousState)){
     var state = stateReducer(_.flattenDeep([transtion[previousState]["E"]]),currentElement);
     return [transtion[previousState][currentElement],state]
   }
   return currentElement ? transtion[previousState][currentElement] : previousState
 }
Example #10
0
 it('should have domain between min value and 0', function () {
   var min = _.min(_.flattenDeep(graphData));
   var max = 0;
   var domain = checkDomain(min, max);
   expect(domain[0]).to.be.lessThan(0);
   checkRange();
 });
Example #11
0
  }, function(err, ops) {

    if (err) {
      self._processingBlock = false;
      return callback(err);
    }

    self._db.batch(_.compact(_.flattenDeep(ops)), function(err) {

      if (err) {
        self._processingBlock = false;
        return callback(err);
      }

      self._recentBlockHashes.set(block.rhash(), bcoin.util.revHex(block.prevBlock));
      self._setTip({ hash: block.rhash(), height: block.__height }, function(err) {
        if (err) {
          self._processingBlock = false;
          return callback(err);
        }
        self._processingBlock = false;

        for (var i = 0; i < self._subscriptions.block.length; i++) {
          self._subscriptions.block[i].emit('block/block', block);
        }

        callback();
      });

    });
  });
Example #12
0
 resolve: (course) => {
   return {
     red: _.sum(_.flattenDeep(course.baskets.map((basket) => {
       const redTeePad = basket.teePads.red
       return redTeePad && redTeePad.par
     }))),
     white: _.sum(_.flattenDeep(course.baskets.map((basket) => {
       const whiteTeePad = basket.teePads.white
       return whiteTeePad && whiteTeePad.par
     }))),
     blue: _.sum(_.flattenDeep(course.baskets.map((basket) => {
       const blueTeePad = basket.teePads.blue
       return blueTeePad && blueTeePad.par
     }))),
   }
 },
Example #13
0
 const isMoveable = (graph, node) => {
   return graph.parent(node) === parent &&
          _.flattenDeep(Object.keys(graph.node(node).outputPorts).map((port) => atomicSuccessorsInPort(graph, node, port))).length === 1 && // TODO if the branch has no side-effects, we could copy it and the number of successors of a node could be more than one
          Object.keys(graph.node(node).inputPorts || {}).every((port) => {
            return walk.predecessor(graph, node, port).every(({node}) => isMoveable(graph, node))
          })
 }
nfa.prototype.possibleEpslonStates = function(states){
	var _this = this;
	return lodash.flattenDeep(states.map(function(state){
		isUndefined(_this.transition_function[state]) && (_this.transition_function[state] = {epslon_symbol:[]})
		return _this.transition_function[state][epslon_symbol] || []
	}))
}
Example #15
0
 it('should have domain between 0 and max value', function () {
   var min = 0;
   var max = _.max(_.flattenDeep(graphData));
   var domain = checkDomain(min, max);
   expect(domain[1]).to.be.greaterThan(0);
   checkRange();
 });
Example #16
0
    // API
    src (...sources) {
        sources = flatten(sources).map(path => resolvePath(path));

        this.bootstrapper.sources = this.bootstrapper.sources.concat(sources);

        return this;
    }
Example #17
0
        it('change property of piece that is placeable', () => {
          const board = new Board(position());
          const piece = Piece.create({ type: 'l', x: 0, y: 0});

          const enhancedPositions = board.enhanceCanDropPosition(piece).board.map((row) => {
            return (
              row.filter((cell) => { return(cell.isDrop); })
            );
          });

          _.flattenDeep(enhancedPositions).should.eql(
            [
              Piece.create({ type: '*', x: 9, y: 1, isDrop: true}),
              Piece.create({ type: '*', x: 8, y: 1, isDrop: true}),
              Piece.create({ type: '*', x: 9, y: 2, isDrop: true}),
              Piece.create({ type: '*', x: 8, y: 2, isDrop: true}),
              Piece.create({ type: '*', x: 9, y: 3, isDrop: true}),
              Piece.create({ type: '*', x: 8, y: 3, isDrop: true}),
              Piece.create({ type: '*', x: 9, y: 4, isDrop: true}),
              Piece.create({ type: '*', x: 9, y: 5, isDrop: true}),
              Piece.create({ type: '*', x: 8, y: 5, isDrop: true}),
              Piece.create({ type: '*', x: 9, y: 6, isDrop: true}),
              Piece.create({ type: '*', x: 8, y: 6, isDrop: true}),
              Piece.create({ type: '*', x: 8, y: 7, isDrop: true}),
              Piece.create({ type: '*', x: 9, y: 8, isDrop: true}),
              Piece.create({ type: '*', x: 8, y: 8, isDrop: true}),
            ]
          );
        });
Example #18
0
  /**
   * use a middleware
   */
  use(path) {
    let fns
    let fn

    // path is optional
    if (typeof path === 'string') {
      fns = [].slice.call(arguments, 1)
    } else {
      fns = [].slice.call(arguments)
      path = '/'
    }
    fns = _.flattenDeep(fns)

    // ensure function
    if (!fns.length || fns.some(fn => !fn || typeof fn !== 'function')) {
      throw new TypeError('fn expected to be functions')
    }

    // compose
    if (fns.length === 1) fn = fns[0]
    else fn = compose(fns)

    const layer = new Layer(
      path,
      {
        end: false,
        strict: this.opts.strict,
        sensitive: this.opts.sensitive,
      },
      fn
    )

    this.stack.push(layer)
    return this
  }
Example #19
0
Grid.prototype.progress = function () {
  var thisGrid = this;
  var perfect = this.perfectBoard();
  if (thisGrid.tileCount() == perfect.tileCount) { // Doesn't matter how the board looks, but we have all the right pieces
    return 100;
  }
  var boardPercent = (_.sum(_.flattenDeep(thisGrid.data)) / _.sum(perfect.uniqTiles) * 100);
  var boardUniq = _.max(_.values(thisGrid.tileCount()));
  var boardCount = (1 / _.values(thisGrid.tileCount()).length);
  var maxTile = 1 - (1 / thisGrid.maxTile());
  var sortedPercent = thisGrid.sortedPercent();
  var score = (boardPercent * .1) + (boardCount * .2) + (maxTile * .3) + (sortedPercent * .5);
  //var score = boardCount;
  //console.log(JSON.stringify({boardPercent:boardPercent,boardUniq:boardUniq,max:_.max(_.values(thisGrid.tileCount())),count:_.values(thisGrid.tileCount()).length,score:(boardPercent * .9) + (boardUniq * .1)}));
  if (false) {
    console.log(JSON.stringify({
      max: _.max(_.values(thisGrid.tileCount())),
      count: _.values(thisGrid.tileCount()).length,
      boardPercent: boardPercent,
      boardUniq: boardUniq,
      boardCount: boardCount,
      score: score
    }));
  }
  return score;
};
        instanceToWrap[method] = function () {
            // Manipulating arguments directly is discouraged
            var args = new Array(arguments.length); 
            for(var i = 0; i < arguments.length; ++i) {
                args[i] = arguments[i];
            }

            // Grab the first parameter out in case it's a route or array of routes.
            var first = null;
            if ('string' === typeof args[0] || args[0] instanceof RegExp ||
                    (Array.isArray(args[0]) && 'string' === typeof args[0][0] || args[0][0] instanceof RegExp)) {
                first = args[0];
                args = args.slice(1);
            }

            args = _.flattenDeep(args).map(function (arg) {
                return wrapHandler(arg);
            });

            // If we have a route path or something, push it in front
            if (first) {
                args.unshift(first);
            }

            return instanceToWrap[original].apply(this, args);
        };
Example #21
0
const mapEnvVars = (
  deploymentManifest
, releaseManifest
, appManifests
) => (
  _.flattenDeep(_.map(appManifests, (app) => {
    const appNameCapitalized = underscored(app.name).toUpperCase();
    const autoEnv = _.mapKeys(deploymentManifest.autoEnvReplacement, (v, key) => key.replace('${APPNAME}', appNameCapitalized));

    var merged = _.merge(autoEnv, _.get(deploymentManifest, 'applicationDefaults.env'), _.get(releaseManifest, 'applicationDefaults.env'), app.deployment.env, _.get(deploymentManifest, 'apps.' + app.name + '.env'));

    var envs = _.reduce(merged, (res, value, key) => {
      const envReplacement = deploymentManifest.envReplacement || {};
      const autoEnvReplacement = deploymentManifest.autoEnvReplacement || {};

      const replacedValue = replaceEnvVar(envReplacement, autoEnvReplacement, app.name, key, value);

      if (replacedValue && !replacedValue.replace) {
        res[key] = JSON.stringify(replacedValue);
      } else {
        res[key] = replacedValue
                    .replace('${APP_VERSION}', app.version)
                    .replace('${SYSTEM_VERSION}', releaseManifest.version)
                    .replace('${org}', deploymentManifest.target.org)
                    .replace('${space}', deploymentManifest.target.space);
      }
      debug(app.name, key + ' -> ' + replacedValue);
      return res;
    }, {});

    return { name: app.name
           , env: envs
           };
  }))
);
Example #22
0
 snapshot.forEach(data => {
   var key = data.key()
   var val = data.val()
   switch (key) {
     case 'groups':
       this.groups = val
       this.addOthersUserObj(_.flattenDeep(val.map(el => {
         return el.teams.map(el => el.objectId)
       })))
       break
     case 'playoffs':
       this.playoffs = val
       break
     case 'queue':
       this.queue = val
       break
     case 'courts':
       this.courts = val
       this.addOthersUserObj(val.map(el => el.umpire))
       break
     case 'discipline':
       this.isSingle = isSingle(val)
       break
   }
 })
Example #23
0
    _.forEach(ramlResources, function (resource) {
        var uri = resource.completeRelativeUri();
        var name = resource.displayName() || capitalizeFirstLetter(uri.replace('/', ''));
        var description = "";
        var annotations = produceAnnotations(resource);
        var type = "";

        if (resource.description()) {
            description = resource.description().value();
        }

        //make sure there are no duplicates
        if (namesArr.indexOf(name) < 0) {

            namesArr.push(name);

            apiResources.push({
                uri: uri,
                name: name,
                description: description,
                type: type,
                endpoints: _.flattenDeep(produceEndpoints(resource)),
                annotations: annotations
            });
        }
    });
Example #24
0
Grid.prototype.nearEnd = function (thisGrid) {
  if (!thisGrid) {
    thisGrid = this;
  }
  /* Original version by counting 0's */
  var zeroes = _.filter(_.flattenDeep(thisGrid.data), function (item) {
    return item === 0;
  }).length;
  //console.log({zeroes:zeroes});
  if (zeroes === 0) {
    return true;
  }
  // New version by checking if a 2 and 4 are near the zeros
  var has2 = false;
  var has4 = false;
  for (var i = 0; i < thisGrid.data.length; i++) {
    for (var j = 0; j < thisGrid.data[i].length; j++) {
      if (thisGrid.data[i][j] === 0) {
        if (thisGrid.getUp(i, j) === 2 || thisGrid.getDown(i, j) === 2 || thisGrid.getLeft(i, j) === 2 || thisGrid.getRight(i, j) === 2) {
          has2 = true;
        }
        if (thisGrid.getUp(i, j) === 4 || thisGrid.getDown(i, j) === 4 || thisGrid.getLeft(i, j) === 4 || thisGrid.getRight(i, j) === 4) {
          has4 = true;
        }
      }
      if (has2 && has4 && zeroes >= 1) {
        return false;
      }
    }
  }
  return !(has2 && has4);
  //return true;
};
Example #25
0
      _.each(extractBuckets(data[agg.id], agg), function (bucket) {

        var _record = _.flattenDeep([record, bucket.key]);
        _.each(metrics, function (metric) {
          var value = bucket.doc_count;
          if (bucket[metric.id] && !_.isUndefined(bucket[metric.id].value)) {
            value = bucket[metric.id].value;
          }
          _record.push(value);
        });

        // If there is another agg to call we need to check to see if it has
        // buckets. If it does then we need to keep on walking the tree.
        // This is where the recursion happens.
        if (agg._next) {
          var nextBucket = bucket[agg._next.id];
          if (nextBucket && nextBucket.buckets) {
            walkBuckets(agg._next, bucket, _record);
          }
        }
        // if there are no more aggs to walk then  push the record to the rows.
        else {
          results.rows.push(_record);
        }
      });
export function getParentsForList (list) {
  let mapped = _.map(list, node => {
    return getParents(node)
  })

  let flat = _.flattenDeep(mapped)
  return flat
}
var mark_multi = function (text) {
  var marks = [];
  _.forEach(crackTool.punctual_marks, function (mark) {
    marks.push(marker_indices(mark, text));
  });
  marks = _.flattenDeep(marks);
  return marks;
};
Example #28
0
Linter.getOptions = function (args) {
    var optList = Array.prototype.slice.call(args, 1);
    optList = lodash.flattenDeep(optList);

    optList.unshift('default');

    return presets.flattenOpts(optList);
};
Example #29
0
 .then(function(output) {
     //遍历路径发送上线
     return q.all(_.flattenDeep([output['js'].map(function(js) {
       return upload(file, js, opts);
     }), output['css'].map(function(css) {
       return upload(file, css, opts);
     })]));
   })
Example #30
0
function done(mine) {
  mine = _.isArray(mine) ? _.uniq(mine)[0] : mine;
  mine.data = _.flattenDeep(mine.data);
  console.log(chalk.underline(chalk[mine.color]('\nFINISHED: ', mine.name)));
  console.timeEnd(mine.name);
  console.log('\n');
  return mine.data;
}