componentDidUpdate(prevProps) { /* eslint-disable react/prop-types */ const { validators, errors, model, dispatch, validateOn, } = this.props; /* eslint-enable react/prop-types */ if (validateOn !== 'change') return; mapValues(validators, (validator, field) => { const fieldModel = [model, field].join('.'); const value = _get(this.props, fieldModel); if (value === _get(prevProps, fieldModel)) return; const validity = getValidity(validator, value); dispatch(actions.setValidity(fieldModel, validity)); }); mapValues(errors, (errorValidator, field) => { const fieldModel = [model, field].join('.'); const value = _get(this.props, fieldModel); if (value === _get(prevProps, fieldModel)) return; const fieldErrors = getValidity(errorValidator, value); dispatch(actions.setErrors(fieldModel, fieldErrors)); }); }
/** * Calculates the aggregation based on the accumulated evaluations. * * @param {array} evaluations The accumulated evaluations * * @return {object} The aggregation object */ function calculateAggregation(evaluations) { const shape = flattenObject(evaluations[0] || {}); const grouped = mapValues(shape, (value, key) => { return evaluations .map((evaluation) => objGet(evaluation, key)) // All the packages with negative values will have a score of 0 (e.g.: downloads acceleration) // So, we must remove all negative values from the aggregation in order to have a better score curve .filter((evaluation) => evaluation >= 0) .sort((a, b) => a - b); }); const aggregation = mapValues(grouped, (evaluations) => { const trimmedLength = Math.round(evaluations.length * trimPercentage); return { min: evaluations[0], max: evaluations[evaluations.length - 1], mean: mean(evaluations), truncatedMean: mean(evaluations.slice(trimmedLength, -trimmedLength)), median: evaluations[Math.round(evaluations.length / 2)], }; }); return unflattenObject(aggregation); }
function renderPanels(screen, options) { let configs = mapValues(options.panels, (panel, name) => { return assign(panel, {name}) }) let panels = mapValues(configs, (panel, name) => { let type = panel.type || 'box' let widget = blessed[type] || blessed.box let config = pick(panel, 'top', 'left', 'height', 'width', 'label', 'border', 'style') if (panel.borderStyles) { config = defaults(config, borderStyles(panel.borderStyles)) } let element = widget(config) screen.append(element) return element }) screen.render() return panels }
export const requests = ( state = initialRequestsState, action ) => { switch ( action.type ) { case JETPACK_SETTINGS_FETCH: return assign( {}, state, { fetchingSettingsList: true } ); case JETPACK_SETTINGS_FETCH_FAIL: case JETPACK_SETTINGS_FETCH_RECEIVE: return assign( {}, state, { fetchingSettingsList: false } ); case JETPACK_SETTING_UPDATE: case JETPACK_SETTINGS_UPDATE: return merge( {}, state, { settingsSent: mapValues( action.updatedOptions, () => true ) } ); case JETPACK_SETTING_UPDATE_FAIL: case JETPACK_SETTING_UPDATE_SUCCESS: case JETPACK_SETTINGS_UPDATE_FAIL: case JETPACK_SETTINGS_UPDATE_SUCCESS: return merge( {}, state, { settingsSent: mapValues( action.updatedOptions, () => false ) } ); default: return state; } };
decode: function decode (meta) { if (meta == null) { return null } switch (meta.kind) { case 'irreducible': return t.irreducible( meta.name, toFunction(meta.predicate) ) case 'refinement': return t.refinement( decode(meta.type), toFunction(meta.predicate), meta.name ) case 'enums': return t.enums(meta.map, meta.name) case 'maybe': return t.maybe(decode(meta.type), meta.name) case 'struct': return t.struct( mapValues(meta.props, (type) => decode(type)), meta.name ) case 'tuple': return t.tuple( map(meta.types, (type) => decode(type)), meta.name ) case 'list': return t.list(decode(meta.type), meta.name) case 'dict': return t.dict( decode(meta.domain), decode(meta.codomain), meta.name ) case 'union': return t.union( map(meta.types, (type) => decode(type)), meta.name ) case 'intersection': return t.intersection( mapValues(meta.types, (type) => decode(type)), meta.name ) case 'func': return t.func( decode(meta.domain), decode(meta.codomain), meta.name ) default: throw new Error('tcomb-codec: unknown meta.kind `'+meta.kind+'`') } }
it('should give equivalent results', () => { const validators = { foo: (val) => val === 'testing foo', bar: { one: (val) => val && val.length >= 1, two: (val) => val && val.length >= 2, }, }; const inverted = invertValidators(validators); const value = { foo: 'testing foo', bar: '123', }; const fieldsValidity = mapValues(inverted, (validator, field) => { const fieldValue = field ? _get(value, field) : value; const fieldValidity = getValidity(validator, fieldValue); return fieldValidity; }); assert.deepEqual(fieldsValidity, { foo: false, bar: { one: false, two: false, }, }); });
_filterOrExclude(_lookupObj, exclude) { const func = exclude ? reject : filter; let lookupObj = _lookupObj; let operationWithRefs = true; let entities; if (typeof lookupObj === 'function') { // For filtering with function, // use whatever object type // is flagged. if (this._withRefs) { entities = this.toRefArray(); } else { entities = this.toModelArray(); operationWithRefs = false; } } else { if (typeof lookupObj === 'object') { lookupObj = mapValues(lookupObj, normalizeEntity); } // Lodash filtering doesn't work with // Model instances. entities = this.toRefArray(); } const filteredEntities = func(entities, lookupObj); const getIdFunc = operationWithRefs ? (obj) => obj[this.modelClass.idAttribute] : (obj) => obj.getId(); const newIdArr = filteredEntities.map(getIdFunc); return this._new(newIdArr, { withRefs: false }); }
componentWillMount(nextProps) { const { config, account, linode } = nextProps || this.props; const slots = AVAILABLE_DISK_SLOTS[linode.hypervisor]; const rootSansDev = config.root_device.substring('/dev/'.length); this.setState({ label: config.label, comments: config.comments, kernel: config.kernel, initrd: config.initrd || '', rootDevice: config.root_device || `/dev/${slots[0]}`, devices: mapValues(config.devices, d => JSON.stringify(pickBy(d, Boolean))), virtMode: config.virt_mode, runLevel: config.run_level, ramLimit: config.memory_limit, isCustomRoot: !!config.root_device.length && (slots.indexOf(rootSansDev) === -1), isMaxRam: config.memory_limit === 0, enableDistroHelper: config.helpers.distro, enableNetworkHelper: config.helpers.network, enableModulesDepHelper: config.helpers.modules_dep, disableUpdatedb: config.helpers.updatedb_disabled, ...this.state, }); if (!config.id) { this.setState({ enableNetworkHelper: account.network_helper }); } }
export function loadAllCourseFilterOptions(): Promise<AllFilterCategories> { return pProps( mapValues(filterCategories, (category: FilterCategory) => fetch(category.url).json(), ), ).then(result => result) }
const attachToStringToObjects = ({ toString, ...styles }) => mapValues(styles, (value, key, ...args) => { if(!isPseudoOrMedia(key) && Object.prototype.toString.call(value) === '[object Object]') { value = {...value} value.toString = () => undefined } return value })
/** * Gets the query params used to populate the params model. * If params are found in the URL, they are used and merged with the defaults. * Otherwise the datastore is checked for params from a previous session, and * those are merged with the defaults. * If no params exist in the URL or the datastore, the defaults are returned. * @return {Object} The initial params. */ function getInitalQueryParamsAndUpdateUrl() { let defaultParams = {'start-date': '30daysAgo', 'end-date': 'yesterday'}; let storedParams = db.get('query-explorer:params'); let urlParams = qs.parse(location.search.slice(1)); // Don't assume that the presence any query params means it's a Query // Explorer URL. Only use the query params if they exist and contain at least // a metric value. if (urlParams && urlParams['metrics']) { // Some of the Query Explorer links out in the wild have double-encoded // URL params. Check for the substring '%253A' (a colon, double-encoded), // and if found then double-decode all params. if (urlParams['metrics'].indexOf('%253A')) { urlParams = mapValues(urlParams, (value) => decodeURIComponent(value)); } // Remove the query params in the URL to prevent losing state on refresh. // https://github.com/googleanalytics/ga-dev-tools/issues/61 if (history && history.replaceState) { history.replaceState(history.state, document.title, location.pathname); } urlParams = sanitize({...defaultParams, ...urlParams}); db.set('query-explorer:params', urlParams); return urlParams; } else if (storedParams) { return sanitize({...defaultParams, ...storedParams}); } else { return defaultParams; } }
onopentag: (name, attrs) => { // eslint-disable-line consistent-return const line = findLastIndex(lineIndexes, i => i <= parser.startIndex) + 1 if (name === 'mj-include') { inInclude = true return handleInclude(decodeURIComponent(attrs.path), line) } if (convertBooleans) { // "true" and "false" will be converted to bools attrs = convertBooleansOnAttrs(attrs) } attrs = mapValues(attrs, val => decodeURIComponent(val)) const newNode = { file: filePath, absoluteFilePath: path.resolve(cwd, filePath), line, includedIn, parent: cur, tagName: name, attributes: attrs, children: [], } if (cur) { cur.children.push(newNode) } else { mjml = newNode } cur = newNode },
function invertValidators(validators) { if (typeof validators === 'function') { return (val) => !validators(val); } return mapValues(validators, invertValidators); }
/** * Handles updating the state when new props are passed externally. * When new params are passed and isQuerying is set to true, a new request * is made. * @param {Object} nextProps */ componentWillReceiveProps(nextProps) { // Compares the props to the instance state to determine when the request // should initiate. if (nextProps.params && this.isQuerying === false && nextProps.isQuerying === true) { this.isQuerying = true; let newParams = sanitize(nextProps.params); // The Embed API has its own defaults for these values, so we need to // explicitly set them in case the user doesn't. let defaultParams = { 'start-date': '', 'end-date': '', }; // Nullify the existing props // TODO(philipwalton): .set() should ideally be able to handle // sending it new properties without merging. let nulledOldParams = mapValues(this.dataChart_.get().query, () => null); let params = {...defaultParams, ...nulledOldParams, ...newParams}; this.dataChart_.set({query: params}).execute(); } // Compares the props to the instance state to determine when the request // has completed. if (this.isQuerying === true && nextProps.isQuerying === false) { this.isQuerying = false; } }
export default function importState(state, { deserializeState, deserializeAction }) { if (!state) return undefined; let preloadedState; let nextLiftedState = parse(state); if (nextLiftedState.payload) { if (nextLiftedState.preloadedState) preloadedState = parse(nextLiftedState.preloadedState); nextLiftedState = parse(nextLiftedState.payload); } if (deserializeState) { nextLiftedState.computedStates = nextLiftedState.computedStates.map(computedState => ({ ...computedState, state: deserializeState(computedState.state) })); if (typeof nextLiftedState.committedState !== 'undefined') { nextLiftedState.committedState = deserializeState(nextLiftedState.committedState); } } if (deserializeAction) { nextLiftedState.actionsById = mapValues(nextLiftedState.actionsById, liftedAction => ({ ...liftedAction, action: deserializeAction(liftedAction.action) })); } return { nextLiftedState, preloadedState }; }
function invertValidity(validity) { if (isPlainObject(validity)) { return mapValues(validity, invertValidity); } return !validity; }
render() { const currentNesting = this.props.path.size; const maxNesting = this.props.config.settings.maxNesting; // Don't allow nesting further than the maximum configured depth and don't // allow removal of the root group. const allowFurtherNesting = typeof maxNesting === 'undefined' || currentNesting < maxNesting; const allowRemoval = currentNesting > 1; const conjunctionOptions = mapValues(this.props.config.conjunctions, (item, index) => ({ id: `conjunction-${this.props.id}-${index}`, name: `conjunction[${this.props.id}]`, label: item.label, checked: index === this.props.conjunction, setConjunction: () => this.setConjunction.call(this, index) })); return ( <Group id={this.props.id} allowRemoval={allowRemoval} allowFurtherNesting={allowFurtherNesting} conjunctionOptions={conjunctionOptions} removeSelf={this.removeSelf.bind(this)} addGroup={this.addGroup.bind(this)} addRule={this.addRule.bind(this)}>{this.props.children}</Group> ); }
const handleApplyContentStyleTool = (currentState, action, tool) => { const styleInd = ['cells', action.row, action.col, 'content', action.target, 'style']; const presentGrid = currentState.grid.present; const filledTool = fillSharedOptions(tool, get(currentState, ['tools', 'sharedOptions'])); let newStyle = filledTool.style; const currentStyle = get(presentGrid, styleInd); newStyle = mapValues(newStyle, (value, key) => { if (value instanceof Array) { if (currentStyle !== undefined && currentStyle[key] !== undefined) { const newPos = (value.indexOf(currentStyle[key]) + 1) % value.length; return value[newPos]; } return value[0]; } else if (typeof value === 'string' && value.match(/[+\-]\d+/)) { const intValue = parseInt(value, 10); if (currentStyle !== undefined && currentStyle[key] !== undefined) { return currentStyle[key] + intValue; } return defaultValue(key, action.target) + intValue; } return value; }); let newGrid = presentGrid; for (const style of Object.keys(newStyle)) { newGrid = newGrid.setIn([...styleInd, style], newStyle[style]); } return currentState.set('grid', insert(currentState.grid, newGrid)); };
export function castlesAt(v) { return mapValues({ K: v, Q: v, k: v, q: v }, m.prop); }
let dispatchValidate = (value) => { let validity = mapValues(props.validators, (validator) => validator(getValue(value))); dispatch(setValidity(model, validity)); return value; }
function dashboard(server, options) { const project = server.project const screen = blessed.screen({ autoPadding: true, smartCSR: true, title: 'Skypager', dockBorders: true }); // Let user quit the app screen.key(['escape', 'q', 'C-c'], function(ch, key) { return process.exit(0); }); server.panels = renderPanels(screen, options) project.debug('launching dashboard with panels', options) mapValues(options.panels, (panel, key) => { if (panel.type === 'log' && panel.process) { let panelOutput = server.logPath(`${panel.process}.${server.env}.log`) let logPanel = server.panels[key] logPanel.add('Monitoring log at ' + panelOutput) streamer(panelOutput, logPanel.add.bind(logPanel)) } }) const logger = new (winston.Logger)({ level: 'debug', transports:[ new (winston.transports.File)({ filename: server.logPath(`dashboard.${server.env}.log`), json: true, colorize: true }) ] }) function silence() { // Don't overwrite the screen console.log = capture('log') console.warn = capture('warn') console.error = capture('error') console.info = capture('info') console.debug = capture('debug') } function capture(level) { return (...args) => { logger.log(level, ...args) } } }
export function assembleFieldInfo(entity, field, value) { mapValues(value, (val, id) => { const fieldInfo = field[id] return { ...fieldInfo, value: getValue(entity, fieldInfo, val), } }) }
replaceValues(object) { return mapValues(object, value => { if (isPlainObject(value)) { return this.replaceValues(value) } return this._variables[value] || value }) }
function validateAndReturnObject(value, schema) { return mapValues(schema, (type, k) => { try { return type(value[k]); } catch (e) { throw new TypesError(`schema failed for key '${k}', ${e.message}`); } }); }
function getLinks(current, links, dest) { return _mapValues(links, function (value) { if (isFunction(value)) { return value(record, current, dest); } else { return value; } }); }
/* * Convert numeric fields to strings to match payload_data schema */ function getBody(request) { var cleanedRequest = mapValues(request, function (v) { return v.toString(); }); return { evt: cleanedRequest, bytes: getUTF8Length(JSON.stringify(cleanedRequest)) }; }
export function removeUndefinedValues (obj) { return _pickBy( _mapValues( obj, value => typeof value === 'object' ? removeUndefinedValues(value) : value ), value => value !== undefined ) }
getDefaultData(properties) { const defaultData = superclass.defaultData || this.defaultData(); if (is.object(defaultData) === true) { return mapValues(defaultData, defaultDataMapper(properties)); } return {}; }
function getLinks(links) { return _mapValues(links, function (value) { if (isFunction(value)) { return value(records); } else { return value; } }); }
const mergeReadyState = (accReadyState = {}, newReadyState) => { return mapValues(newReadyState, (newQueryRs, queryName) => { const accQueryRs = accReadyState[queryName] || {}; return { ...newQueryRs, ready: newQueryRs.ready || accQueryRs.ready || false // possibly remain "ready" based on old props }; }); };