SVGSpriter.prototype._compile = function() {
	
	// If the shape queue is not currently active
	if (!this._queue.active && this._compileQueue.length) {
		var masterShapes		= _.reject(this._shapes, function(shape) { return !!shape.master; }).length;
		this.info('Compiling %d shapes ...', masterShapes);

		var that 				= this,
		args					= this._compileQueue.shift();
		
		// Initialize the namespace powers
		while (!this._namespacePow.length || (Math.pow(26, this._namespacePow.length) < masterShapes)) {
			this._namespacePow.unshift(Math.pow(26, this._namespacePow.length));
			_.invoke(this._shapes, 'resetNamespace');
		}
		
		// Sort shapes by ID
		this._shapes			= this._shapes.sort(this.config.shape.sort);
		
		// Set the shape namespaces on all master shapes
		_.reject(this._shapes, function(shape) { return !!shape.master; }).map(function(shape, index){
			shape.setNamespace(this._indexNamespace(index));
		}, this);
		
		this._layout(args[0], function(error, files, data) {
			
			// Add intermediate SVG files
			if (that.config.shape.dest) {
				files.shapes	= that._getShapeFiles(that.config.shape.dest);
				that.verbose('Returning %d intermediate SVG files', files.shapes.length);
			}
			that.info('Finished %s sprite compilation', _.keys(data).map(function(mode){
				return '«' + mode + '»';
			}).join(' + '));
			
			that._logStats(files);

			args[1](error, files, data);
			that.emit('compiled');
		});
	}
};
Example #2
0
 enhance: function(image, callback) {
   var longEdge = Math.max(image.width, image.height)
   var splitMax = Math.ceil(Math.log(longEdge) / Math.LN2)
   if (image.frames.length === 1) {
     fillGif(image)
   }
   for(var i = 0, len = image.frames.length; i < len; i++) {
     var grid = createPixelGrid(image.frames[i], image.width, image.height)
     var grids = [grid]
     var splitCount = Math.floor(scale(i, 0, len, 1, splitMax))
     _.times(Math.floor(scale(i, 0, len, 1, splitMax)), function() {
       grids = _.flatten(grids, function(g) {
         return g.split()
       })
     })
     _.invoke(grids, 'average')
     image.frames[i].data = new Buffer(grid.toArray())
   }
   callback(null, image)
 }
Example #3
0
  handleSearchChange = (e) => {
    debug('handleSearchChange()')
    debug(e.target.value)
    // prevent propagating to this.props.onChange()
    e.stopPropagation()
    const { minCharacters } = this.props
    const { open } = this.state
    const newQuery = e.target.value

    _.invoke(this.props, 'onSearchChange', e, { ...this.props, value: newQuery })

    // open search dropdown on search query
    if (newQuery.length < minCharacters) {
      this.close()
    } else if (!open) {
      this.tryOpen(newQuery)
    }

    this.setValue(newQuery)
  }
Example #4
0
File: home.js Project: ferni/loaddr
 db.model('Loaddr').find({_creator: req.user._id}, function (err, loaddrs) {
     if (err) return next(err);
     if (loaddrs.length === 0) {
         return res.render('app', {
             loaddrs: loaddrs,
             user: req.user,
             connectionID: req.session.connectionID
         });
     }
     _.invoke(loaddrs, 'loadPrototype');
     wallet.loadBalances(loaddrs).then(function() {
         return res.render('app', {
             loaddrs: loaddrs,
             user: req.user,
             connectionID: req.session.connectionID,
             title: 'Loaddr - There\'s an address for everything'
         });
     }).catch(function(e) {
         next(e);
     });
 });
Example #5
0
        $scope.$watch('indexPattern.fields', function () {
          _.invoke(rowScopes, '$destroy');
          rowScopes.length = 0;

          $scope.rows = $scope.indexPattern.getFields('scripted').map(function (field) {
            var rowScope = $scope.$new();
            var columns = [field.name, field.script, field.type];
            rowScope.field = field;
            rowScopes.push(rowScope);

            columns.push({
              markup: popularityHtml,
              scope: rowScope
            }, {
              markup: controlsHtml,
              scope: rowScope
            });

            return columns;
          });
        });
Example #6
0
        .then((_items) => {
            items = _items;
            if(items.length < ironReq) {
                throw Constants.NO_IRONS;
            }

            role.coins -= coinReq;
            var promises = _.invoke(items, "delete");

            if (Math.random() < (refineOptions.luck + (equipment.luck || 0)) / 100) {
                equipment.refinement += 1;
                equipment.luck = 0;
                success = true;
            }
            else {
                equipment.luck = ((equipment.luck || 0) + refineOptions.luckGrowth) / 100;
                success = false;
            }

            promises.unshift(role.save(), equipment.save());
            return promises;
        })
Example #7
0
  handleSearchChange = (e, { value }) => {
    debug('handleSearchChange()')
    debug(value)

    // prevent propagating to this.props.onChange()
    e.stopPropagation()

    const { minCharacters } = this.props
    const { open } = this.state
    const newQuery = value

    _.invoke(this.props, 'onSearchChange', e, { ...this.props, searchQuery: newQuery })
    this.trySetState({ searchQuery: newQuery }, { selectedIndex: 0 })

    // open search dropdown on search query
    if (!open && newQuery.length >= minCharacters) {
      this.open()
      return
    }
    // close search dropdown if search query is too small
    if (open && minCharacters !== 1 && newQuery.length < minCharacters) this.close()
  }
Example #8
0
        $scope.$watchCollection('indexPattern.fields', function () {
          _.invoke(rowScopes, '$destroy');

          $scope.rows = $scope.indexPattern.getFields().map(function (field) {
            var childScope = $scope.$new();
            rowScopes.push(childScope);
            childScope.field = field;

            // update the active field via object comparison
            if (_.isEqual(field, $scope.popularityHoverState)) {
              $scope.showPopularityControls(field);
            }

            return [field.name, field.type, field.analyzed, field.indexed,
              {
                markup: popularityHtml,
                scope: childScope,
                value: field.count
              }
            ];
          });
        });
Example #9
0
        function refreshRows() {
          // clear and destroy row scopes
          _.invoke(rowScopes.splice(0), '$destroy');

          var fields = filter($scope.indexPattern.getNonScriptedFields(), $scope.fieldFilter);
          _.find($scope.fieldTypes, {index: 'indexedFields'}).count = fields.length; // Update the tab count

          $scope.rows = fields.map(function (field) {
            var childScope = _.assign($scope.$new(), { field: field });
            rowScopes.push(childScope);

            return [
              {
                markup: nameHtml,
                scope: childScope,
                value: field.displayName
              },
              {
                markup: typeHtml,
                scope: childScope,
                value: field.type
              },
              _.get($scope.indexPattern, ['fieldFormatMap', field.name, 'type', 'title']),
              {
                markup: field.analyzed ? yesTemplate : noTemplate,
                value: field.analyzed
              },
              {
                markup: field.indexed ? yesTemplate : noTemplate,
                value: field.indexed
              },
              {
                markup: controlsHtml,
                scope: childScope
              }
            ];
          });
        }
  fireCallbacks() {
    const {
      onBottomPassed,
      onBottomPassedReverse,
      onBottomVisible,
      onBottomVisibleReverse,
      onPassing,
      onPassingReverse,
      onTopPassed,
      onTopPassedReverse,
      onTopVisible,
      onTopVisibleReverse,
      onOffScreen,
      onOnScreen,
    } = this.props
    const callbacks = {
      bottomPassed: onBottomPassed,
      bottomVisible: onBottomVisible,
      passing: onPassing,
      offScreen: onOffScreen,
      onScreen: onOnScreen,
      topPassed: onTopPassed,
      topVisible: onTopVisible,
    }
    const reverse = {
      bottomPassed: onBottomPassedReverse,
      bottomVisible: onBottomVisibleReverse,
      passing: onPassingReverse,
      topPassed: onTopPassedReverse,
      topVisible: onTopVisibleReverse,
    }

    _.invoke(this.props, 'onUpdate', null, { ...this.props, calculations: this.calculations })
    this.fireOnPassed()

    _.forEach(callbacks, (callback, name) => this.execute(callback, name))
    _.forEach(reverse, (callback, name) => this.execute(callback, name))
  }
Example #11
0
  makeSelectedItemActive = (e) => {
    const { open } = this.state
    const { multiple } = this.props

    const item = this.getSelectedItem()
    const value = _.get(item, 'value')

    // prevent selecting null if there was no selected item value
    // prevent selecting duplicate items when the dropdown is closed
    if (_.isNil(value) || !open) return

    // state value may be undefined
    const newValue = multiple ? _.union(this.state.value, [value]) : value

    // notify the onChange prop that the user is trying to change value
    this.setValue(newValue)
    this.setSelectedIndex(newValue)
    this.handleChange(e, newValue)

    // Heads up! This event handler should be called after `onChange`
    // Notify the onAddItem prop if this is a new value
    if (item['data-additional']) _.invoke(this.props, 'onAddItem', e, { ...this.props, value })
  }
Example #12
0
      function refreshRows() {
        _.invoke(rowScopes, '$destroy');
        rowScopes.length = 0;

        const fields = filter($scope.indexPattern.getScriptedFields(), $scope.fieldFilter);
        _.find($scope.fieldTypes, {index: 'scriptedFields'}).count = fields.length; // Update the tab count

        $scope.rows = fields.map(function (field) {
          const rowScope = $scope.$new();
          rowScope.field = field;
          rowScopes.push(rowScope);

          return [
            _.escape(field.name),
            _.escape(field.script),
            _.get($scope.indexPattern, ['fieldFormatMap', field.name, 'type', 'title']),
            {
              markup: controlsHtml,
              scope: rowScope
            }
          ];
        });
      }
Example #13
0
 morphToFetch: Promise.method(function(relationName, relatedData, options) {
   var pending = [];
   var groups = _.groupBy(this.parent, function(m) {
     return m.get(relatedData.morphName + '_type');
   });
   for (var group in groups) {
     var Target = Helpers.morphCandidate(relatedData.candidates, group);
     var target = new Target();
     pending.push(target
       .query('whereIn',
         _.result(target, 'idAttribute'),
         _.uniq(_.invoke(groups[group], 'get', relatedData.morphName + '_id'))
       )
       .sync(options)
       .select()
       .tap(eagerLoadHelper(this, relationName, {
         relatedData: relatedData.instance('morphTo', Target, {morphName: relatedData.morphName})
       }, options)));
   }
   return Promise.all(pending).then(function(resps) {
     return _.flatten(resps);
   });
 })
    translate: function(tx, ty, opt) {

        ty = ty || 0;

        if (tx === 0 && ty === 0) {
            // Like nothing has happened.
            return this;
        }

        opt = opt || {};
        // Pass the initiator of the translation.
        opt.translateBy = opt.translateBy || this.id;
        // To find out by how much an element was translated in event 'change:position' handlers.
        opt.tx = tx;
        opt.ty = ty;

        var position = this.get('position') || { x: 0, y: 0 };
	var translatedPosition = { x: position.x + tx || 0, y: position.y + ty || 0 };

	if (opt.transition) {

	    if (!_.isObject(opt.transition)) opt.transition = {};

	    this.transition('position', translatedPosition, _.extend({}, opt.transition, {
		valueFunction: joint.util.interpolate.object
	    }));

	} else {

            this.set('position', translatedPosition, opt);

            // Recursively call `translate()` on all the embeds cells.
            _.invoke(this.getEmbeddedCells(), 'translate', tx, ty, opt);
	}

        return this;
    },
Example #15
0
    remove: function(options) {

	var collection = this.collection;

	if (collection) {
	    collection.trigger('batch:start');
	}

        // First, unembed this cell from its parent cell if there is one.
        var parentCellId = this.get('parent');
        if (parentCellId) {
            
            var parentCell = this.collection && this.collection.get(parentCellId);
            parentCell.unembed(this);
        }
        
        _.invoke(this.getEmbeddedCells(), 'remove', options);
        
        this.trigger('remove', this, this.collection, options);

	if (collection) {
	    collection.trigger('batch:stop');
	}
    },
Example #16
0
  /**
   * @static
   * @param {OperationalTx} optx
   * @return {Promise<ComposedTx>}
   */
  static async makeComposedTx (optx) {
    let targets = optx.getTargets()
    let targetsTotalValue = ColorTarget.sum(targets)

    let comptx = optx.makeComposedTx()
    comptx.addOutputs(targets.map((target) => { return {target: target} }))

    let selectedCoins = await optx.selectCoins(targetsTotalValue, comptx)
    comptx.addInputs(_.invoke(selectedCoins.coins, 'toRawCoin'))

    let fee = comptx.estimateRequiredFee()
    let change = selectedCoins.total.minus(targetsTotalValue).minus(fee)

    if (change.getValue() > optx.getDustThreshold().getValue()) {
      let uncolored = new UncoloredColorDefinition()
      let changeAddress = await optx.getChangeAddress(uncolored)
      comptx.addOutput({
        script: bitcore.Script.fromAddress(changeAddress).toHex(),
        value: change.getValue()
      })
    }

    return comptx
  }
 handleKeyDown = (e) => {
   _.invoke(this.props, 'onKeyDown', e, this.props)
   if (keyboardKey.getCode(e) === keyboardKey.Enter) _.invoke(this.props, 'onClick', e, this.props)
 }
Example #18
0
  handleResultSelect = (e, result) => {
    debug('handleResultSelect()')
    debug(result)

    _.invoke(this.props, 'onResultSelect', e, { ...this.props, result })
  }
Example #19
0
 onWatcherChange(e, path) {
   invoke(this.workers, 'onChange', path);
 }
Example #20
0
  handleSelectionChange = (e) => {
    debug('handleSelectionChange()')

    const result = this.getSelectedResult()
    _.invoke(this.props, 'onSelectionChange', e, { ...this.props, result })
  }
var ProductStore = _.assign({}, EventEmitter.prototype, {
  emitChange(type, record) {
    this.emit('change', type, record)
  },

  addChangeListener(callback) {
    this.on('change', callback)
  },

  removeChangeListener(callback) {
    this.removeListener('change', callback)
  },

  getAll() {
    let activeProducts = products.where({ archived: false })
    return _.sortBy(_.invoke(activeProducts, 'toJSON'), 'name')
  },

  getProduct(id) {
    let product = products.get(id)
    if (!product) {
      return false
    }
    return {
      members: product.members.toJSON(),
      product: product.toJSON(),
      tags: product.tags.toJSON(),
      velocity: productVelocity[id] || null
    }
  },
Example #22
0
 Vis.prototype.requesting = function () {
   // Invoke requesting() on each agg. Aggs is an instance of AggConfigs.
   _.invoke(this.aggs.getRequestAggs(), 'requesting');
 };
Example #23
0
    removeLinks: function(model) {

        _.invoke(this.getConnectedLinks(model), 'remove');
    },
module.exports = function(options) {

  var defaults = {
    proxy: {
      target: options.proxyTarget,
      changeOrigin: true
    }
  };

  options = _.defaults(options || {}, defaults);


  function cacheResolver(req) {

    var target = url.parse(options.proxy.target);
    var outgoing = setupOutgoing({},
      _.assign(options.proxy, {
        target: target
      }), req);

    outgoing = _.pick(outgoing, [
      // https://nodejs.org/docs/v4.4.2/api/url.html
      'protocol', 'slashes',
      'auth',
      'hostname',
      'host', 'port', 
      'path',
      'pathname',
      'query', 'search',
      'hash'
    ]);

    target = _.omit(target, [
      'path',
      'pathname'
    ]);

    // log('proxy target', target);
    // log('outgoing', outgoing);

    outgoing = _.defaults(outgoing, target, {
        protocol: outgoing.port === 80 ? 'http' : outgoing.port === 443 ? 'https' : undefined,
        pathname: outgoing.pathname ||  outgoing.path
    });

    // convert back into URL object
    outgoing = url.parse(url.format(outgoing));

    return _.get(outgoing, 'href');
  }

  var proxy = httpProxy.createProxyServer(options.proxy);

  var cache = options.cache;

  _.invoke(cache, 'store.events.on', 'redisError', function(err) {
    log(err);
  });

  var promisifiedGet = Promise.promisify(cache.get.bind(cache)); 
  var getFromCache = function(cacheKey) {
    return promisifiedGet(cacheKey).then(function(data) {
      if (_.isNil(data)) {
        throw new Error('no data available for key '+cacheKey);
      }
      return data;
    });
  };

  proxy.on('error', function(err, req, res) {
    log('proxy error!', err);
  });

  proxy.on('proxyReq', function(proxyReq, req, res, options) {
    req.proxy = {
      proxyReq: proxyReq,
      options: options
    };

    log('proxying request', proxyReq.method, req.cacheKey);
  });

  proxy.on('proxyRes', function(proxyRes, req, res) {
    log('received response from upstream', req.proxy.proxyReq.method, req.cacheKey, proxyRes.statusCode, proxyRes.statusMessage);
    log('storing headers');

    var headersData =  _.pick(proxyRes, ['statusCode', 'statusMessage', 'headers']);
    cache.set('headers:'+req.cacheKey, headersData);


    var dataStream = proxyRes.headers['content-encoding'] ? proxyRes.pipe(zlib.createUnzip()) : proxyRes;

    var data = [];

    dataStream.on('data', function(chunk) {
      data.push(chunk);
    });


    dataStream.on('end', function() {
      data = Buffer.concat(data).toString('base64');
      if (proxyRes.statusCode === 200) {
        log('storing %s response for %s', proxyRes.statusCode, req.cacheKey);
        cache.set(req.cacheKey, data);
      } else {
        log('not storing %s response for %s ', proxyRes.statusCode, req.cacheKey);
      }
    });
  });

  function cachedProxyMiddleware(req, res, next) {

    var cacheKey = req.cacheKey = cacheResolver(req);

    var headersCacheKey = 'headers:'+cacheKey;

    req.cache = {};

    var reqComplete = {complete: true};

    getFromCache(headersCacheKey).then(function(headersData) {

      log('retrieved %s from cache', headersCacheKey);

      _.assign(req.cache, headersData);

      var cachedEtag = _.get(headersData, 'headers.etag');
      var isFresh = fresh(req.headers, {
        'etag': cachedEtag
      });

      // TODO abstract `isFresh` as one of many validators
      // before returning `304` directly
      if (isFresh) {
        res.sendStatus(304);
        return reqComplete;
      }

      return headersData;

    }).then(function(headersData) {
      if (headersData === reqComplete) {
        return reqComplete;
      }

      return getFromCache(cacheKey);
    }).then(function(data) {

      if (data === reqComplete) {
        return reqComplete;
      }

      // redis returns a pseudo-buffer; create actual Buffer
      data = new Buffer(data, 'base64');

      log('retrieved %s from cache', cacheKey);

      var headers = _.omit(req.cache.headers, ['date', 'content-encoding', 'content-length']);

      res.status(req.cache.statusCode);

      // log(headers);

      res.set(headers);

      res.send(data).end();
    }).caught(function(err) {
      log(err.message);
      proxy.web(req, res);
    }).caught(next);

  }

  // expose proxy for further use,
  // e.g. upgrading web sockets
  cachedProxyMiddleware.proxy = proxy;

  // expose the cache
  cachedProxyMiddleware.cache = cache;

  cachedProxyMiddleware.options = options;

  return cachedProxyMiddleware;

};
Example #25
0
 invoke(...args) {
   return lodash.invoke(this, ...args)
 }
Example #26
0
 function pushState(state, title, url) {
     _state = state;
     _url = url;
     _.invoke(_callbacks, 'apply');
 }
		var pushEmptyArray = function() {
			_.invoke(roomMask, 'push', 0);
		};
Example #28
0
File: app.js Project: mishadev/ost
        this.componentWillUnmount = function() {
            this._base("componentWillUnmount");

            _.invoke(_stores, "off", this._onChange);
        };
 handleClick = e => _.invoke(this.props, 'onClick', e, this.props)
  handleClick = (e) => {
    const { type } = this.props

    if (type !== 'ellipsisItem') _.invoke(this.props, 'onClick', e, this.props)
  }