(res, val) => res && isPlainObject(val) && isString(val.name) && (isUndefined(val.label) || isString(val.label)) && (isUndefined(val.template) || isString(val.template) || isFunction(val.template)) && (isUndefined(val.transformData) || isFunction(val.transformData)),
/** * Registers a callable for a specific data filter supported by YoastSEO. * * Can only be performed for plugins that have finished loading. * * @param {string} modification The name of the filter. * @param {Function} callable The callable. * @param {string} pluginName The plugin that is registering the * modification. * @param {number} [priority] Used to specify the order in which the * callables associated with a particular * filter are called. Lower numbers * correspond with earlier execution. * * @returns {boolean} Whether or not applying the hook was successful. */ _registerModification( modification, callable, pluginName, priority ) { if ( ! isString( modification ) ) { console.error( "Failed to register modification for plugin " + pluginName + ". Expected parameter `modification` to be a string." ); return false; } if ( ! isFunction( callable ) ) { console.error( "Failed to register modification for plugin " + pluginName + ". Expected parameter `callable` to be a function." ); return false; } if ( ! isString( pluginName ) ) { console.error( "Failed to register modification for plugin " + pluginName + ". Expected parameter `pluginName` to be a string." ); return false; } if ( this._validateOrigin( pluginName ) === false ) { console.error( "Failed to register modification for plugin " + pluginName + ". The integration has not finished loading yet." ); return false; } // Default priority to 10. const prio = isNumber( priority ) ? priority : 10; const callableObject = { callable: callable, origin: pluginName, priority: prio, }; // Make sure modification is defined on modifications object. if ( isUndefined( this.modifications[ modification ] ) ) { this.modifications[ modification ] = []; } this.modifications[ modification ].push( callableObject ); return true; }
function ReactPlugin(options) { // Make sure the plugin was instantiated as a constructor, i.e. new ReactPlugin() if (!(this instanceof ReactPlugin)) { throw new Error( 'The ReactPlugin must be instantiated with the "new" keyword, i.e. "new ReactPlugin()"\n\n' ); } this.options = options || {}; // The hostname option must be a string if (this.options.hostname && !isString(this.options.hostname)) { throw new Error('The "hostname" option of the ReactPlugin must be a string!\n\n'); } const parsedPort = parseFloat(this.options.port); // The port option must be something that can be made a number if (this.options.port && !isNaN(parsedPort)) { throw new Error('The "port" option of the ReactPlugin must be a number!\n\n'); } // If the port can be interpreted as a number, it must be above 0 and below 65535 if (parsedPort < 0 || parsedPort > 65535) { throw new Error('The "port" must be between 0 and 65535 (inc)!\n\n'); } // The variationFolderName option must be a string if (this.options.variationFolderName && !isString(this.options.variationFolderName)) { throw new Error( 'The "variationFolderName" option of the ReactPlugin must be a string!\n\n' ); } }
const route = (path, method, ...middleware) => function(target, k, descriptor) { if (!isString(path)) { throw new TypeError("Path should be a string.") } if (!target.router) { target.router = new Router() } if (isEmpty(method)) { throw new Error("HTTP method name cannot be empty.") } if (!isString(method)) { throw new TypeError("HTTP method name should be a string.") } method = toLowerCase(method) if (!(method in methods)) { throw new Error(`Unknown HTTP method name: ${method}`) } // Add handler to given method // TODO: Add support for static class methods though initializer target.router[method](path, ...middleware, descriptor.value) }
static _massageTokenState(state) { if (isString(state)) { state = Token.stateFromCode(state); } else if (isString(state.type)) { state.type = tt[state.type]; } return state; }
var SMS = function (appid, secret) { if (!isString(appid)) throw new Error('appid should be string') if (!isString(secret)) throw new Error('secret should be string') this._appid = appid this._secret = secret this._recipients = [] return this }
it('returns error on invalid or negative cancel delay', () => { assert(_isString(validateParams({ ...validParams, cancelDelay: 'nope' }))) assert(_isString(validateParams({ ...validParams, cancelDelay: -100 }))) })
it('returns error on invalid or negative slice interval', () => { assert(_isString(validateParams({ ...validParams, sliceInterval: 'nope' }))) assert(_isString(validateParams({ ...validParams, sliceInterval: -100 }))) })
constructor (options = {}) { if (!(arguments.length === 2 && _isString(arguments[0]) && _isArray(arguments[1])) && !(arguments.length === 1 && (_isPlainObject(arguments[0]) || _isString(arguments[0])))) { throw new Error('Invalid argument, initialize Devour with an object.') } let defaults = { middleware: jsonApiMiddleware, logger: true, resetBuilderOnCall: true, auth: {}, trailingSlash: {collection: false, resource: false} } let deprecatedConstructors = (args) => { return (args.length === 2 || (args.length === 1 && _isString(args[0]))) } if (deprecatedConstructors(arguments)) { defaults.apiUrl = arguments[0] if (arguments.length === 2) { defaults.middleware = arguments[1] } } options = _defaultsDeep(options, defaults) let middleware = options.middleware this._originalMiddleware = middleware.slice(0) this.middleware = middleware.slice(0) this.headers = {} this.axios = axios this.auth = options.auth this.apiUrl = options.apiUrl this.models = {} this.deserialize = deserialize this.serialize = serialize this.builderStack = [] this.resetBuilderOnCall = !!options.resetBuilderOnCall if (options.pluralize === false) { this.pluralize = s => s this.pluralize.singular = s => s } else if ('pluralize' in options) { this.pluralize = options.pluralize } else { this.pluralize = pluralize } this.trailingSlash = options.trailingSlash === true ? _forOwn(_clone(defaults.trailingSlash), (v, k, o) => { _set(o, k, true) }) : options.trailingSlash options.logger ? Logger.enable() : Logger.disable() if (deprecatedConstructors(arguments)) { Logger.warn('Constructor (apiUrl, middleware) has been deprecated, initialize Devour with an object.') } }
it('returns string handles', () => { const source = new NormalSource(); const sourceId = registry.addSource(Types.FOO, source); const targetA = new NormalTarget(); const targetAId = registry.addTarget(Types.FOO, targetA); const targetB = new NormalTarget(); const targetBId = registry.addTarget([Types.FOO, Types.BAR], targetB); expect(isString(sourceId)).to.equal(true); expect(isString(targetAId)).to.equal(true); expect(isString(targetBId)).to.equal(true); });
cli.flags = reduce(cli.flags, (res, val, key) => { if (key.length <= 1) { return res; } switch (key) { case 'htmltarget': res.htmlTarget = val; break; case 'styletarget': res.styleTarget = val; break; case 'pathprefix': res.pathPrefix = val; break; case 'inlineimages': res.inlineImages = val; break; case 'maxfilesize': res.maxFileSize = val; break; case 'timeout': res.timeout = val; break; case 'assetpaths': case 'assetPaths': if (isString(val)) { val = [val]; } res.assetPaths = val; break; case 'include': case 'ignore': if (isString(val) || isRegExp(val)) { val = [val]; } res[key] = map(val || [], entry => { // Check regex const match = entry.match(/^\/(.*)\/([igmy]+)?$/); if (match) { return new RegExp(escapeRegExp(match[1]), match[2]); } return entry; }); break; default: res[key] = val; break; } return res; }, {});
var fixture = function (fixtureName, options) { options = isObject(options) ? options : {}; var jsName = isString(options.js) ? options.js : fixtureName; var levelsName = isString(options.levels) ? options.levels : fixtureName; var code = fs.readFileSync(path.join(fixturesDirectory, jsName) + '.js', 'utf8'); var levels = fs.readFileSync(path.join(fixturesDirectory, levelsName) + '.levels', 'utf8'); var scopifyOptions = pick(options, 'blockScope'); return function () { var file = createTernFile(jsName + '.js', code, options); var tokens = scopify(walk, file.ast, file.scope, scopifyOptions); assertLevels(tokensToLevels(code, tokens), levels); }; };
const $ = (root, options0, fnMatch0) => { let options = options0; let fnMatch = fnMatch0; if (isFunction(options0) || isString(options0)) { options = {}; fnMatch = options0; } options = addDefaults(options, { fIncludeTextElements: false, fLog: false, }); if (isString(fnMatch)) fnMatch = getMatcher(fnMatch); return visitElement(root, options, fnMatch); };
it('returns error on numeric price target with invalid price condition', () => { assert(_isString(validateParams({ ...validParams, priceTarget: 100, priceCondition: 'nope' }))) })
function castGeojson(format, value) { if (!isObject(value)) { if (!isString(value)) { return ERROR } try { value = JSON.parse(value) } catch (error) { return ERROR } if (!isPlainObject(value)) { return ERROR } } if (format === 'default') { try { const valid = tv4.validate(value, geojsonProfile) if (!valid) { return ERROR } } catch (error) { return ERROR } } else if (format === 'topojson') { try { const valid = tv4.validate(value, topojsonProfile) if (!valid) { return ERROR } } catch (error) { return ERROR } } return value }
export default function validateString(string, errorMessage) { if (!isString(string)) { throw new Error(errorMessage); } return string; }
module.exports = (state = {}, price) => { const { args = {}, remainingAmount } = state const { sliceAmount, orderType, symbol, amount, _margin } = args const m = amount < 0 ? -1 : 1 const rem = m === 1 ? Math.min(sliceAmount, remainingAmount) : Math.max(sliceAmount, remainingAmount) if (Math.abs(rem) < DUST) { return null } return new Order({ symbol, price, cid: nonce(), amount: rem, type: _isString(orderType) ? orderType : _margin ? 'MARKET' : 'EXCHANGE MARKET' }) }
lessThanOrEqualTo(field, value) { if (!isNumber(value) && !isString(value)) { throw new Error('You must supply a number or string.'); } return this.addFilter(field, '$lte', value); }
function iterateTree(tree, level=0, index=0) { let tag = tree.shift(); const key = onGenerateKey(tag, index); const props = (tree.length && isPlainObject(tree[0])) ? Object.assign(tree.shift(), { key: key }) : { key: key }; if (level === 0 && className) { props.className = className; } const children = tree.map( (branch, idx) => Array.isArray(branch) ? iterateTree(branch, level + 1, idx) : branch ); tag = tags[tag] || tag; if (isString(props.style)) { props.style = zipObject( props.style.split(';') .map(prop => prop.split(':')) .map(keyVal => [camelCase(keyVal[0].trim()), keyVal[1].trim()]) ); } return (typeof onIterate === 'function') ? onIterate(tag, props, children, level) : React.createElement(tag, props, children); }
/** * Creates and returns a `MEMO_ID` memo. * @param {string} id - 64-bit number represented as a string * @returns {xdr.Memo} */ static id(id) { let error = new Error("Expects a int64 as a string. Got " + id); if (!isString(id)) { throw error; } let number; try { number = new BigNumber(id); } catch (e) { throw error; } // Infinity if (!number.isFinite()) { throw error; } // NaN if (number.isNaN()) { throw error; } return xdr.Memo.memoId(UnsignedHyper.fromString(id)); }
/** * Adds a greater than filter to the query. Requires `field` to be greater * than `value`. * http://docs.mongodb.org/manual/reference/operator/gt/ * * @param {String} field Field. * @param {Number|String} value Value. * @throws {Error} `value` must be of type: `number` or `string`. * @returns {Query} The query. */ greaterThan(field, value) { if (!isNumber(value) && !isString(value)) { throw new Error('You must supply a number or string.'); } return this.addFilter(field, '$gt', value); }
return map(pth, function(p){ // Arrays of paths can contain a mix of both strings and RegExps if(isString(p)){ return path.resolve(process.cwd(), p); } return p });
export function decodeCheck(versionByteName, encoded) { if (!isString(encoded)) { throw new TypeError('encoded argument must be of type String'); } let decoded = base32.decode(encoded); let versionByte = decoded[0]; let payload = decoded.slice(0, -2); let data = payload.slice(1); let checksum = decoded.slice(-2); if (encoded != base32.encode(decoded)) { throw new Error('invalid encoded string'); } let expectedVersion = versionBytes[versionByteName]; if (isUndefined(expectedVersion)) { throw new Error(`${versionByteName} is not a valid version byte name. expected one of "accountId" or "seed"`); } if (versionByte !== expectedVersion) { throw new Error(`invalid version byte. expected ${expectedVersion}, got ${versionByte}`); } let expectedChecksum = calculateChecksum(payload); if (!verifyChecksum(expectedChecksum, checksum)) { throw new Error(`invalid checksum`); } return new Buffer(data); }
rcLoader.for(file.path, function (err, cfg) { if (err) return cb(err); var globals = {}; if (cfg.globals) { globals = cfg.globals; delete cfg.globals; } if (cfg.overrides) { forEach(cfg.overrides, function (options, pattern) { if (!minimatch(file.path, pattern, { nocase: true, matchBase: true })) return; if (options.globals) { globals = assign(globals, options.globals); delete options.globals; } assign(cfg, options); }); delete cfg.overrides; } // get or create file.jshint, we will write all output here var out = file.jshint || (file.jshint = {}); var str = isString(out.extracted) ? out.extracted : file.contents.toString('utf8'); out.success = jshint(str, cfg, globals); if (!out.success) reportErrors(file, out, cfg); return cb(null, file); });
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); };
plumbing.init = function (requestOptions) { var self = this; self._rp_promise = new PromiseImpl(function (resolve, reject) { self._rp_resolve = resolve; self._rp_reject = reject; }); self._rp_callbackOrig = requestOptions.callback; requestOptions.callback = self.callback = function RP$callback(err, response, body) { plumbing.callback.call(self, err, response, body); }; if (isString(requestOptions.method)) { requestOptions.method = requestOptions.method.toUpperCase(); } requestOptions.transform = requestOptions.transform || plumbing.defaultTransformations[requestOptions.method]; self._rp_options = requestOptions; self._rp_options.simple = requestOptions.simple !== false; self._rp_options.resolveWithFullResponse = requestOptions.resolveWithFullResponse === true; self._rp_options.transform2xxOnly = requestOptions.transform2xxOnly === true; };
registerConnector('dsv', (str, options = {}) => { const delimiter = options.delimiter || ','; if (!isString(delimiter)) { throw new TypeError('Invalid delimiter: must be a string!'); } return dsvFormat(delimiter).parse(str); });
importSass.then(sass => { if (isString(scss.content) && isEmpty(scss.content) || !isUndefined(scss.content.responseText) && isEmpty(scss.content.responseText)) { return resolve(''); } sass.compile(scss.content, scss.options, result => { if (result.status === 0) { if (!isUndefined(System.sassPluginOptions) && System.sassPluginOptions.autoprefixer) { if (!result.text) { log('error', System.meta.loadAddress + ' did not parse!'); resolve(escape(' ')); return; } postcss([autoprefixer]).process(result.text).then(({ css, }) => { resolve(escape(css)); }); } else { resolve(escape(result.text)); } } else { log('warn', 'Stacklite :: github:KevCJones/plugin-scss/sass-inject-build.js -> npm:sass.js'); log('error', result.formatted); reject(result.formatted); } }); });
request.Request.prototype.init = function RP$initInterceptor(options) { var self = this; // Init may be called again - currently in case of redirects if (isPlainObject(options) && self._callback === undefined && self._rp_promise === undefined) { self._rp_promise = new Bluebird(function (resolve, reject) { self._rp_resolve = resolve; self._rp_reject = reject; }); self._rp_callbackOrig = self.callback; self.callback = RP$callback; if (isString(options.method)) { options.method = options.method.toUpperCase(); } options.transform = options.transform || defaultTransformations[options.method]; self._rp_options = options; self._rp_options.simple = options.simple === false ? false : true; self._rp_options.resolveWithFullResponse = options.resolveWithFullResponse === true ? true : false; } return originalInit.apply(self, arguments); };
// Builds the app and runs it on a connected emulator / device. function buildAndRun(args) { process.chdir(path.join(args.root, 'android')); const cmd = process.platform.startsWith('win') ? 'gradlew.bat' : './gradlew'; const packageName = fs .readFileSync(`${args.appFolder}/src/main/AndroidManifest.xml`, 'utf8') .match(/package="(.+?)"/)[1]; const packageNameWithSuffix = getPackageNameWithSuffix( args.appId, args.appIdSuffix, packageName, ); const adbPath = getAdbPath(); if (args.deviceId) { if (isString(args.deviceId)) { runOnSpecificDevice( args, cmd, packageNameWithSuffix, packageName, adbPath, ); } else { console.log(chalk.red('Argument missing for parameter --deviceId')); } } else { runOnAllDevices(args, cmd, packageNameWithSuffix, packageName, adbPath); } }