/** * When a third-party is passing a billion arguments back, reporting that information can get insane fairly quickly. * * This method names each argument, and then tries to reduce any values that has redundant file strings. * @param {Arguments} args * @param {[string]} argumentNames * @returns {object} */ function sanitizeArguments(args, argumentNames) { return _.mapValues(_.zipObject(argumentNames, args), function (value) { if (_.isString(value)) { value = stripRedundantPathInformation(value); } return value; }); }
formatError(err) { let match; match = err.message.match(/Violation of UNIQUE KEY constraint '((.|\s)*)'. Cannot insert duplicate key in object '.*'.(:? The duplicate key value is \((.*)\).)?/); match = match || err.message.match(/Cannot insert duplicate key row in object .* with unique index '(.*)'/); if (match && match.length > 1) { let fields = {}; const uniqueKey = this.model && this.model.uniqueKeys[match[1]]; let message = 'Validation error'; if (uniqueKey && !!uniqueKey.msg) { message = uniqueKey.msg; } if (match[4]) { const values = match[4].split(',').map(part => part.trim()); if (uniqueKey) { fields = _.zipObject(uniqueKey.fields, values); } else { fields[match[1]] = match[4]; } } const errors = []; _.forOwn(fields, (value, field) => { errors.push(new sequelizeErrors.ValidationErrorItem( this.getUniqueConstraintErrorMessage(field), 'unique violation', // sequelizeErrors.ValidationErrorItem.Origins.DB, field, value, this.instance, 'not_unique' )); }); return new sequelizeErrors.UniqueConstraintError({ message, errors, parent: err, fields }); } match = err.message.match(/Failed on step '(.*)'.Could not create constraint. See previous errors./) || err.message.match(/The DELETE statement conflicted with the REFERENCE constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./) || err.message.match(/The INSERT statement conflicted with the FOREIGN KEY constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./) || err.message.match(/The MERGE statement conflicted with the FOREIGN KEY constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./) || err.message.match(/The UPDATE statement conflicted with the FOREIGN KEY constraint "(.*)". The conflict occurred in database "(.*)", table "(.*)", column '(.*)'./); if (match && match.length > 0) { return new sequelizeErrors.ForeignKeyConstraintError({ fields: null, index: match[1], parent: err }); } match = err.message.match(/Could not drop constraint. See previous errors./); if (match && match.length > 0) { return new sequelizeErrors.UnknownConstraintError(match[1]); } return new sequelizeErrors.DatabaseError(err); }
formatError(err) { const errCode = err.errno || err.code; switch (errCode) { case 1062: { const match = err.message.match(/Duplicate entry '(.*)' for key '?((.|\s)*?)'?$/); let fields = {}; let message = 'Validation error'; const values = match ? match[1].split('-') : undefined; const fieldKey = match ? match[2] : undefined; const fieldVal = match ? match[1] : undefined; const uniqueKey = this.model && this.model.uniqueKeys[fieldKey]; if (uniqueKey) { if (uniqueKey.msg) message = uniqueKey.msg; fields = _.zipObject(uniqueKey.fields, values); } else { fields[fieldKey] = fieldVal; } const errors = []; _.forOwn(fields, (value, field) => { errors.push(new sequelizeErrors.ValidationErrorItem( this.getUniqueConstraintErrorMessage(field), 'unique violation', // sequelizeErrors.ValidationErrorItem.Origins.DB, field, value, this.instance, 'not_unique' )); }); return new sequelizeErrors.UniqueConstraintError({message, errors, parent: err, fields}); } case 1451: case 1452: { // e.g. CONSTRAINT `example_constraint_name` FOREIGN KEY (`example_id`) REFERENCES `examples` (`id`) const match = err.message.match(/CONSTRAINT ([`"])(.*)\1 FOREIGN KEY \(\1(.*)\1\) REFERENCES \1(.*)\1 \(\1(.*)\1\)/); const quoteChar = match ? match[1] : '`'; const fields = match ? match[3].split(new RegExp(`${quoteChar}, *${quoteChar}`)) : undefined; return new sequelizeErrors.ForeignKeyConstraintError({ reltype: String(errCode) === '1451' ? 'parent' : 'child', table: match ? match[4] : undefined, fields, value: fields && fields.length && this.instance && this.instance[fields[0]] || undefined, index: match ? match[2] : undefined, parent: err }); } default: return new sequelizeErrors.DatabaseError(err); } }
'sortKeysBy': function (obj, comparator) { var keys = _.sortBy(_.keys(obj), function (key) { return comparator ? comparator(obj[key], key) : key; }); return _.zipObject(keys, _.map(keys, function (key) { return obj[key]; })); }
.end(function(err, res){ if(err) { return callback(err, null); } var $ = cheerio.load(res.text); var formFields = $('form[name=login] input[type=hidden]').map(function(i, element){ var input = $(element); return [[input.attr('name'), input.attr('value')]]; }).get(); callback(null, _.zipObject(formFields)); });
rawCrewMember.each(function (elem, index, array) { //$(this)==elem,因为需要传入一个cheerio对象,所以这样用 var rawMemberDetail = $(this).text().replace(/\n/g, "|").replace(/\s/g, "-").split('|'); //删除首尾的两个空格内容 rawMemberDetail.shift(); rawMemberDetail.pop(); var crewMemberObject = _.zipObject(crewMemberKey, rawMemberDetail); flightObjectArrary.push(crewMemberObject); });
before(async function () { // solc takes a while this.timeout(10000); const contents = await Promise.all(contracts.map(async (filename) => (await promisify(fs.readFile)('./contracts/' + filename)).toString() )); const sources = _.zipObject(contracts, contents); result = solc.compile({ sources }, 1); });
.submit(function(err, relatedResults) { if (err) { relationshipDeferred.reject(err); } else { var keys = _.map(relatedResults.results, 'id'); var related = _.zipObject(keys, relatedResults.results); documents.results[index].loadedDocuments = related; relationshipDeferred.resolve(); } });
function (results, next) { const tidToTopic = _.zipObject(tids, results.topics); const uidToUser = _.zipObject(uids, results.users); postsData.forEach(function (post) { if (results.topics && tidToTopic[post.tid]) { post.topic = tidToTopic[post.tid]; if (post.topic && post.topic.category) { post.category = post.topic.category; } } if (uidToUser[post.uid]) { post.user = uidToUser[post.uid]; } }); postsData = postsData.filter(post => post && post.topic && !post.topic.deleted); next(null, postsData); },
function findSimilarFiles(mainManifest, mainUniquePaths, otherManifest, otherUniquePaths) { // Create inverse lookup table for the otherManifest that maps stringified data to a list of paths with the same hash and filesize // Ignores files that are empty (filesize === 0), because reporting similarities of empty files is not helpful var otherListInverseFileLookup = _.chain(otherManifest).pick(otherUniquePaths).omit(isFilesizeZero).mapValues(JSON.stringify).invert(true).value(); // Create an object that maps a path in the mainManifest to a list of potential duplicates paths from the otherManifest return _.chain(_.zipObject(mainUniquePaths, mainUniquePaths)).mapValues(function(path) { return otherListInverseFileLookup[JSON.stringify(mainManifest[path])]; }).omit(_.isEmpty).value(); }
Async.map(refTuples, derefDependency.bind(this), function(derefErr, dereffedTuples) { if (!derefErr) { var dereffedTable = Lodash.zipObject(dereffedTuples); cb(null, dereffedTable); } else { // console.warn(Chalk.gray('famous'), Chalk.yellow('warn'), 'Couldn\'t resolve some dependencies'); cb(derefErr, depRefTable); } });
res.send(activity.map(function(repo) { var filteredCommits = _.values(repo.commits).filter(function (commit) { return -1 !== commit.Author.Email.indexOf(author) && new Date(commit.Author.When).getTime() / 1000 > since }); return { project: repo.project, repository: repo.repository, commits: _.zipObject(filteredCommits.map(function(c) { return c.Sha }), filteredCommits) }; }).filter(function(repo) {
function rowToGeoJSON(header, row) { let properties = _.zipObject(header, row); return { type: 'Feature', id: properties.CODE_POSTAL, label: properties.COMMUNE, geometry: { type: 'Point', coordinates: [ +properties.LONGITUDE, +properties.LATITUDE ] }, properties: _.omit(properties, [ 'LONGITUDE', 'LATITUDE' ]) }; }
redis.hmget('notifications:' + request.user.id, keys, function (error, values) { if (error) { reject(error); return; } resolve({ notifications: _.zipObject(keys, values.map(toInteger)) }); });
componentDidMount: function () { // component is now in the DOM var self = this var DOMNode = ReactDOM.findDOMNode(this) this.pc = d3.parcoords({ //alpha: 0.2, color: "#069", shadowColor: "#f3f3f3", // does not exist in current PC version width: this.props.width, height: this.props.height, dimensionTitleRotation: this.props.dimensionTitleRotation || -50, margin: { top: 33, right: 0, bottom: 12, left: 0 }, nullValueSeparator: "bottom" })( DOMNode ) var ratio = 100/this.props.data.length; var types = _.zipObject(_.map(this.props.dimensions, (d, key)=>{return key}), _.map(this.props.dimensions, (d)=>{return d.type})) //var dimensions = _.map(this.props.dimensions, (d, key)=>{return key}) //var dimensionTitles = _.map(this.props.dimensions, (d)=>{return d.description}) var dimensions = _.map(this.props.dimensionsVisible, (d, key)=>{return d.value}) var dimensionTitles = _.map(this.props.dimensionsVisible, (d, key)=>{return d.label}) this.pc = this.pc .data(this.props.data) .alpha( _.min([1,_.max([ratio,0.04])]) ) .composite("source-over") // globalCompositeOperation "darken" may be broken in chrome, "source-over" is boring .mode("queue") // // TODO: once dimensions-metadata is available in d3 par coords, this will be a single call .types(types) .dimensions(dimensions) // show/hide dimensions [0,1,2,3,4,5] .dimensionTitles(dimensionTitles) .render() .shadows() ////////////.commonScale(false, "number", [0,1]) ////////////.tickValues([0.00,0.25,0.50,0.75,1.00]) //[0,0.25,0.5,0.75,1.0] ////////////.tickFormat('') .createAxes() .reorderable() .brushMode("1D-axes") // enable brushing .on("brushend", function (d) { self.onBrushEnd(d) }) .on("brush", function (d) { self.onBrush(d) }) //////////.on("resize", function (d) { console.log('onResize') }) //////////.on("highlight", function (d) { console.log('onHighlight') }) //////////.on("render", function (d) { console.log('onRender') }) if (this.props.initialBrushExtents) {// set initial brushes this.pc.brushExtents(this.props.initialBrushExtents) } //this.pc.render() },
function run_(opts) { opts = _.defaults(opts || {}, { browsers: ['default-browser'], files: ['default-file'] }); var tests = _.zipObject(opts.browsers, _.fill(Array(opts.browsers.length), opts.files)), runner = opts.runner || new Runner(makeConfigStub({browsers: opts.browsers})); return runner.run(tests); }
getInitialState: function() { /* * Keeps track of sort direction on each column. */ var directionHash = _.zipObject(this.props.columns, _.times(this.props.columns.length, function() { return 'ascending'; })); return { directionHash: directionHash }; },
this.files.forEach(function(file) { var locales = file.src.filter(function(filepath) { if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { return true; } }).map(function(filepath) { return grunt.file.readJSON(filepath); }); locales = _.zipObject(_.pluck(locales, "lang_code"), locales); _.mapValues(locales, function(e, i) { var lang = e.lang_code.replace("-widgets", ""); if (e.lang_code.indexOf("-widgets") !== -1 && locales[lang]) { delete locales[e.lang_code]; delete e.lang_code; _.assign(locales[lang].widgets, e); } }); var outDir = this.options().outDir; _.each(locales, function(e, i) { var data = { lang_code: { message: i }, extDescription: { message: e.extDescription }, extName: { message: e.extName }, themes_upload_image: { message: e.themes.upload_image } }; grunt.file.write(outDir + "/_locales/" + i.replace("-", "_") + "/messages.json", JSON.stringify(data)); }); grunt.file.write(file.dest, "define(" + JSON.stringify(locales) + ");"); grunt.log.writeln('File "' + file.dest + '" created.'); }.bind(this));
/** * Transform a collection of schema entities into model objects, suitable for rendering. The returned * object will contain model objects, keyed by their slugified title or id. */ function entitiesToModel(entities) { entities = util.isArray(entities) ? entities : [entities]; entities = _.map(entities, entityToModel); entities.sort(function(a, b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; }); entities = _.zipObject(_.pluck(entities, "slug"), entities); return entities; }
// sort object keys in alp order sortKeysBy( obj, comparator ) { let keys = _.sortBy( _.keys(obj), (key) => { return comparator ? comparator(obj[key], key) : key; }); return _.zipObject( keys, _.map(keys, (key) => { return obj[key]; })); }
modelIns.findOne(id).then(function (record) { if (!record) { res.notFound() } else { var data = _.zipObject([model, 'user'], [record, req.session.user || {}]) if( req.param('preload') == 'string' ){ data = JSON.stringify(data) } res.view(file, {data : data}) } }).fail(function (err) {
converterField.thermocycleDyes = function (input) { var filtered = _.filter(input, function (item) { return _.result(item, 'wells', []).length; }); //todo -verify a dye was selected, or use defualt. currently view is reponsible for guarantee var zipped = _.zipObject(_.pluck(filtered, 'dye'), _.pluck(filtered, 'wells')); if (_.keys(zipped).length == 0) { return null; } return zipped; };
drone.on('server.onRoundOverTeamScores', function(words) { let scores = words.splice(1, words[0] * 1); let data = _.zipObject([ 'numberOfScores', 'targetScore', ], words); data.scores = scores; winston.info('server.onRoundOverTeamScores', data); state.round.scores = data.scores; state.round.targetScore = data.targetScore; roundOver(); });
_forEach(columnNames, (value, key) => { let columns; // Convert column names to an object so it can // be passed to Model#format if (_isArray(columnNames[key])) { columns = _zipObject(columnNames[key], null); } else { columns = _zipObject(columnNames, null); } // Format column names using Model#format if (_isArray(columnNames[key])) { columnNames[key] = _keys(this.format(columns)); } else { columnNames = _keys(this.format(columns)); } });
drone.on('server.onLevelLoaded', function(words) { let data = _.zipObject([ 'map', 'mode', 'roundsPlayed', 'roundsTotal' ], words); winston.info('server.onLevelLoaded', data); startRound(Date.now(), false); state.round.map = data.map; state.round.mode = data.mode; });
// helper to generate human-friendly errors. // adapted version from less_engine.js function sassError(ctx /*, options*/) { // libsass error string format: path:line: error: message var error = _.zipObject( [ 'path', 'line', 'level', 'message' ], ctx.split(':', 4).map(function(str) { return str.trim(); }) ); if (error.line && error.level && error.message) { return new Error('Line ' + error.line + ': ' + error.message); } return new Error(ctx); }
connection.query('desc ' + tableName, function(err, data) { if (err) { reject(); return; } schemaDef[tableName] = data; pendingCount -= 1; obj[tableName] = _.zipObject(_.map(data, 'Field'), _.map(data, 'Type')); tableMapped[tableName] = _.camelCase(tableName); fields = fields.concat(_.map(data, 'Type')); resolve(); });
QueryStringSerializer.prototype.deserialize = function (query) { if (!query) return {}; var parameters = query.split("&"), values = _.map(parameters, function (value) { var parts = value.split("="); return { key: parts[0], value: parts[1] }; }); return _.zipObject(_.map(values, 'key'), _.map(values, 'value')); };
_.each(['sample', 'anemometer'], function(db) { _.each( _.zipObject(['create', 'drop'], ['PUT', 'DELETE']), function(method, action) { httpConfig[action + '-' + db + '-db'] = { options: { url: '<%= env.couchdb.basePath %>' + db, method: method, auth: auth } } }) })
function (results, next) { const cidToCategory = _.zipObject(cids, results.categories); topicsData.forEach(function (topic, index) { if (topic && results.categories && cidToCategory[topic.cid]) { topic.category = cidToCategory[topic.cid]; } if (topic && results.tags && results.tags[index]) { topic.tags = results.tags[index]; } }); next(null, topicsData); },