Example #1
0
 function toJS(track) {
     return {
         name: track.name(),
         artistCredit: _.map(
             track.artistCredit().names.toJS(),
             _.partialRight(_.omit, ['artist', 'automaticJoinPhrase'])
         )
     };
 }
Example #2
0
              _(Model.associations).where({type: 'collection'}).forEach(function (association) {
                var alias = association.alias;
                var _getAssocRoute = _.partialRight(util.format, baseRoute, alias);
                var opts = _.merge({ alias: alias }, routeOpts);

                sails.log.silly('Binding "shortcuts" to association blueprint `'+alias+'` for',controllerId);
                _bindRoute( _getAssocRoute('%s/:parentid/%s/add/:id?'),      'add' , opts );
                _bindRoute( _getAssocRoute('%s/:parentid/%s/remove/:id?'),   'remove', opts );
              });
Example #3
0
            _(Model.associations).where({type: 'collection'}).forEach(function (association) {
              var alias = association.alias;
              var _getAssocRoute = _.partialRight(util.format, baseRoute, alias);
              var opts = _.merge({ alias: alias }, routeOpts);
              sails.log.silly('Binding RESTful association blueprint `'+alias+'` for',controllerId);

              sails.router.bind( _getAssocRoute('post %s/:parentid/%s/:id?'),     _getAction('add'), null, opts );
              sails.router.bind( _getAssocRoute('delete %s/:parentid/%s/:id?'),   _getAction('remove'), null, opts );
            });
function saveObjects(t) {
  t.plan(1);

  index.saveObjects(objects)
    .then(get('taskID'))
    .then(index.waitTask)
    .then(get('status'))
    .then(_.partialRight(t.equal, 'published', 'Objects were saved'))
    .then(noop, _.bind(t.error, t));
}
function deleteIndex(t) {
  t.plan(1);

  client.deleteIndex(indexName)
    .then(get('taskID'))
    .then(index.waitTask)
    .then(get('status'))
    .then(_.partialRight(t.equal, 'published', 'Index was deleted'))
    .then(noop, _.bind(t.error, t));
}
Example #6
0
 $('.author-token').mouseleave(function(e) {
   var tokenClass = _.find(e.target.classList, _.ary(_.partialRight(_.startsWith, 'author-tokenid'), 1));
   if (!tokenClass) {
     return;
   }
   var tokenId = tokenClass.split('-')[2];
   if (timeouts[tokenId]) {
     clearTimeout(timeouts[tokenId]);
   }
 });
Example #7
0
function defaults(obj, defaultOps) {
    defaults.innerFun = defaults.innerFun || _.partialRight(_.assign, function(a, b) {
        return typeof a == 'undefined' ? b : a;
    });
    if (_.isPlainObject(obj) || obj === undefined) {
        obj = obj || {};
        defaults.innerFun(obj, defaultOps);
    }
    return obj;
}
 before(() => {
   return App.setup()
   .then(() => Admin.removeAsync())
   .then(() => AdminSeed.seed(adminsToSeed))
   .then(_.partialRight(TestUtils.prepareSeededObjects, Settings.Admin.paths, (item) => item.email))
   .then((seeded) => {
     seededAdmins = seeded;
     return agentUtils.performLogin(_.first(seeded).email, 'test');
   });
 });
Example #9
0
            .map(function(value, key) {
                var o = {}
                o[column_name] = key,
                o.count = value.length

                if (num_columns > 1) {
                    o.children = _.map(value, _.partialRight(_.omit, column_name))
                }
                return o
            })
            _.mapKeys(Model.associations, function(value, key){
              var foreign = value.options;
              var alias = foreign.as || foreign.name || foreign;
              var _getAssocRoute = _.partialRight(util.format, baseRestRoute, alias);
              var opts = _.merge({ alias: alias, target: value.target.name }, routeOpts);
              sails.log.silly('Binding RESTful association blueprint `'+alias+'` for',controllerId);

              _bindRoute(_getAssocRoute('post %s/:parentid/%s/:id?'), 'add', opts);
              _bindRoute(_getAssocRoute('delete %s/:parentid/%s/:id?'), 'remove', opts);
            });
        beforeEach(function (done) {
            let createFunc = _.partialRight(fixtureFilePath ? SequelizeMocking.createAndLoadFixtureFile : SequelizeMocking.create, options);

            createFunc(originalSequelize, fixtureFilePath)
                .then(function (sequelizeInstance) {
                    mockedSequelize = sequelizeInstance;
                    done();
                })
                .catch(done);
        });
Example #12
0
				function (callback) {
					request({
						method: 'get',
						path: '/ping',
						headers: { 'x-fancy-access-token': token }
					},
						null,
						_.partialRight(testResponse, callback)
					);
				}
Example #13
0
  return function omit(context, cb) {

    var input = context.input;

    if (Array.isArray(context.output)) {
      cb(null, _.map(context.output, _.partialRight(_.omit, input)));
    } else {
      cb(null, _.omit(context.output, input));
    }
  }
    newTest = beforeEach(currentTestInstance ? currentTestInstance : test, function (assert) {
        let createFunc = _.partialRight(fixtureFilePath ? SequelizeMocking.createAndLoadFixtureFile : SequelizeMocking.create, options);

        createFunc(originalSequelize, fixtureFilePath)
            .then(function (sequelizeInstance) {
                mockedSequelize = sequelizeInstance;
                assert.end();
            })
            .catch(assert.end);
    });
/**
 * Get the latest or greatest versions from the NPM repository
 * @param packageMap   an object whose keys are package name and values are current versions
 * @param options       Options. Default: { versionTarget: 'latest' }. You may also specify { versionTarge: 'greatest' }
 * @returns             Promised {packageName: version} collection
 */
function getLatestVersions(packageMap, options) {

    var getPackageVersion;
    options = options || {};

    var packageList = Object.keys(packageMap);

    // validate options.versionTarget
    options.versionTarget = options.versionTarget || 'latest';

    // determine the getPackageVersion function from options.versionTarget
    switch (options.versionTarget) {
        case 'latest':
            getPackageVersion = selectedPackageManager.latest;
            break;
        case 'greatest':
            getPackageVersion = selectedPackageManager.greatest;
            break;
        case 'newest':
            getPackageVersion = selectedPackageManager.newest;
            break;
        case 'major':
            getPackageVersion = selectedPackageManager.greatestMajor;
            break;
        case 'minor':
            getPackageVersion = selectedPackageManager.greatestMinor;
            break;
        default:
            var supportedVersionTargets = ['latest', 'newest', 'greatest', 'major', 'minor'];
            return Promise.reject(new Error('Unsupported versionTarget: ' + options.versionTarget +
                '. Supported version targets are: ' + supportedVersionTargets.join(', ')));
    }

    // ignore 404 errors from getPackageVersion by having them return null instead of rejecting
    function getPackageVersionProtected(dep) {
        return getPackageVersion(dep, packageMap[dep]).catch(function (err) {
            if (err.message == 404) { // eslint-disable-line eqeqeq
                return null;
            } else {
                throw err;
            }
        });
    }

    // zip up the array of versions into to a nicer object keyed by package name
    function zipVersions(versionList) {
        return cint.toObject(versionList, function (version, i) {
            return cint.keyValue(packageList[i], version);
        });
    }

    return Promise.map(packageList, getPackageVersionProtected)
        .then(zipVersions)
        .then(_.partialRight(_.pickBy, _.identity));
}
Example #16
0
    value: function find(patterns) {
      var aliases = this.aliases;
      var names = _.keys(aliases);
      var matcher = _.partialRight(minimatch.filter, { matchBase: true });

      return _.chain(patterns).map(function (pattern) {
        return names.filter(matcher(pattern));
      }).flattenDeep().reduce(function (found, name) {
        return found.concat(aliases[name]);
      }, []).value();
    }
Example #17
0
  _.each(swagger.paths, function (path) {
    var intersection = _.spread(_.partialRight(_.intersectionWith, _.isEqual));
    var pathArgs = _(path).pick(SwaggerMethods).map('parameters').value();
    pathArgs = intersection(pathArgs);

    if (_.isNull(globalArgs)) {
      globalArgs = pathArgs;
      return;
    }
    globalArgs = intersection([globalArgs, pathArgs]);
  });
Example #18
0
function requestDecision(req, res, next, options, grants){
    var authCode     = grants.authorization_code
      , redirect     = req.query.redirect_uri
      , responseType = req.query.response_type
      , clientId     = req.query.client_id
      , sendError    = _.partialRight(exports._respondWithError, res )
      , grantCode    = _.partialRight(authCode.grantCode, redirect, responseType, clientId, options)
      , errs         = [];

    _.each(['client_id', 'redirect_uri', 'response_type'], function(param){
        if ( req.query[param] === undefined )
            errs.push(param + ' is a required parameter');
    })
    
    if ( errs.length )
        return sendError(new errors.InvalidRequestError(errs.join(' ')))
    
    if ( ~redirect.indexOf('#') ){
        return sendError(new errors.InvalidRequestError('redirect_uri cannot contain a hash (#) fragment.') )
    }
    
    if ( responseType !== 'code' && responseType !== 'token')
        return sendError(new errors.InvalidRequestError('the response_type must either be \'token\' or \'code\''))
    
    authCode
        .resourceOwnerApproval(req, res, clientId, redirect, options)
        .then(grantCode)
        .then(function(code){
            var frag = responseType === 'token' 
                ? '#access_token=' + code + '&token_type=bearer'
                : !~redirect.indexOf('?')
                    ? '?' + 'code=' + code
                    : '&' + 'code=' + code;

            res.writeHead(302, { 'Location': redirect + frag })
            return res.end()
        })
        .catch(function(err){
            exports._respondWithError(err, res, redirect)
        })
}
Example #19
0
  condition(proNumber = "", digits = 9) {
    var clean, convert

    if(proNumber === "" || proNumber === null) {
      return ""
    }

    clean = this.clean.bind(this)
    convert = _.partialRight(this.convert.bind(this), digits)

    return _.flowRight(convert, clean)(proNumber)
  }
Example #20
0
Producer.prototype.send = function (data, options) {
    var self = this, hash, promise, task;

    if (!Array.isArray(data)) {
        data = [data];
    }

    options = _.merge({}, {
        codec: self.options.codec,
        retries: self.options.retries,
        batch: self.options.batch
    }, options || {});

    hash = [
        options.codec,
        options.retries.attempts,
        options.retries.delay.min,
        options.retries.delay.max,
        options.batch.size,
        options.batch.maxWait,
    ].join('.');

    if (self.queue[hash] === undefined) {
        promise = new Promise(function (resolve, reject) {
            self.queue[hash] = {
                timeout: null,
                resolve: resolve,
                reject: reject,
                options: options,
                data: [],
                dataSize: 0
            };
        });
        self.queue[hash].promise = promise;
    }

    task = self.queue[hash];
    task.data.push(data);
    task.dataSize += _.sumBy(data, _.partialRight(_.get, 'message.value.length', 0));

    if (task.dataSize >= options.batch.size || options.batch.maxWait === 0) {
        if (task.timeout !== null) {
            clearTimeout(task.timeout);
        }
        self._send(hash);
    } else if (task.timeout === null) {
        task.timeout = setTimeout(function () {
            self._send(hash);
        }, options.batch.maxWait);
    }

    return task.promise;
};
/**
 * Get the latest versions from the NPM repository
 * @param packageList   A list of package names to query
 * @param options       Options. Default: { versionTarget: 'latest' }. You may also specify { versionTarge: 'greatest' }
 * @returns             Promised {packageName: version} collection
 */
function getLatestVersions(packageList, options) {

    options = options || {};

    // configure registry
    if (options.registry) {
        npm.config.set('registry', options.registry);
    }

    // validate options.versionTarget
    options.versionTarget = options.versionTarget || 'latest';

    // determine the getPackageVersions function from options.versionTarget
    switch (options.versionTarget) {
        case('latest'):
            getPackageVersion = getLatestPackageVersion;
            break;
        case('greatest'):
            getPackageVersion = getGreatestPackageVersion;
            break;
        default:
            var supportedVersionTargets = ['latest', 'greatest'];
            return Promise.reject('Unsupported versionTarget: ' + options.versionTarget + '. Supported version targets are: ' + supportedVersionTargets);
    }

    // TODO: It would be better here to create an object of promised versions, keyed by the package name, instead of an array. This should make the final _.pick unnecessary and subsequently allow the whole PromiseInspection logic to be generalized

    return Promise.settle(packageList.map(getPackageVersion))
        // convert the array of versions to a nicer object keyed by package name
        .then(function (versions) {
            return Promise.map(versions, function (version) {
                if (version.isRejected()) {
                    var reason = version.reason();
                    if (reason.statusCode === 404) {
                        return null;
                    }
                    else {
                        throw reason;
                    }
                }
                else {
                    return version.value();
                }
            });
        })
        .then(function (versions) {
            return cint.toObject(versions, function (version, i) {
                return cint.keyValue(packageList[i], version);
            });
        })
        .then(_.partialRight(_.pick, _.identity))
}
Example #22
0
	grunt.registerTask('index', "compiles index.html", function(){
		var process = _.compose(
				_.bind(grunt.file.write, grunt.file, './deploy/index.html'),
				_.partialRight(_.bind(grunt.template.process, grunt.template), {
					data : {
						jsFiles : ['app/vendor.js', 'app/templates.js', 'app/app.js'],
						cssFiles : ['static/css/index.css']
					}
				}),
				_.bind(grunt.file.read, grunt.file, './src/index.html')
			);
		process();
	});
Example #23
0
const withToolTip = WrappedComponent => props => {
	// inject interval props to renderTooltipForDatanum
	const renderTooltipForDatanum = props.renderTooltipForDatanum
		? partialRight( props.renderTooltipForDatanum, props.tooltipInterval )
		: null;

	const newProps = {
		...props,
		renderTooltipForDatanum,
	};

	return <WrappedComponent { ...newProps } />;
};
Example #24
0
    return _.map(categories, ({ childKey, ...category }) => {
      const categoryProps = {
        key: childKey || category.name,
        active: _.inRange(selectedIndex, count, count + category.results.length),
        renderer: categoryRenderer,
        ...category,
      }
      const renderFn = _.partialRight(this.renderResult, count)

      count += category.results.length

      return <SearchCategory {...categoryProps}>{category.results.map(renderFn)}</SearchCategory>
    })
function clearIndex(t) {
  t.plan(1);

  index.clearIndex()
    // clear index
    .then(get('taskID'))
    .then(index.waitTask)
    .then(get('status'))
    .then(_.partialRight(t.equal, 'published', 'Index was cleared'))
    // we do not use .catch since it's a reserved word in IE8
    // https://github.com/jakearchibald/es6-promise/issues/20
    .then(noop, _.bind(t.error, t));
}
Example #26
0
exports.connect = function(storePropName, propertyOfState, filter){

	var filterFunc;
	if (filter === undefined)
		filterFunc = _.identity;
	else if (typeof filter === 'string')
		filterFunc = _.partialRight(_.pluck, filter);
	else
		filterFunc = _.partialRight(_.pick, filter);

	var propTypes = {};
	propTypes[storePropName] = storePropValidator;

	return {
		propTypes: propTypes,
		getInitialState: function(){
			var state = {};
			if (propertyOfState) // non-empty string
				state[propertyOfState] = filterFunc(this.props[storePropName].getInitialState());
			else
				state = filterFunc(this.props[storePropName].getInitialState());
			return state;
		},
		componentDidMount: function(){
			_.extend(this, Reflux.ListenerMethods);
			if (propertyOfState) {
				this.listenTo(this.props[storePropName], function(state){
					var newState = {};
					newState[propertyOfState] = filterFunc(state);
					this.setState(newState);
				}.bind(this));
			} else {
				this.listenTo(this.props[storePropName], _.compose(this.setState, filterFunc));
			}
		},
		componentWillUnmount: Reflux.ListenerMixin.componentWillUnmount
	};
};
Example #27
0
module.exports.validateToken = function (req, res, next, options) {
    var path = url.parse(req.url ).pathname
      , requestingToken = req.method === 'POST' && path === options.tokenEndpoint
      , requestingCode  = req.method === 'GET'  && path === options.authorizeEndpoint
      , sendError       = _.partialRight(exports._respondWithError, res )
      , auth     = req.authorization || {}
      , inHeader = !!(auth.credentials)
      , inQuery  = !!(req.query && req.query.access_token)
      , inBody   = !!(req.body  && req.body.access_token)
      , token_type = inHeader ? auth.scheme : inBody ? req.body.token_type : req.query.token_type
      , token;

    //console.log(requestingCode, options.grants )

    if ( requestingToken || (requestingCode && _.contains(options.grants, 'authorization_code') )) 
        return next();
    
    if ( inHeader + inBody + inQuery === 0 )
        return sendError(new errors.InvalidRequestError(
            'access_token not included in the request' ))

    else if ( inHeader + inBody + inQuery > 1 )
        return sendError(new errors.InvalidRequestError(
            'access_token can only be specified in either the: header, body, or query, once' ))

    if ( !token_type || token_type.toLowerCase() !== 'bearer' )
        return sendError(new errors.InvalidRequestError('token_type missing or invalid' ))

    token = inHeader
        ? auth.credentials
        : inQuery 
            ? req.query.access_token
            : req.body.access_token
  
    options.hooks.validateToken(token, function(err, valid){
        if ( err )   return sendError(err);
        if ( valid ) return next();

        res.setHeader('Link',
                '<' + options.tokenEndpoint + '>; rel=\'oauth2-token\'; ' +
                'grant-types=\'' + options.grants.join(', ') +'\'; token-types=\'bearer\'');

        res.setHeader('WWW-Authenticate',
            'Bearer realm=\'' + options.realm + '\', ' +
            'error=\'401\', ' +
            'error_description=\'Client not authorized\'')

        sendError(new errors.UnauthorizedClient('Client not authorized')); 
    });
}
Example #28
0
    initDefaults: function (config) {
        var streams = exports.init(config),
            redirect = _.partial(redirectToSearchPage, config),
            redirectWithoutLocation = _.partialRight(redirect, undefined);

        streams.filterNonGeocodeObjectStream.onValue(redirectWithoutLocation);
        streams.geocodedLocationStream.onValue(function (wmCoords) {
            // get the current state of the search dom
            var filterObj = Search.buildSearch(streams.elems);
            redirect(filterObj, wmCoords);
        });

        streams.resetStream.onValue(Search.reset, streams.elems);
    },
Example #29
0
exports.run = function (argv) {
  var services = service.list();

  if (argv.json) {
    var names = _.pluck(services, "name");
    var metas = _.map(services, _.partialRight(_.omit, "name"));
    console.log(JSON.stringify(_.zipObject(names, metas), null, "  "));
  } else {
    _.each(service.list(), function (meta) {
      console.log(meta.desc ? "%s - %s" : "%s", meta.name, meta.desc);
      console.log("    Repo format: %s", meta.repo || "Undocumented");
    });
  }
};
Example #30
0
    trigger: function trigger(event, payload, options) {
        var tasks;

        function doQuery(options) {
            return models.Webhook.findAllByEvent(event, options);
        }

        tasks = [
            doQuery,
            _.partialRight(makeRequests, payload, options)
        ];

        return pipeline(tasks, options);
    }