function mineReducer(state = { loading: false, ids: [], entities: {}, error: null }, action = {}){ const {type, payload} = action; switch (type){ case LOAD_MINE: return extend({}, state, { loading: true, error: null }); case _reject(LOAD_MINE): return extend({}, state, { loading: false, error: payload }); case resolve(LOAD_MINE): const norm = normalize(payload.items, Schemas.PLAYLIST_ARRAY); return extend({}, state, { loading: false, error: null, ids: union(state.ids, norm.result), entities: extend({}, state.entities, norm.entities.playlists) }); default: return state; } }
export default function(state = initialState, action){ switch (action.type){ case SAVE_ITEM: case REMOVE_ITEM: case LOAD_LIST: return extend({}, state, { loading: true, error: null }); case _reject(SAVE_ITEM): case _reject(REMOVE_ITEM): case _reject(LOAD_LIST): return extend({}, state, { loading: false, error: action.payload }); case resolve(SAVE_ITEM): case resolve(LOAD_LIST): case resolve(REMOVE_ITEM): return extend({}, state, { loading: false, savedItemsIds: action.payload.result, savedItems: extend({},action.payload.entities.saved_items) }); default: return state; } }
this._getContext = function() { var parent = this.getParent(); var context = this.getInitialContext(); if (parent) { context = extend({}, parent.context, context); if (parent.getChildContext) { return extend(context, parent.getChildContext()); } return context; } return context; };
export default function reducer(state = initialState, action){ const { type, payload } = action; switch (type){ case CREATE: case LIST: case GET: case DELETE: case UPDATE: return extend({}, state, { loading: true, error: null }); case _reject(LIST): case _reject(GET): case _reject(CREATE): case _reject(DELETE): case _reject(UPDATE): return extend({}, state, { loading: false, error: payload }); case resolve(CREATE): case resolve(GET): case resolve(UPDATE): if(!payload) return state; return extend({}, state, { loading: false, error: null, ids: union(state.ids, [payload.key]), entities: extend({}, state.entities, {[payload.key]: payload}) }); case resolve(DELETE): return extend({}, state, { loading: false, error: null, ids: pull(state.ids, action.payload.key), entities: omit(state.entities, action.payload.key) }); default: return state; } }
var deleteCharacter = function(tx, args) { var sel = args.selection; var direction = args.direction; var startChar, endChar; if (!sel.isCollapsed()) { throw new Error('Selection must be collapsed for transformation "deleteCharacter"'); } var prop = tx.get(sel.path); if ((sel.startOffset === 0 && direction === 'left') || (sel.startOffset === prop.length && direction === 'right')) { var tmp = merge(tx, extend({}, args, { selection: sel, containerId: args.containerId, path: sel.path, direction: direction })); sel = tmp.selection; } else { // simple delete one character startChar = (direction === 'left') ? sel.startOffset-1 : sel.startOffset; endChar = startChar+1; var op = tx.update(sel.path, { delete: { start: startChar, end: endChar } }); updateAnnotations(tx, { op: op }); sel = tx.createSelection(sel.path, startChar); } args.selection = sel; return args; };
renderIntro($$) { let totalItems = this.state.totalItems let el = $$('div').addClass('se-intro no-filters') el.append( $$('div').addClass('se-items-count').append( $$('strong').append(totalItems), ' public APIs found' ), $$(Button).addClass('se-add-api') .on('click', this._showApiDialog) .append('Add public API') ) if (this.state.dialog) { let activeKey = this.state.active let activeIndex = findIndex(this.state.items, function(item) { return item.key === activeKey }) el.append( $$(Modal, { width: 'middle' }).addClass('se-api-form-modal').append( $$(ApiForm, extend({}, {currentApp: this.props.app}, this.state.items[activeIndex])).ref('api-form') ) ) } return el }
const globalReset = () => { const ExpressBrute = require('express-brute'); const BruteKnex = require('brute-knex'); const db = require('../../../../data/db'); store = store || new BruteKnex({ tablename: 'brute', createTable: false, knex: db.knex }); globalResetInstance = globalResetInstance || new ExpressBrute(store, extend({ attachResetToRequest: false, failCallback(req, res, next, nextValidRequestDate) { // TODO use i18n again return next(new common.errors.TooManyRequestsError({ message: `Too many attempts try again in ${moment(nextValidRequestDate).fromNow(true)}`, context: common.i18n.t('errors.middleware.spamprevention.forgottenPasswordIp.error', {rfa: spamGlobalReset.freeRetries + 1 || 5, rfp: spamGlobalReset.lifetime || 60 * 60}), help: common.i18n.t('errors.middleware.spamprevention.forgottenPasswordIp.context') })); }, handleStoreError: handleStoreError }, pick(spamGlobalReset, spamConfigKeys)) ); return globalResetInstance; };
const contentApiKey = () => { const ExpressBrute = require('express-brute'); const BruteKnex = require('brute-knex'); const db = require('../../../../data/db'); store = store || new BruteKnex({ tablename: 'brute', createTable: false, knex: db.knex }); contentApiKeyInstance = contentApiKeyInstance || new ExpressBrute(store, extend({ attachResetToRequest: true, failCallback(req, res, next) { const err = new common.errors.GhostError({ message: common.i18n.t('errors.middleware.spamprevention.tooManyAttempts') }); common.logging.error(err); return next(err); }, handleStoreError: handleStoreError }, pick(spamContentApiKey, spamConfigKeys)) ); return contentApiKeyInstance; };
const userLogin = () => { const ExpressBrute = require('express-brute'); const BruteKnex = require('brute-knex'); const db = require('../../../../data/db'); store = store || new BruteKnex({ tablename: 'brute', createTable: false, knex: db.knex }); userLoginInstance = userLoginInstance || new ExpressBrute(store, extend({ attachResetToRequest: true, failCallback(req, res, next, nextValidRequestDate) { return next(new common.errors.TooManyRequestsError({ message: `Too many sign-in attempts try again in ${moment(nextValidRequestDate).fromNow(true)}`, // TODO add more options to i18n context: common.i18n.t('errors.middleware.spamprevention.tooManySigninAttempts.context'), help: common.i18n.t('errors.middleware.spamprevention.tooManySigninAttempts.context') })); }, handleStoreError: handleStoreError }, pick(spamUserLogin, spamConfigKeys)) ); return userLoginInstance; };
var methodBody = function() { var argsLength = arguments.length; var args = new Array(argsLength); for (var i = 0; i < argsLength; i++) { args[i] = arguments[i]; } var requiredParamsStart = apiPathParamsCount; var requiredParamsEnd = requiredParamsStart + paramNames.length; var requiredParamArgs = args.slice(requiredParamsStart, requiredParamsEnd); // Callback is at the end var callback = isFunction(args[args.length - 1]) ? args.pop() : null; // Required Parmas var params = zipObject(paramNames, requiredParamArgs); extend(params, isPlainObject(args[args.length - 1]) ? args.pop() : {}); // Path arguments are determined after required parameters var apiPathArgs = args.slice(0, apiPathParamsCount); var request = requestType; if (isString(requestType)) { request = requestType.toUpperCase() === 'POST' ? client.postRequest : client.getRequest; } else if (!isFunction(requestType)) { request = client.getRequest; } return request.call(client, buildApiPath(apiPathArgs), params, callback); };
this.getChildContext = function() { var childContext = Controller.prototype.getChildContext.call(this); return extend(childContext, { toc: this.toc, i18n: I18n.instance, }); };
return function(blogIdentifier, params, callback) { params = extend({type: type}, params); if (isArray(validate)) { validate = partial(function(params, requireKeys) { if (requireKeys.length) { var keyIntersection = intersection(keys(params), requireKeys); if (requireKeys.length === 1 && !keyIntersection.length) { throw new Error('Missing required field: ' + requireKeys[0]); } else if (!keyIntersection.length) { throw new Error('Missing one of: ' + requireKeys.join(', ')); } else if (keyIntersection.length > 1) { throw new Error('Can only use one of: ' + requireKeys.join(', ')); } } return true; }, params, validate); } if (isFunction(validate)) { if (!validate(params)) { throw new Error('Error validating parameters'); } } if (arguments.length > 2) { return this.createPost(blogIdentifier, params, callback); } else { return this.createPost(blogIdentifier, params); } };
export default function (url,opt,callback) { let DEFAULT = { method: 'GET', credentials: 'same-origin', headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } }; let options = merge({}, DEFAULT, opt); if (options.method === 'GET'){ options.body = extend({}, options.body, { _: Date.now() }); url = `${url}?${transformRequest(options.body)}`; options.body = void(0); }else if(options.headers['Content-Type'] === 'application/x-www-form-urlencoded'){ options.body = transformRequest(options.body); }else if(options.headers['Content-Type'] === 'application/json'){ options.body = stringifyJSON(options.body); } return fetch(url,options) .then((response) => { if (response.status >= 200 && response.status < 300 || response.status === 302) { return response.json(); } else { return Promise.reject({ status: false, msg: '网络错误' }); } }) .then(callback && callback.bind(this) || function (rs) {return rs;}) .catch((fail) => Promise.reject(fail) ); }
function XMLExporter(config) { config = extend({ idAttribute: 'id' }, config); DOMExporter.call(this, config); // used internally for creating elements this._el = DefaultDOMElement.parseXML('<dummy></dummy>'); }
this.enhanceCollaborator(req, function(err, info) { if (!err && info) { collaborator = extend({}, info, collaborator); // Store info for each collaborator this._collaboratorInfo[args.collaboratorId] = info; } // Notify others that there is a new collaborator this.broadCast(collaboratorIds, { type: 'collaboratorConnected', documentId: args.documentId, collaborator: collaborator }); // Get enhance collaborators (e.g. including some app-specific user-info) var collaborators = this.getEnhanceCollaborators(args.documentId, args.collaboratorId); // Send the response res.send({ type: 'connectDone', documentId: args.documentId, version: result.version, changes: result.changes, collaborators: collaborators }); }.bind(this));
function HTMLImporter(config) { config = extend({ idAttribute: 'data-id' }, config); DOMImporter.call(this, config); // only used internally for creating wrapper elements this._el = DefaultDOMElement.parseHTML('<html></html>'); }
NodeIndex.create = function(prototype) { var index = extend(new NodeIndex(), prototype); index.clone = function() { return NodeIndex.create(prototype); }; return index; };
function() { function runTask() { run(task); } defaults(task.options, { sourceMap: !!(task.sourceMappings || task.sourceMap), }); extend(task.options, taskOpts); if (dynamicOpts) dynamicOpts(task.options, task); const throwMsg = task.options.throws; if (throwMsg) { // internal api doesn't have this option but it's best not to pollute // the options object with useless options delete task.options.throws; assert.throws(runTask, function(err) { return ( throwMsg === true || err.message.indexOf(throwMsg) >= 0 ); }); } else { if (task.exec.code) { const result = run(task); if (result && typeof result.then === "function") { return result; } } else { runTask(); } } },
const privateBlog = () => { const ExpressBrute = require('express-brute'); const BruteKnex = require('brute-knex'); const db = require('../../../../data/db'); store = store || new BruteKnex({ tablename: 'brute', createTable: false, knex: db.knex }); privateBlogInstance = privateBlogInstance || new ExpressBrute(store, extend({ attachResetToRequest: false, failCallback(req, res, next, nextValidRequestDate) { common.logging.error(new common.errors.GhostError({ message: common.i18n.t('errors.middleware.spamprevention.tooManySigninAttempts.error', { rateSigninAttempts: spamPrivateBlog.freeRetries + 1 || 5, rateSigninPeriod: spamPrivateBlog.lifetime || 60 * 60 }), context: common.i18n.t('errors.middleware.spamprevention.tooManySigninAttempts.context') })); return next(new common.errors.GhostError({ message: `Too many private sign-in attempts try again in ${moment(nextValidRequestDate).fromNow(true)}` })); }, handleStoreError: handleStoreError }, pick(spamPrivateBlog, spamConfigKeys)) ); return privateBlogInstance; };
function BrowserifyHook(options) { this.options = extend({ jsx: false, es6: false, cache: true, }, options); }
function transform(file, enc, callback) { if (file.isStream()) { this.emit('error', new PluginError(PLUGIN_NAME, 'Streams not supported')); return callback(); } let rollupOpts = options.rollup || {}; rollup(extend({ entry: file.path }, rollupOpts)).then((bundle) => { let result = bundle.generate(options.bundle) file.contents = new Buffer(result.code, enc); callback(null, file); }).catch(err => { let message = originalError.annotated || originalError.message; let details = { name: originalError.name, stack: originalError.stack, fileName: originalError.fileName, lineNumber: originalError.lineNumber }; this.emit('error', new PluginError(PLUGIN_NAME, message, details)); callback(); }); }
_showResults: function(results, options) { this.showResults( this.selectivity.filterResults(results), extend({ dropdown: this }, options) ); },
this.setTagName = function(tagName) { var newEl = $._createElement(tagName, this.el.root); var $newEl = $(newEl); $newEl.html(this.$el.html()); newEl.attribs = extend({}, this.el.attribs); this._replaceNativeEl(newEl); return this; };
Meteor.publish('experiments.by-acronym', function (projectAcr) { ensuresArg('Publishing experiments.by-acronym, argument `projectAcr`', projectAcr, String) let prj = Project.findOne({ acronym: projectAcr }, { fields: basicPrjFields }) if (prj && prj.isUserMember(this.userId)) { let constrains = expRetrievalConstrains.call(this, prj) return Exp.find(extend({projectId: getp(prj, '_id')}, constrains)) } else return [] })
this.addIcon = function(iconName, options) { var iconConfig = this.config.icons[iconName]; if (!iconConfig) { iconConfig = {}; this.config.icons[iconName] = iconConfig; } extend(iconConfig, options); };
triggerEvent: function(eventName, data) { var event = document.createEvent('Event'); event.initEvent(eventName, /* bubbles: */ false, /* cancelable: */ true); extend(event, data); this.el.dispatchEvent(event); return !event.defaultPrevented; },
Selectivity.OptionListeners.push(function(selectivity, options) { if (options.tokenSeparators) { options.allowedTypes = extend({ tokenSeparators: 'array' }, options.allowedTypes); options.tokenizer = options.tokenizer || defaultTokenizer; } });
parse (datas){ datas = _sortBy( datas, (movie) => movie.name.toLowerCase() ); return _extend( this.datas, { allMovies: datas, movies: datas } ); }
fs.readFile(file, 'utf8', (err, content) => { if (err) { cb(err); } else { exports.transform(content, extend({}, opts, { filename: path.basename(file) }), cb); } });
const getMutationObject = (key) => { const mutationTargetProps = getTargetProps({childName, key, target}, "props"); const mutationTargetState = getTargetProps({childName, key, target}, "state"); const mutation = eventReturn.mutation || nullFunction; const mutatedProps = mutation( assign({}, mutationTargetProps, mutationTargetState), baseProps ); const childState = this.state[childName] || {}; return childName ? extend(this.state, { [childName]: extend(childState, { [key]: extend(childState[key], {[target]: mutatedProps}) }) }) : extend(this.state, { [key]: extend(this.state[key], {[target]: mutatedProps}) }); };