function loadedData(sectorStrata) { let radius = 300; let width = 810, height = 1200; let root = d3.select('#bubbles'); let center = {x: width/2, y: 300}; let subSectorIndex = _.mapObject(_.invert(_.uniq(_.pluck(sectorStrata, 'subSector'))), parseInt); let subSectorNodes = agrregateBy(sectorStrata, 'subSector'); let strataNodes = sectorStrata.map(d => { return { id: d.subSector + '-' + d.strata, name: d.strata, subSector: d.subSector, strata: d.strata, income: parseFloat(d.income), expend: parseFloat(d.expend), count: parseInt(d.count, 10), }; }); let fillRange = d3.scale.linear() .domain([0, _.size(subSectorIndex)]).range(["#D3ECE7", "#8ACAC0"]); let fillColor = d => fillRange(subSectorIndex[d.subSector]); // let subSectorNodes = _.groupBy(sectorStrata, 'subSector').map((stratas, subSector) => { // let // // let bubbleRadius= = (((d.income / avgPowAmount) * radius) / data.length) * 2e9 // let bubbleRadius = radiusScale(income); // //radiusScale(d.income); // if (!(d.id in nodesIndex)) { // let r = Math.random() * (radius - bubbleRadius); // let a = Math.random() * Math.PI * 2; // let [x,y] = pol2cart(r, a, radius, radius); // nodesIndex[d.id] = {id: d.id, x, y}; // nodes.push(nodesIndex[d.id]); // } // let node = nodesIndex[d.id]; // _.extend( // node, // { // radius: bubbleRadius, // subData: d.subData, // data: d, // }); // }); const COLS = 4; function rowAndCol(d) { let sIndex = subSectorIndex[d.subSector]; let col = (sIndex % COLS); let row = Math.floor(sIndex / COLS); return [row, col]; } function strataCenter (d) { let [row, col] = rowAndCol(d); return {x: col * 180 + 130, y: row * 220 + 140}; } // Should be the same as strataCenter, hacking to work round issues function labelsCenter (d) { let [row, col] = rowAndCol(d); // Horrible hack let adjustRow = [-30, -10, 10, 20, 40]; let adjustCol = [-20, 2, 15, 30] return {x: col * 180 + 130 + adjustCol[col], y: row * 220 + 140 + adjustRow[row] + 90}; } function stratas() { let indexed = _.groupBy(strataNodes, 'subSector'); subSectorNodes.forEach(n => { let parents = indexed[n.subSector]; n.px = n.x = d3.mean(parents, d => d.x); n.py = n.y = d3.mean(parents, d => d.y); }); vis.update(subSectorNodes, d => center); labels.update(false); subSectorsButton.style({ 'background-color': 'white', 'color': '#522574', }); stratasButton.style({ 'background-color': '#522574', 'color': 'white', }); } function subSectors() { let indexed = _.indexBy(subSectorNodes, 'subSector'); strataNodes.forEach(n => { let parent = indexed[n.subSector]; let noise = () => Math.random() * 50 - 25; n.px = n.x = parent.x + noise(); n.py = n.y = parent.y + noise(); }); vis.update(strataNodes, strataCenter); labels.update(true); subSectorsButton.style({ 'background-color': '#522574', 'color': 'white', }); stratasButton.style({ 'background-color': 'white', 'color': '#522574', }); } let buttons = root.append('div'); let stratasButton = buttons.append('button') .text('ALL') .on('click', stratas); let subSectorsButton = buttons.append('button') .text('BY SUB-SECTOR') .on('click', subSectors); buttons.selectAll('button') .style({ 'margin-right': '8px', 'background-color': 'white', 'border': '1px solid #522574', 'color': '#522574', 'font-size': '14px', 'font-family': 'sans-serif', 'padding-top': '5px', 'padding-bottom': '5px', 'padding-left': '20px', 'padding-right': '20px', 'text-transform': 'uppercase', }) let bubbleContainer = root.append('svg') .attr('width', width) .attr('height', height) .append('g') // .attr('transform', `translate(${width/2}, ${height/2})`); let labels = gridLabels({data: subSectorNodes, container: bubbleContainer, center: labelsCenter}); let popover = root.append('div') .style({ 'font-family': 'museo-sans, helventica, sans-serif', 'padding-left': '18px', 'padding-right': '18px', 'padding-top': '16px', 'padding-bottom': '14px', border: '1px solid #94BFB7', 'border-radius': '2px', 'background-color': '#ffffff', 'color': '#645C5D', 'font-size': '16px', 'line-height': '23px', }); function updatePopover(fields) { let fieldEls = popover.selectAll('div').data(fields); fieldEls.exit(); let enter = fieldEls.enter() .append('div'); enter.append('span').attr('class', 'name').style({color: '#706F6F'}); enter.append('span').attr('class', 'value').style({'font-weight': 'bold', color: '#522977'}) fieldEls.select('.name').text(d => d.name + ': '); fieldEls.select('.value').text(d => d.value); popover.style({ position: 'absolute', display: 'block', }); } let vis = bubblesVis({container: bubbleContainer, width, height, subSectorIndex, radius, maxAmount: d3.max(subSectorNodes, d => d.income), fillColor}) .on('mouseover', function (d, i) { let inSubSectorView = !!d.strata; d3.selectAll('.node').attr("stroke", (dd,ii) => { if (inSubSectorView) { return (dd.strata === d.strata) ? "#94BFB7" : 'none' } else { return (d === dd) ? "#94BFB7" : 'none'; } }); updatePopover([ (inSubSectorView ? {name: 'Income band', value: d.strata} : {name: 'Sub-Sector', value: d.subSector}), {name: 'Total income', value: formatMoney(d.income)}, {name: 'Total spending', value: formatMoney(d.expend)}, {name: 'Number of organisations', value: formatCount(d.count)}, ]); }) .on('mousemove', () => { let [x,y] = d3.mouse(root[0][0]); popover.style({ left: (x+20) + 'px', top: (y+20) + 'px', }); }) .on('mouseout', function (d, i) { d3.selectAll('.node').attr("stroke", 'none'); popover.style({ display: 'none', }); }); stratas(); }
_toolArchitectures: function () { var self = this; var toolArches = _.pluck(self.toolsOnDisk, 'arch'); self.includeTool && toolArches.push(archinfo.host()); return _.uniq(toolArches).sort(); },
.then(function(created) { debug('[syncLabels] finished: created=`%j`', created.length) return _.uniq(synced.concat(created)) })
setResults(results, cb){ this.setState({ 'results' : _.uniq(results, false, object.itemUtil.atId) }, cb); }
/** * Similar to BackboneViewWidget, but more simplistic * @param {Function} ViewConstructor Constructor function for the view * @param {Object} model Model data * @param {Function} template Template function * @param {Object} options Options object from set call * @param {String} key VDom Key */ function ComponentWidget(ViewConstructor, model, template, options, key) { this.ViewConstructor = ViewConstructor; this.model = model; this.model.isComponentModel = true; this.template = template; this.key = key || _.uniqueId('w_component'); this.model.session = (this.model.session || []).concat(['content', 'yield']); if (typeof TUNGSTENJS_DEBUG_MODE !== 'undefined') { this.model._private = { content: true, yield: true }; } // Start with generic model functions var methodsToExpose = modelFunctionsToMap; // Add any methods declared by the model if (model.exposedFunctions && _.isArray(model.exposedFunctions)) { methodsToExpose = methodsToExpose.concat(model.exposedFunctions); } // Add any methods declared by the component if (options && options.exposedFunctions && _.isArray(options.exposedFunctions)) { methodsToExpose = methodsToExpose.concat(options.exposedFunctions); } // dedupe methodsToExpose = _.uniq(methodsToExpose); var i, fn; for (i = 0; i < methodsToExpose.length; i++) { fn = methodsToExpose[i]; if (typeof model[fn] === 'function') { if (typeof this[fn] === 'undefined') { this[fn] = _.bind(model[fn], model); } else { errors.cannotOverwriteComponentMethod(fn); } } } if (options && options.exposedEvents === true || model.exposedEvents === true) { this.exposedEvents = true; } else { this.exposedEvents = []; if (options && options.exposedEvents && _.isArray(options.exposedEvents)) { this.exposedEvents = this.exposedEvents.concat(options.exposedEvents); } if (model.exposedEvents && _.isArray(model.exposedEvents)) { this.exposedEvents = this.exposedEvents.concat(model.exposedEvents); } this.exposedEvents = _.uniq(this.exposedEvents); } // Other model functions should be present, but noops for (i = 0; i < modelFunctionsToDummy.length; i++) { fn = modelFunctionsToDummy[i]; this[fn] = getDummyFunction(fn); } // Setting some values for Collection use this.idAttribute = 'key'; this.attributes = model.attributes; this.cid = model.cid; if (options && options.collection) { // If passed a collection during construction, save a reference this.collection = options.collection; } // Ensure that destroying the model destroys the component if (typeof this.model.destroy === 'function') { var self = this; var _destroy = _.bind(this.model.destroy, this.model); this.model.destroy = function(opts) { if (self.collection) { self.collection.remove(self); } else if (self.parent) { self.parent.unset(self.parentProp); } _destroy(opts); }; } }
}, function(err, data) { data = _.map(data, function(name) { return getClassName(name); }); res.send(_.uniq(data)); });
pkg.on('resolve', function () { var deps = _.pluck(pkg.getDeepDependencies(), 'name'); assert.deepEqual(_.uniq(deps), ["package-bootstrap", "jquery-ui", "jquery"]); next(); });
Object.keys(oshops).forEach(function(slug){ total=amount=count=totalfees=0; monthorder=[]; result.shops[slug]={items:[]}; // // repport by shop oshops[slug].items.sort(Orders.sortByDateAndUser).forEach(function(item){ // // map user items if(!result.users[item.customer.displayName]){ result.users[item.customer.displayName]={} } // // map shops items // why the showAll??? if(item.fulfillment.status==='fulfilled'){ // compute order/mont for this shop monthorder.push(item.oid); // customer item if(!result.users[item.customer.displayName][item.sku]){ result.users[item.customer.displayName][item.sku]={count:0,amount:0,title:item.title} } result.users[item.customer.displayName][item.sku].count+=item.quantity; result.users[item.customer.displayName][item.sku].amount+=item.finalprice; // shop item result.shops[slug].items.push({ oid:item.oid, rank:item.rank, shipping:Orders.formatDate(item.shipping.when), customer:item.customer.displayName, quantity:item.quantity, title:itemGetTitle(item), part:item.part, price:item.price.toFixed(2), finalprice:item.finalprice.toFixed(2), fulfillment:item.fulfillment.status, note:item.note }) } // // only fulfilled are computed if(item.fulfillment.status==='fulfilled'){ count+=parseFloat(item.quantity); total+=parseFloat(item.finalprice.toFixed(2)); totalfees+=parseFloat((item.finalprice*item.fees).toFixed(2)); amount+=parseFloat(item.price.toFixed(2)); if(!products[item.sku])products[item.sku]={count:0,amount:0,title:item.title+'('+item.part+')'} products[item.sku].count+=item.quantity products[item.sku].amount+=item.finalprice } }); // end of items shop=findShopBySlug(shops,slug) result.shops[slug].monthitems=count; result.shops[slug].monthamount=parseFloat((total).toFixed(2)); result.shops[slug].monthorders=_.uniq(monthorder).length; result.shops[slug].details=oshops[slug].details; if(shop&&shop.address){ result.shops[slug].streetAdress=shop.address.streetAdress; result.shops[slug].region=shop.address.region; result.shops[slug].postalCode=shop.address.postalCode; result.shops[slug].geo=shop.address.geo; } result.shops[slug].monthfees=parseFloat((totalfees).toFixed(2)); monthamount+=result.shops[slug].monthamount; monthitems+=result.shops[slug].monthitems; monthca+=result.shops[slug].monthfees; // access fees % // => result.shops[slug].details.fees })
var timer = setTimeout(function(){ self.images = _.uniq(self.images); self.images = _.compact(self.images); bigCB(); clearTimeout(timer); }, 15000);
client.on('disconnect', function(){ var client_name = sessions[client.sessionId.toString()]; delete sessions[client.sessionId.toString()]; client.send({members: _.uniq(_.values(sessions))}); client.broadcast({members: _.uniq(_.values(sessions))}); });
ProcessData.prototype.detectJoystickFrame = function (frame, previousFrames) { previousFrames || (previousFrames = this.recent.slice(-1 * JOYSTICK_DETECTION_FRAMES)); if (!frame || !previousFrames || previousFrames.length === 0) { return null; } var diffs = []; var result; previousFrames.forEach(function (previousFrame) { diffs.push(this.detectChangeFrame(frame, previousFrame)); }.bind(this)); var pins = _.chain(diffs).compact().pluck('pin').value(); var values = _.chain(diffs).compact().pluck('value').value(); if (pins.length === JOYSTICK_DETECTION_FRAMES && values.length === JOYSTICK_DETECTION_FRAMES && _.uniq(pins).length === 1) { result = { pin: pins[0] }; } return result; };
var addProxyObjects = function(principal, objects, callback) { var mp = ['image', 'stream', 'fullImage'], cp = ['members', 'followers', 'following', 'lists', 'likes', 'replies', 'shares'], props = [], selves = [], urls; if (!principal) { callback(null); return; } // Get all the media stream properties that we know have urls and are parts of these objects _.each(mp, function(prop) { props = props.concat(_.pluck(objects, prop)); }); // Get all the collection properties that we know have urls and are parts of these objects _.each(cp, function(prop) { props = props.concat(_.pluck(objects, prop)); }); // Squish them down so we only have the ones we need props = _.compact(props); urls = _.compact(_.pluck(props, "url")); // Get all the self-links _.each(objects, function(obj) { if (obj.links && obj.links.self && obj.links.self.href) { urls.push(obj.links.self.href); } }); // Uniquify the whole set of URLs urls = _.uniq(urls); // Only need proxies for remote URLs urls = _.filter(urls, function(url) { var parts = urlparse(url); return (parts.hostname != URLMaker.hostname); }); Step( function() { var User = require("./model/user").User; User.fromPerson(principal.id, this); }, function(err, user) { if (err) { throw err; } else if (!user) { // Don't add proxy urls for non-users callback(null); return; } else { Proxy.ensureAll(urls, this); } }, function(err, utp) { if (err) { callback(err); return; } _.each(props, function(prop) { if (_.has(utp, prop.url)) { if (!prop.pump_io) { prop.pump_io = {}; } prop.pump_io.proxyURL = URLMaker.makeURL("/api/proxy/"+utp[prop.url].id); } }); _.each(objects, function(obj) { if (obj.links && obj.links.self && obj.links.self.href) { if (_.has(utp, obj.links.self.href)) { if (!obj.pump_io) { obj.pump_io = {}; } obj.pump_io.proxyURL = URLMaker.makeURL("/api/proxy/"+utp[obj.links.self.href].id); } } }); callback(null); } ); };
exports.uniq = function (input) { return _.uniq(input); };
_.each(config.sites, function (site) { var site = config.sites[0]; // We're going to create a temporary file for each site, which is a valid // SASS stylesheet that defines variables. We'll then prepend this to // our SASS compilation so that variables defined in a configuration // file can lead to conditional inclusion of components. var sassVariables = []; // We begin by declaring all of our included components (both required and user-defined) _.each(requiredComponents.slice(0).concat(site.components), function (component) { sassVariables.push('$include-'+component+'-component: true !default;'); }); // We then declare all components are not included, but because of the "!default" flag, // these variables are only recognised if they weren't previously defined. This // means that we're effectively making sure all the variables are defined // so that the SASS file does not error out (see magento-boilerplate.scss) _.each(availableComponents, function (noop, component) { sassVariables.push('$include-'+component+'-component: false !default;'); }); // Create an array of stylesheets var stylesheets = [ tempWrite.sync(sassVariables.join('\n')) // Temporary file made up of concatenated variables ]; // Attach any site-specific stylesheets _.each(site.compilation.stylesheets, function (stylesheet) { stylesheets.push(stylesheet); }); // Finally, attach the stylesheet in the skin path stylesheets.push(skinPath(site)+'/assets/stylesheets/styles.scss'); // Create an array of default include paths var includePaths = [ 'node_modules/foundation-sites/scss', 'node_modules/font-awesome/scss', 'node_modules/magento-boilerplate/node_modules/foundation-sites/scss', 'node_modules/magento-boilerplate/node_modules/font-awesome/scss', 'node_modules/magento-boilerplate/assets/stylesheets' ]; // Attach any site-specific include paths _.each(site.compilation.includePaths, function (includePath) { includePaths.push(includePath); }); // Finally, include the theme's directory in the include paths includePaths.push(skinPath(site)+'/assets/stylesheets'); streams.push( gulp .src(_.uniq(stylesheets)) .pipe($.concat('styles.scss')) .pipe($.sass({ outputStyle: config.production ? 'compressed' : 'nested', sourceComments: !config.production, includePaths: _.uniq(includePaths) })) .on('error', $.notify.onError()) .pipe($.autoprefixer('last 2 versions')) .pipe(gulp.dest(skinPath(site)+'/css')) .pipe(browserSync.stream()) .pipe($.notify('Compiled Stylesheets.')) ); });
function AkamaiPurge(urls, options, callback) { var queuedUrls = [], mapper; // check to see if you using this as a constructor if (false === this instanceof AkamaiPurge) { throw new Error('Must use AkamaiPurge as constructor (hint: use the new keyword)'); } // argument flippy-flop if (!_.isArray(urls) && _.isObject(urls)) { options = _.clone(urls); if (options.urls) { urls = options.urls; } } // argument flippy-flop if (options instanceof Function) { callback = options; options = {}; } // do any options exist? if (false === options instanceof Object) { options = {}; } // find a callback to use if (false === callback instanceof Function) { if (options.callback instanceof Function) { callback = options.callback; } else if (options.complete instanceof Function) { callback = options.complete; } else { callback = function() {}; } } // apply defaults options = _.extend({ type: 'arl', domain: 'production', action: 'remove' }, options); // clean urls/cpcodes array urls = _.uniq(urls); // prepare urls into separate arrays, which will directly correspond with // the number of requests that must be made to the CCUAPI urls.forEach(function(url, index) { var queueIndex = Math.floor(index / AKAMAI_URIS_PER_REQUEST); if (!queuedUrls[queueIndex]) { queuedUrls[queueIndex] = []; } queuedUrls[queueIndex].push(url); }); // iterator function for the map mapper = function(urlSet, callback) { var _callback, request; _callback = function(err, response) { process.nextTick(function() { if (err) { if (this._events && this._events.error) { // only emit error if it's bound. this.emit('error', err, response, request, urlSet, options); } callback(err, response); return; } this.emit('request-success', response, request, urlSet, options); callback(null, response); }.bind(this)); }.bind(this); request = new AkamaiPurgeRequest(urlSet, options, _callback); }.bind(this); // and we're off... // if the mapper returns any error, all remaining requests are halted async.mapSeries(queuedUrls, mapper, function(err, results) { process.nextTick(function() { if (!err) { // emit success event this.emit('success', results || []); } callback(err, results || []); }.bind(this)); }.bind(this)); }
}, function(err){ self.images = _.uniq(self.images); self.images = _.compact(self.images); clearTimeout(timer); bigCB(); });
renderForm: function(resolve, reject) { var $form = this.$('#projectForm'), button_tmpl = require('../templates/project_buttons.ejs'), view = this, form_config, config_themes, newProject, populateForm = false; if ( this.disableForm ) { $form.append( '<div class="alert alert-warning" role="alert">Form is disabled</div>'); return resolve(); } // Prevent return or enter from submitting the form $form.keypress(function(event){ var field_type = event.originalEvent.srcElement.type; if (event.keyCode === 10 || event.keyCode === 13){ if(field_type !== 'textarea'){ event.preventDefault(); } } }); newProject = false; if ( this.model.isNew() || this.copyProject ) { newProject = true; } form_config = this.model.getConfig().form; config_themes = this.model.getConfig().themes || ['generic']; if(_.isUndefined(form_config)) { this.app.view.error('This blueprint does not have a form!'); reject('This blueprint does not have a form!'); } else { var themes = this.app.themes.filter(function(theme) { if ( _.isEqual(config_themes, ['generic']) ) { return true; } else { return _.contains(config_themes, theme.get('value')); } }), social_chars = { "sbnation": 8, "theverge": 5, "polygon": 7, "racked": 6, "eater": 5, "vox": 9, "curbed": 6, "custom": 0 }, schema_properties = { "title": { "title": "Title", "type": "string", "required": true }, "theme": { "title": "Theme", "type": "string", "required": true, "default": pluckAttr(themes, 'value')[0], "enum": pluckAttr(themes, 'value') }, "slug": { "title": "Slug", "type": "string" }, "tweet_text":{ "type": "string", "minLength": 0 } }, options_form = { "attributes": { "data-model": "Project", "data-model-id": this.model.isNew() ? '' : this.model.id, "data-action": this.model.isNew() ? 'new' : 'edit', "data-next": 'show', "method": 'post' } }, options_fields = { "theme": { "type": "select", "optionLabels": pluckAttr(themes, 'label'), }, "slug": { "label": "Slug", "validator": function(callback){ var slugPattern = /^[0-9a-z\-_]{0,60}$/; var slug = this.getValue(); if ( slugPattern.test(slug) ){ callback({ "status": true }); } else if (slugPattern.test(slug.substring(0,60))){ this.setValue(slug.substr(0,60)); callback({ "status": true }); } else { callback({ "status": false, "message": "Must contain fewer than 60 numbers, lowercase letters, hyphens, and underscores." }); } } }, "tweet_text":{ "label": "Social share text", "constrainMaxLength": true, "constrainMinLength": true, "showMaxLengthIndicator": true } }; // if there is only one theme option, hide the dropdown if ( themes.length === 1 ) { options_fields['theme']['type'] = 'hidden'; } if(this.model.hasPreviewType('live') && this.model.getConfig().spreadsheet_template){ var googleText = form_config.schema.properties.google_doc_url.title; var newText = googleText + '<br><button type="button" data-action="create-spreadsheet" class="btn btn-default">Get new spreadsheet</button>'; form_config.schema.properties.google_doc_url.title = newText; } _.extend(schema_properties, form_config.schema.properties || {}); if( form_config.options ) { _.extend(options_form, form_config.options.form || {}); _.extend(options_fields, form_config.options.fields || {}); } var opts = { "schema": { "title": this.model.blueprint.get('title'), "description": this.model.getConfig().description, "type": "object", "properties": schema_properties }, "options": { "form": options_form, "fields": options_fields, "focus": this.firstRender }, "postRender": _.bind(function(control) { this.alpaca = control; var theme = control.childrenByPropertyId["theme"], social = control.childrenByPropertyId["tweet_text"]; if ( social && social.type !== 'hidden' ) { if ( social_chars[theme.getValue()] ) { social.schema.maxLength = 140-(26+social_chars[theme.getValue()]); } else { social.schema.maxLength = 140 - 26; } social.updateMaxLengthIndicator(); if ( theme && theme.type !== 'hidden' ) { $(theme).on('change', function(){ social.schema.maxLength = 140 - ( 26 + social_chars[ theme.getValue() ] ); social.updateMaxLengthIndicator(); }); } } this.alpaca.childrenByPropertyId["slug"].setValue( this.model.get('slug_sans_theme') ); control.form.form.append( helpers.render(button_tmpl, this.templateData()) ); resolve(); }, this) }; if( form_config['view'] ) { opts.view = form_config.view; } if(!this.model.isNew() || this.copyProject) { populateForm = true; } else if (this.model.isNew() && !this.copyProject && !this.model.hasInitialBuild()){ var uniqBuildVals = _.uniq(_.values(this.model.buildData())); if (!( uniqBuildVals.length === 1 && typeof uniqBuildVals[0] === 'undefined')){ populateForm = true; } } if(populateForm){ opts.data = this.model.formData(); if ( !_.contains(pluckAttr(themes, 'value'), opts.data.theme) ) { opts.data.theme = pluckAttr(themes, 'value')[0]; } } $form.alpaca(opts); } },
}, function (packageSource, options) { buildmessage.assertInCapture(); var packageMap = options.packageMap; var isopackCache = options.isopackCache; var includeCordovaUnibuild = options.includeCordovaUnibuild; var pluginWatchSet = packageSource.pluginWatchSet.clone(); var plugins = {}; var pluginProviderPackageNames = {}; // Build plugins _.each(packageSource.pluginInfo, function (info) { buildmessage.enterJob({ title: "building plugin `" + info.name + "` in package `" + packageSource.name + "`", rootPath: packageSource.sourceRoot }, function () { // XXX we should probably also pass options.noLineNumbers into // buildJsImage so it can pass it back to its call to // compiler.compile var buildResult = bundler.buildJsImage({ name: info.name, packageMap: packageMap, isopackCache: isopackCache, use: info.use, sourceRoot: packageSource.sourceRoot, sources: info.sources, // While we're not actually "serving" the file, the serveRoot is used to // calculate file names in source maps. serveRoot: 'packages/' + packageSource.name, npmDependencies: info.npmDependencies, // Plugins have their own npm dependencies separate from the // rest of the package, so they need their own separate npm // shrinkwrap and cache state. npmDir: files.pathResolve( files.pathJoin(packageSource.sourceRoot, '.npm', 'plugin', info.name)) }); // Add this plugin's dependencies to our "plugin dependency" // WatchSet. buildResult.watchSet will end up being the merged // watchSets of all of the unibuilds of the plugin -- plugins have // only one unibuild and this should end up essentially being just // the source files of the plugin. // // Note that we do this even on error, so that you can fix the error // and have the runner restart. pluginWatchSet.merge(buildResult.watchSet); if (buildmessage.jobHasMessages()) { return; } _.each(buildResult.usedPackageNames, function (packageName) { pluginProviderPackageNames[packageName] = true; }); // Register the built plugin's code. if (!_.has(plugins, info.name)) { plugins[info.name] = {}; } plugins[info.name][buildResult.image.arch] = buildResult.image; }); }); // Grab any npm dependencies. Keep them in a cache in the package // source directory so we don't have to do this from scratch on // every build. // // Go through a specialized npm dependencies update process, // ensuring we don't get new versions of any (sub)dependencies. This // process also runs mostly safely multiple times in parallel (which // could happen if you have two apps running locally using the same // package). // // We run this even if we have no dependencies, because we might // need to delete dependencies we used to have. var nodeModulesPath = null; if (packageSource.npmCacheDirectory) { if (meteorNpm.updateDependencies(packageSource.name, packageSource.npmCacheDirectory, packageSource.npmDependencies)) { nodeModulesPath = files.pathJoin( packageSource.npmCacheDirectory, 'node_modules' ); } } // Find all the isobuild:* pseudo-packages that this package depends on. Why // do we need to do this? Well, we actually load the plugins in this package // before we've fully compiled the package --- plugins are loaded before the // compiler builds the unibuilds in this package (because plugins are allowed // to act on the package itself). But when we load plugins, we need to know if // the package depends on (eg) isobuild:compiler-plugin, to know if the plugin // is allowed to call Plugin.registerCompiler. At this point, the Isopack // object doesn't yet have any unibuilds... but isopack.js doesn't have access // to the PackageSource either (because it needs to work with both // compiled-from-source and loaded-from-disk packages). So we need to make // sure here that the Isopack has *some* reference to the isobuild features // which the unibuilds depend on, so we do it here (and also in // Isopack#initFromPath). var isobuildFeatures = []; packageSource.architectures.forEach((sourceArch) => { sourceArch.uses.forEach((use) => { if (!use.weak && isIsobuildFeaturePackage(use.package) && isobuildFeatures.indexOf(use.package) === -1) { isobuildFeatures.push(use.package); } }); }); isobuildFeatures = _.uniq(isobuildFeatures); var isopk = new isopack.Isopack; isopk.initFromOptions({ name: packageSource.name, metadata: packageSource.metadata, version: packageSource.version, isTest: packageSource.isTest, plugins: plugins, pluginWatchSet: pluginWatchSet, cordovaDependencies: packageSource.cordovaDependencies, npmDiscards: packageSource.npmDiscards, includeTool: packageSource.includeTool, debugOnly: packageSource.debugOnly, prodOnly: packageSource.prodOnly, testOnly: packageSource.testOnly, pluginCacheDir: options.pluginCacheDir, isobuildFeatures }); _.each(packageSource.architectures, function (architecture) { if (architecture.arch === 'web.cordova' && ! includeCordovaUnibuild) { return; } files.withCache(() => { var unibuildResult = compileUnibuild({ isopack: isopk, sourceArch: architecture, isopackCache: isopackCache, nodeModulesPath: nodeModulesPath, noLineNumbers: options.noLineNumbers }); _.extend(pluginProviderPackageNames, unibuildResult.pluginProviderPackageNames); }); }); if (options.includePluginProviderPackageMap) { isopk.setPluginProviderPackageMap( packageMap.makeSubsetMap(_.keys(pluginProviderPackageNames))); } return isopk; });
exports.publishToUsersOnChannel = function (channel_id, user_id_array, data) { user_id_array = _.uniq(user_id_array) sendDataToSocketIdArray(conn_pool.channel_pool.getUsersSocketIdArrayOnChannel(channel_id, user_id_array), data) }
this.groupStats(jobid, function(err, result) { var dataSet = {} , newDataSet = {} , uniqueEngines = [] , uniqueGroups = []; // Go through all the items result.forEach(function(item) { if (dataSet[item.match] == undefined) dataSet[item.match] = []; uniqueEngines.push(item.engine); uniqueGroups.push(item.group); dataSet[item.match].push({ position: item.position , stack: item.group , match: item.url , keyword: item.keyword , engine: item.engine }); }); uniqueEngines = _.uniq(uniqueEngines); uniqueGroups = _.uniq(uniqueGroups); // The mathcing url set Object.keys(dataSet).forEach(function(key) { var sortByEngineAndKeyword = _.sortBy(dataSet[key], function(elem) { return elem.engine + elem.keyword; }); var keywords = _.uniq(_.pluck(sortByEngineAndKeyword, 'keyword')); if (newDataSet[key] == undefined) newDataSet[key] = {}; newDataSet[key].categories = keywords; newDataSet[key].series = []; //console.log(key, sortByEngineAndKeyword); //console.log(keywords); // Order by the given keywords uniqueEngines.forEach(function(engine) { uniqueGroups.forEach(function(group) { var item = {}; var results = _.filter(sortByEngineAndKeyword, function(element) { return element.engine == engine && element.stack == group; }); item.stack = group; results = _.pluck(results, 'position'); item.name = engine; item.data = results; //console.dir(item); newDataSet[key].series.push(item); }); }); }); cb(null, newDataSet); });
saveChanges: function(){ var self = this, formData, cCode = this.model.get('userCurrencyCode'), submitForm = this.$el.find('#contractForm')[0], keywordsArray = this.inputKeyword.getTagValues(), shipsToInput = this.$('#shipsTo'), invalidInputList = [], maxQuantInput = this.$el.find('#inputMaxQuantity'), tempDisabledFields = [], hasError; validateMediumEditor.checkVal(this.$('#inputDescription')); if (keywordsArray.length < 1){ this.$('#inputKeyword').addClass('invalid'); hasError = true; } keywordsArray = keywordsArray.map(function(tag){ var re = /#/g; return tag.replace(re, ''); }); this.$el.find('#inputCurrencyCode').val(cCode); this.$el.find('#inputShippingCurrencyCode').val(cCode); //convert number field to string field this.$el.find('#inputPrice').val(this.$el.find('#priceLocal').val()); this.$el.find('#inputShippingDomestic').val(this.$el.find('#shippingPriceLocalLocal').val()); this.$el.find('#inputShippingInternational').val(this.$el.find('#shippingPriceInternationalLocal').val()); // disable blank fields that cause errors if sent to the server if (!maxQuantInput.val()) { maxQuantInput.attr('disabled', true); tempDisabledFields.push(maxQuantInput); } formData = new FormData(submitForm); if (this.noShipping){ formData.append('ships_to', 'NA'); } //make sure a ships to value is entered if (!shipsToInput.val() && !this.noShipping){ this.$('.js-shipToWrapper').addClass('invalid'); hasError = true; } //add old and new image hashes __.each(this.imgHashes, function(imHash){ //make sure all hashes are valid if (imHash != "b472a266d0bd89c13706a4132ccfb16f7c3b9fcb" && imHash.length === 40){ formData.append('images', imHash); } }); if (!this.imgHashes.length) { this.$('.js-editItemSubImagesWrapper').addClass('invalid'); hasError = true; } if (keywordsArray.length) { __.each(keywordsArray, function(keyword){ formData.append('keywords', keyword); }); } else { formData.append('keywords', ''); } //if this is an existing product, do not delete the images if (self.model.get('id')) { formData.append('delete_images', false); formData.append('contract_id', self.model.get('id')); } //if condition is disabled, insert default value if ($('#inputCondition:disabled').length > 0){ formData.append('condition', 'New'); } //add moderator list from profile __.each(this.model.get('moderators'), function(moderator){ formData.append('moderators', moderator.guid); }); //add formChecked class to form so invalid fields are styled as invalid this.$el.find('#contractForm').addClass('formChecked'); if (this.checkFormValidity() && !hasError) { return $.ajax({ type: "POST", url: self.model.get('serverUrl') + "contracts", contentType: false, processData: false, data: formData, success: function (data) { data = JSON.parse(data); if (data.success === true) { self.trigger('saveNewDone', data.id); } else { app.simpleMessageModal.open({ title: window.polyglot.t('errorMessages.saveError'), message: '<i>' + data.reason + '</i>' }); } }, error: function (jqXHR, status, errorThrown) { console.log(jqXHR); console.log(status); console.log(errorThrown); }, complete: function(){ //re-enable any disabled fields __.each(tempDisabledFields, function(jQObject){ jQObject.attr('disabled', false); }); } }); } $(submitForm).add(this.$('#imageForm')).find(':invalid, .invalid').each(function() { var inputName, $label; inputName = (($label = self.$("label[for='"+$(this).attr('id')+"']")).length && $label.text()) || $(this).attr('data-label') || $(this).attr('id'); invalidInputList.push(inputName.trim()); }); invalidInputList = __.uniq(invalidInputList); app.simpleMessageModal.open({ title: window.polyglot.t('errorMessages.saveError'), message: window.polyglot.t('errorMessages.missingError') + '<br><i><br />' + invalidInputList.join('<br />') + '</i>' }); return $.Deferred().reject('failed form validation').promise(); },
_.each(userToRolesMap, function(userToRole, uId){ addRole(uId, _.uniq(userToRole), isReinitialization); });
function checkUnique() { assert(_.uniq(contexts).length === contexts.length); }
processData: function(term, data, callback) { let users = data; // Only show assigned user list when there is no search term if ($dropdown.hasClass('js-multiselect') && term.length === 0) { const selectedInputs = getSelectedUserInputs(); // Potential duplicate entries when dealing with issue board // because issue board is also managed by vue const selectedUsers = _.uniq(selectedInputs, false, a => a.value) .filter((input) => { const userId = parseInt(input.value, 10); const inUsersArray = users.find(u => u.id === userId); return !inUsersArray && userId !== 0; }) .map((input) => { const userId = parseInt(input.value, 10); const { avatarUrl, avatar_url, name, username } = input.dataset; return { avatar_url: avatarUrl || avatar_url, id: userId, name, username, }; }); users = data.concat(selectedUsers); } let anyUser; let index; let j; let len; let name; let obj; let showDivider; if (term.length === 0) { showDivider = 0; if (firstUser) { // Move current user to the front of the list for (index = j = 0, len = users.length; j < len; index = (j += 1)) { obj = users[index]; if (obj.username === firstUser) { users.splice(index, 1); users.unshift(obj); break; } } } if (showNullUser) { showDivider += 1; users.unshift({ beforeDivider: true, name: 'Unassigned', id: 0 }); } if (showAnyUser) { showDivider += 1; name = showAnyUser; if (name === true) { name = 'Any User'; } anyUser = { beforeDivider: true, name: name, id: null }; users.unshift(anyUser); } if (showDivider) { users.splice(showDivider, 0, 'divider'); } if ($dropdown.hasClass('js-multiselect')) { const selected = getSelected().filter(i => i !== 0); if (selected.length > 0) { if ($dropdown.data('dropdownHeader')) { showDivider += 1; users.splice(showDivider, 0, { header: $dropdown.data('dropdownHeader'), }); } const selectedUsers = users .filter(u => selected.indexOf(u.id) !== -1) .sort((a, b) => a.name > b.name); users = users.filter(u => selected.indexOf(u.id) === -1); selectedUsers.forEach((selectedUser) => { showDivider += 1; users.splice(showDivider, 0, selectedUser); }); users.splice(showDivider + 1, 0, 'divider'); } } } callback(users); if (showMenuAbove) { $dropdown.data('glDropdown').positionMenuAbove(); } },
var data = fs.readFileSync('badges.json').toString(); data = data.replace(/ "_id".*?,/g, ''); data = data.replace(/ "imageData".*?,/g, ''); var lines = data.split('\n'); lines.pop(); var entries = lines.map(JSON.parse); var userEmails = entries.map(function (e) { return e.recipient; }); var emails = _.uniq(userEmails) emails.forEach(function (e) { User.findOrCreate(e, function (err, user) { }); }); setTimeout(function () { entries.forEach(function (e) { User.findOrCreate(e.recipient, function (err, user) { var endpoint = e.meta.pingback; var image = e.meta.imagePath; delete e.meta; var badge = new Badge({
getAppName(function(result) { if (!result) { // this is for the non-project specific commands callback(); return; } config.locale = env.locale || config.locale; config.base = base; config.alloy_path = path.join(base, 'app'); config.resources_path = path.join(base, 'Resources'); config.res_alloy_path = path.join(base, 'Resources', 'alloy'); config.fonts_path = path.join(config.resources_path, 'fonts'); config.modules_path = path.join(base, 'modules'); config.platform_path = path.join(base, 'platform'); config.spec_path = path.join(base, 'spec'); config.i18n_path = path.join(base, 'i18n'); config.build_path = path.join(base, 'build'); config.tishadow_build = path.join(config.build_path, 'tishadow'); config.tishadow_src = path.join(config.tishadow_build, 'src'); config.tishadow_spec = path.join(config.tishadow_src, 'spec'); config.tishadow_dist = path.join(config.tishadow_build, 'dist'); config.alloy_map_path = path.join(config.tishadow_build, 'alloy_map.json'); var app_name = config.app_name = result.name[0] || "bundle"; config.bundle_file = path.join(config.tishadow_dist, app_name + ".zip"); config.jshint_path = fs.existsSync(config.alloy_path) ? config.alloy_path : config.resources_path; if (config.isTiCaster && result.ticaster_user[0] && result.ticaster_app[0]) { config.room = result.ticaster_user[0] + ":" + result.ticaster_app[0]; } if (config.room === undefined) { logger.error("ticaster setting missing from tiapp.xml"); process.exit(); } config.isAlloy = fs.existsSync(config.alloy_path); if (!config.platform && config.isAlloy) { var deploymentTargets = []; result['deployment-targets'][0].target.forEach(function(t) { if (t['_'] === 'true') { var platform = t['$'].device; if (platform === 'ipad' || platform === 'iphone') { if (deploymentTargets.indexOf('ios') !== -1) { return; } platform = 'ios'; } deploymentTargets.push(platform); } }); config.platform = deploymentTargets; } config.last_updated_file = path.join(config.tishadow_build, 'last_updated' + (config.platform ? '_' + config.platform.join('_') : '')); config.isPatch = env.patch; config.isUpdate = (env.update || env.patch) && fs.existsSync(config.tishadow_src) && fs.existsSync(config.last_updated_file); if (config.isSpec) { config.specCount = _.uniq(glob.sync(config.spec_path +"/**/*_spec.js").concat(glob.sync(config.resources_path + "/**/*_spec.js"))).length; } callback(); });
setFormValues: function(){ var self = this, countries = new countriesModel(), timezones = new timezonesModel(), languages = new languagesModel(), countryList = countries.get('countries'), currecyList = countries.get('countries'), timezoneList = timezones.get('timezones'), languageList = languages.get('languages'), country = this.$el.find('#country'), ship_country = this.$el.find('#settingsShipToCountry'), currency = this.$el.find('#currency_code'), timezone = this.$el.find('#time_zone'), language = this.$el.find('#language'), user = this.model.get('user'), avatar = user.avatar_hash, ship_country_str = "", country_str = "", currency_str = "", timezone_str = "", language_str = "", pageNSFW = this.model.get('page').profile.nsfw, moderatorStatus = this.model.get('page').profile.moderator; this.$el.find('#pageForm input[name=nsfw]').val([String(pageNSFW)]); currecyList = __.uniq(currecyList, function(item){return item.code;}); currecyList = currecyList.sort(function(a,b){ var cA = a.currency.toLowerCase(), cB = b.currency.toLowerCase(); if (cA < cB){ return -1; } if (cA > cB){ return 1; } return 0; }); //add BTC currecyList.unshift({code: "BTC", currency:"Bitcoin", currencyUnits: "4"}); __.each(countryList, function(c, i){ var country_option = $('<option value="'+c.dataName+'" data-name="'+c.name+'">'+c.name+'</option>'); var ship_country_option = $('<option value="'+c.dataName+'" data-name="'+c.name+'">'+c.name+'</option>'); country_option.attr("selected",user.country == c.dataName); //if user has a country in their profile, preselect it in the new address section ship_country_option.attr("selected",user.country== c.dataName); ship_country_str += ship_country_option[0].outerHTML; country_str += country_option[0].outerHTML; }); __.each(currecyList, function(c, i){ //only show currently available currencies if(self.availableCurrenciesList.indexOf(c.code) > -1 || c.code === "BTC"){ var currency_option = $('<option value="'+c.code+'">'+c.currency+'</option>'); currency_option.attr("selected",user.currency_code == c.code); currency_str += currency_option[0].outerHTML; } }); __.each(timezoneList, function(t, i){ var timezone_option = $('<option value="'+t.offset+'">'+t.name+'</option>'); timezone_option.attr("selected",user.time_zone == t.offset); timezone_str += timezone_option[0].outerHTML; }); __.each(languageList, function(l, i){ var language_option = $('<option value="'+l.langCode+'">'+l.langName+'</option>'); language_option.attr("selected",user.language == l.langCode); language_str += language_option[0].outerHTML; }); ship_country.html(ship_country_str); currency.html(currency_str); country.html(country_str); timezone.html(timezone_str); language.html(language_str); __.each(this.userModel.get('moderators'), function(modID){ "use strict"; if(modID) { modID.fromModel = true; self.renderModerator(modID); } }); //set moderator status this.$('#moderatorForm input[name=moderator]').val([String(moderatorStatus)]); },
var distinctCollections = function(indexes){ return _.uniq(_.pluck(indexes, "collection")); };
schemaNames(): Array<SchemaName> { // $FlowFixMe: flow doesn't understand our null filtering return _.uniq(this.tables().map(table => table.schema).filter(schemaName => schemaName != null)); }
db.view_with_list('usgin-cache', 'wfsUrls', 'threshold', {min:4}, function (err, urls) { callback(err, _.uniq(urls)); });