function resolver (campaign) { const {platform, sub_status, status} = campaign const defaultStatus = { name: sub_status || status, is_active: false, platform, description: '???' } const foundStatus = find(statuses, {name: status, platform}) const foundSubStatus = find(statuses, {name: sub_status, platform}) let foundDescriptor if (foundStatus && !foundStatus.is_active) { foundDescriptor = foundStatus } else { foundDescriptor = foundSubStatus || foundStatus || defaultStatus } return assign(omit(campaign, 'status', 'sub_status'), { status: assign({}, foundDescriptor, { status, sub_status, icon: getStatusIcon(foundDescriptor) }) }) }
it('simple replacements', () => { let oldNumber = '+91' let currentSelectedCountry = find(allCountries, { iso2: 'in' }) let nextSelectedCountry = find(allCountries, { iso2: 'iq' }) let expectedNumber = '964' let newNumber = replaceCountryCode( currentSelectedCountry, nextSelectedCountry, oldNumber.replace(/\D/g, '') ) expect(newNumber).toEqual(expectedNumber) })
module.exports = function(state, opts){ var json = state.result , components = state.seen return { enter(path) { let { node, scope } = path; if (isReactClass(node.callee, scope)) { var spec = resolveToValue(node.arguments[0], scope).properties , comment = doc.parseCommentBlock(doc.findLeadingCommentNode(path)) , component = getCreatClassName(spec, path, scope, comment) , propTypes = find(spec, node => t.isProperty(node) && node.key.name === 'propTypes') , getDefaultProps = find(spec, node => (t.isProperty(node) || t.isObjectMethod(node)) && node.key.name === 'getDefaultProps' ) components.push(component) json[component] = { props: {}, composes: [], methods: methodData(spec), desc: comment || '' } if (opts.mixins) { var mixins = find(spec, node => t.isProperty(node) && node.key.name === 'mixins'); if ( mixins ){ json[component].mixins = [] parseMixins(mixins.value.elements, scope, json[component].mixins) } } propTypes && parsePropTypes(resolveToValue(propTypes.value, scope), json[component], scope) if (getDefaultProps) { let body = (t.isProperty(getDefaultProps) ? getDefaultProps.value.body :getDefaultProps.body).body; let defaultProps = find(body, node => t.isReturnStatement(node) && (isResolvable(node.argument) || t.isIdentifier(node.argument))) if (defaultProps) parseDefaultProps(resolveToValue(defaultProps.argument, scope), json[component], state.file, scope) } } } } }
it('should not append the country code when the current and next country have the same country code', () => { // e.g. when switching from us to ca a 1 gets appended let oldNumber = '+1(600)' let currentSelectedCountry = find(allCountries, { iso2: 'us' }) let nextSelectedCountry = find(allCountries, { iso2: 'ca' }) let expectedNumber = '1600' let newNumber = replaceCountryCode( currentSelectedCountry, nextSelectedCountry, oldNumber.replace(/\D/g, '') ) expect(newNumber).toEqual(expectedNumber) })
it('should take care of formatting nuances when replacing country codes', () => { // e.g. US virgin islands number formats to something like this '+1(340)' // the problem would be solved if we just take the numbers and replace country code and then reformat the number let oldNumber = '+1(340)' let currentSelectedCountry = find(allCountries, { iso2: 'vi' }) let nextSelectedCountry = find(allCountries, { iso2: 'iq' }) let expectedNumber = '964' let newNumber = replaceCountryCode( currentSelectedCountry, nextSelectedCountry, oldNumber.replace(/\D/g, '') ) expect(newNumber).toEqual(expectedNumber) })
Project.prototype.findAddonByName = function(name) { this.initializeAddons(); var exactMatch = find(this.addons, function(addon) { return name === addon.name || (addon.pkg && name === addon.pkg.name); }); if (exactMatch) { return exactMatch; } return find(this.addons, function(addon) { return name.indexOf(addon.name) > -1 || (addon.pkg && name.indexOf(addon.pkg.name) > -1); }); };
render () { if (!this.props.merchant) { return ( <div> loading... </div> ) } const message = find(this.props.merchant[0].messages, (o) => { return o.message_id == this.props.params.id }) let messageDate = Moment(message.timestamp).format('LL') return ( <div className='col-md-9'> <div className='box-typical box-typical-padding'> <div className='box-body no-padding'> <div className='mailbox-read-info'> <h4 className='m-t-lg with-border m-b-0'>{message.subject}</h4> <span>From: <a href='mailto:concierge@placeful.co'>concierge@placeful.co</a> <small className='pull-right'>{messageDate}</small></span> </div> <p className='p-t-md'> {message.body} </p> </div> </div> </div> ) }
export const __delete = (req, res) => { const id = req.params.id; const records = getSanitizedRecords(); const record = find(records, { id: id }); if (!record) { res.status(ERR_NOT_FOUND).send({ msg: 'Not found' }); return; } try { const filteredRecords = records.filter(record => { return record.id !== id; }); config.set(CONFIG_KEY, filteredRecords); res.send({ err: null }); } catch (err) { res.status(ERR_INTERNAL_SERVER_ERROR).send({ msg: 'Failed to save ' + JSON.stringify(settings.rcfile) }); } };
/** * Finds an aircraft by its internal id * * @method findAircraftById * @param {string} id * @return {AircraftModel} */ findAircraftById(id) { if (!id) { return; } return _find(this.aircraft.list, (aircraft) => aircraft.id === id); }
function updateOrAddStep( step ) { if ( find( signupProgress, { stepName: step.stepName } ) ) { updateStep( step ); } else { addStep( step ); } }
function saveStep( step ) { if ( find( signupProgress, { stepName: step.stepName } ) ) { updateStep( step ); } else { addStep( assign( {}, step, { status: 'in-progress' } ) ); } }
it( 'should mark submitted steps with an API request method as pending', function() { SignupActions.submitSignupStep( { stepName: 'asyncStep' } ); assert.equal( find( SignupProgressStore.get(), { stepName: 'asyncStep' } ).status, 'pending' ); } );
export function getLayerByName(map, name) { var layers = map.getLayers() .getArray(); return lodashFind(layers, { 'wvname': name }); };
this._toggleTarget = function(targetNode) { var node = this.props.node; var surface = this.context.surfaceManager.getFocusedSurface(); // console.log('XRefTargets: toggling target of ', node.id); // Update model var newTargets = node.targets; if (newTargets.indexOf(targetNode.id) > 0) { newTargets = without(newTargets, targetNode.id); } else { newTargets.push(targetNode.id); } // Compute visual feedback var targets = this.state.targets; var target = find(this.state.targets, function(t) { return t.node === targetNode; }); // Flip the selected flag target.selected = !target.selected; // Triggers a rerender this.setState({ targets: targets }); // console.log('XRefTargets: setting targets of ', node.id, 'to', newTargets); // ATTENTION: still we need to use surface.transaction() surface.transaction(function(tx) { tx.set([node.id, 'targets'], newTargets); }); };
saveSearch(destination) { const { items } = this.getStorageObject(); const found = find(items, oldItem => isEqual( getNameLabel(destination.item.properties), getNameLabel(oldItem.item.properties), ), ); const timestamp = moment().unix(); if (found != null) { found.count += 1; found.lastUpdated = timestamp; found.item = cloneDeep(destination.item); } else { items.push({ count: 1, lastUpdated: timestamp, ...destination, }); } setOldSearchesStorage({ version: STORE_VERSION, items: orderBy(items, 'count', 'desc'), }); this.emitChange(destination); }
/** * Arm the exit of the holding pattern * * @for Pilot * @method cancelHoldingPattern * @param fixName {string} name of the fix at which the hold should be canceled (optional) * @return {array} [success of operation, readback] */ cancelHoldingPattern(fixName) { let holdWaypointModel = _find(this._fms.waypoints, (waypointModel) => waypointModel.isHoldWaypoint); if (!holdWaypointModel) { return [false, 'that must be for somebody else, we weren\'t given any holding instructions']; } if (fixName) { holdWaypointModel = this._fms.findWaypoint(fixName); if (!holdWaypointModel || !holdWaypointModel.isHoldWaypoint) { return [false, { log: `that must be for somebody else, we weren't given holding over ${fixName.toUpperCase()}`, say: `that must be for somebody else, we weren't given holding over ${fixName.toLowerCase()}` }]; } } holdWaypointModel.deactivateHold(); // force lower-case in verbal readback to get speech synthesis to pronounce the fix instead of speling it return [true, { log: `roger, we'll cancel the hold at ${holdWaypointModel.getDisplayName()}`, say: `roger, we'll cancel the hold at ${holdWaypointModel.name.toLowerCase()}` }]; }
export const update = (req, res) => { const id = req.params.id; const records = getSanitizedRecords(); const record = find(records, { id: id }); if (!record) { res.status(ERR_NOT_FOUND).send({ msg: 'Not found' }); return; } const { enabled = record.enabled, name = record.name, oldPassword = '', newPassword = '' } = { ...req.body }; const willChangePassword = oldPassword && newPassword; // Skip validation for "enabled" and "name" if (willChangePassword && !bcrypt.compareSync(oldPassword, record.password)) { res.status(ERR_PRECONDITION_FAILED).send({ msg: 'Incorrect password' }); return; } const inuse = (record) => { return record.id !== id && record.name === name; }; if (some(records, inuse)) { res.status(ERR_CONFLICT).send({ msg: 'The specified user already exists' }); return; } try { record.mtime = new Date().getTime(); record.enabled = Boolean(enabled); record.name = String(name || ''); if (willChangePassword) { const salt = bcrypt.genSaltSync(); const hash = bcrypt.hashSync(newPassword.trim(), salt); record.password = hash; } config.set(CONFIG_KEY, records); res.send({ id: record.id, mtime: record.mtime }); } catch (err) { res.status(ERR_INTERNAL_SERVER_ERROR).send({ msg: 'Failed to save ' + JSON.stringify(settings.rcfile) }); } };
// * Grbl v0.9 // [G38.2 G54 G17 G21 G91 G94 M0 M5 M9 T0 F20. S0.] // * Grbl v1.1 // [GC:G0 G54 G17 G21 G90 G94 M0 M5 M9 T0 S0.0 F500.0] static parse(line) { const r = line.match(/^\[(?:GC:)?((?:[a-zA-Z][0-9]+(?:\.[0-9]*)?\s*)+)\]$/); if (!r) { return null; } const payload = {}; const words = _compact(r[1].split(' ')) .map((word) => { return _trim(word); }); for (let i = 0; i < words.length; ++i) { const word = words[i]; // Gx, Mx if (word.indexOf('G') === 0 || word.indexOf('M') === 0) { const r = _find(GRBL_MODAL_GROUPS, (group) => { return _includes(group.modes, word); }); if (!r) { continue; } const prevWord = _get(payload, 'modal.' + r.group, ''); if (prevWord) { _set(payload, 'modal.' + r.group, ensureArray(prevWord).concat(word)); } else { _set(payload, 'modal.' + r.group, word); } continue; } // T: tool number if (word.indexOf('T') === 0) { _set(payload, 'tool', word.substring(1)); continue; } // F: feed rate if (word.indexOf('F') === 0) { _set(payload, 'feedrate', word.substring(1)); continue; } // S: spindle speed if (word.indexOf('S') === 0) { _set(payload, 'spindle', word.substring(1)); continue; } } return { type: GrblLineParserResultParserState, payload: payload }; }
function deriveFromProps({line, now}: Props) { // Finds the stuff that's shared between FlatList and renderItem const processedLine = processBusLine(line, now) const scheduleForToday = getScheduleForNow(processedLine.schedules, now) const {times, status, index, nextStart} = getCurrentBusIteration( scheduleForToday, now, ) const isLastBus = index === scheduleForToday.times.length - 1 let subtitle = 'Error' switch (status) { case 'none': subtitle = 'Not running today' break case 'before-start': case 'between-rounds': subtitle = startsIn(now, nextStart) break case 'after-end': subtitle = 'Over for today' break case 'running': { if (isLastBus) { subtitle = 'Last Bus' } else { const first = find(times, isTruthy) const last = findLast(times, isTruthy) if (!first || !last) { subtitle = 'Not running today' } else if (now.isBefore(first)) { subtitle = startsIn(now, first) } else if (now.isAfter(last)) { subtitle = 'Running' } else { subtitle = 'Running' } } break } default: { ;(status: empty) } } if (process.env.NODE_ENV !== 'production') { // for debugging subtitle += ` (${now.format('dd h:mma')})` } return { subtitle: subtitle, status: status, schedule: scheduleForToday, currentBusIteration: index, } }
/** * Toggle layer * @param {String} id | Layer ID */ onClickLayer(id) { const { removeLayer, addLayer, activeLayers } = this.props; if (lodashFind(activeLayers, { id: id })) { removeLayer(id); } else { addLayer(id); } }
export function hasDomainCredit( state, siteId ) { const plans = getPlansBySiteId( state, siteId ); if ( plans.data ) { const currentPlan = find( plans.data, 'currentPlan' ); return currentPlan.hasDomainCredit; } return null; }
delay(2000).then(() => { /* throw new Error('500'); // SERVER ERROR */ const screen = find(fakeDatabase.screens, { id }); screen.description = description; return screen; });
export function isMissingByOwnerAndSlug( state, owner, slug ) { const preparedOwner = owner.toLowerCase(); const preparedSlug = slug.toLowerCase(); return !! find( state.reader.lists.missingLists, ( list ) => { return list.owner === preparedOwner && list.slug === preparedSlug } ); }
getLanguageName (langKey) { if (this.state && this.state.languages) { const lang = find(this.state.languages, { key: langKey }); return lang ? lang.name : translate('unknown'); } else { return langKey; } }
const stringifyParam = value => { const paramType = find(order.concat(string), p => p.matchInstance(value)); if (paramType) { return paramType.stringify(value); } else { return value; } };
return headings.reduce((memo, heading) => { let set = find(sets, (set) => set.title === heading); if (set) { memo.push(set); } return memo; }, []);
render() { const { pages, post } = this.props const { readNext } = post let nextPost if (readNext) { nextPost = find(pages, page => includes(page.path, readNext)) } if (!nextPost) { return React.createElement('noscript', null) } else { nextPost = find(pages, page => includes(page.path, readNext.slice(1, -1))) // Create pruned version of the body. const html = nextPost.data.body const body = prune(html.replace(/<[^>]*>/g, ''), 200) return ( <div> <h6 style={{ ...scale(-0.5), margin: 0, letterSpacing: -0.25 }}> READ THIS NEXT: </h6> <h3 style={{ marginTop: 0, marginBottom: rhythm(1 / 4) }}> <Link to={{ pathname: prefixLink(nextPost.path), query: { readNext: true } }}> {nextPost.data.title} </Link> </h3> <p>{body}</p> <hr /> </div> ) } }
export function findRoute(pathname) { return find(routes, (route) => pathname .replace(/(\?.*)|(#.*)/g, '') .replace(/\/$/, '') .replace(/^\//, '') === route.path ); }
function selectErrorDefinition(id, container) { var selectBox = getErrorDefinitionsField(container); var option = find(selectBox.options, function(o) { return o.value === id; }); option.selected = 'selected'; TestHelper.triggerEvent(selectBox, 'change'); }
ll = ll.map(o=>{ let direction = _find(state.attenceList.directionList, {id:o.direction}); return { ...o, directionName: direction.name, directionBackgroundColor: direction.color, } });