_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q49100
removeIgnoredLevels
train
function removeIgnoredLevels(response, options) { try { const filteredLevels = getLevelsToAudit(options); if (filteredLevels && filteredLevels.indexOf(auditLevel.low) >= 0) { return response; } const filteredResponse = JSON.parse(JSON.stringify(response, null, 2)); ...
javascript
{ "resource": "" }
q49101
addSensitiveDataInfosIn
train
function addSensitiveDataInfosIn(response) { const allSensitiveDataPatterns = getSensitiveData(process.cwd()); const augmentedResponse = JSON.parse(JSON.stringify(response, null, 2)); const files = augmentedResponse.files || []; files.forEach((file) => { if (file && isSensitiveData(file.path, al...
javascript
{ "resource": "" }
q49102
isSensitiveData
train
function isSensitiveData(filepath, allSensitiveDataPatterns) { if ( filepath && allSensitiveDataPatterns && allSensitiveDataPatterns.ignoredData && globMatching.any(filepath, allSensitiveDataPatterns.ignoredData, { matchBase: true, nocase: true, }) ...
javascript
{ "resource": "" }
q49103
updateSensitiveDataInfosOfIgnoredFilesIn
train
function updateSensitiveDataInfosOfIgnoredFilesIn(response, options) { const ignoredData = getIgnoredSensitiveData(options); const updatedResponse = JSON.parse(JSON.stringify(response, null, 2)); const files = updatedResponse.files || []; files.forEach((file) => { if ( file && ...
javascript
{ "resource": "" }
q49104
getIgnoredSensitiveData
train
function getIgnoredSensitiveData(options) { try { const sensitiveDataIgnoreFile = pathJoin( options.directoryToPackage, '.publishrc' ); const publishPleaseConfiguration = JSON.parse( readFile(sensitiveDataIgnoreFile).toString() ); const res...
javascript
{ "resource": "" }
q49105
removePackageTarFileFrom
train
function removePackageTarFileFrom(projectDir, response) { try { const file = pathJoin(projectDir, response.filename); unlink(file); return response; } catch (error) { if (error.code === 'ENOENT') { return response; } if (response) { respons...
javascript
{ "resource": "" }
q49106
getCustomSensitiveData
train
function getCustomSensitiveData(projectDir) { const sensitiveDataFile = pathJoin(projectDir, '.sensitivedata'); const content = readFile(sensitiveDataFile).toString(); const allPatterns = content .split(/\n|\r/) .map((line) => line.replace(/[\t]/g, ' ')) .map((line) => line.trim()) ...
javascript
{ "resource": "" }
q49107
createNodeServer
train
function createNodeServer(http, nodePort, webSocketPort, watchFiles, tsWarning, tsError, target) { return http.createServer(async (req, res) => { try { const fileExtension = req.url.slice(req.url.lastIndexOf('.') + 1); switch (fileExtension) { case '/': { ...
javascript
{ "resource": "" }
q49108
styleToFilters
train
function styleToFilters(style) { var layers = {}; // Store layers and filters used in style if (style && style.layers) { for (var i = 0; i < style.layers.length; i++) { var layerName = style.layers[i]['source-layer']; if (layerName) { // if the layer already exists in our filters, update i...
javascript
{ "resource": "" }
q49109
createMessage
train
function createMessage(type, transaction) { const msg = new StunMessage(); msg.setType(type); msg.setTransactionID(transaction || createTransaction()); return msg; }
javascript
{ "resource": "" }
q49110
createDgramServer
train
function createDgramServer(options = {}) { let isExternalSocket = false; if (options.socket instanceof dgram.Socket) { isExternalSocket = true; } const socket = isExternalSocket ? options.socket : dgram.createSocket('udp4'); const server = new StunServer(socket); if (!isExternalSocket) { socket.o...
javascript
{ "resource": "" }
q49111
normalize
train
function normalize(gj) { if (!gj || !gj.type) return null; var type = types[gj.type]; if (!type) return null; if (type === 'geometry') { return { type: 'FeatureCollection', features: [{ type: 'Feature', properties: {}, geom...
javascript
{ "resource": "" }
q49112
establishServerSession
train
function establishServerSession(req, path, newPage, reset, newControllerId, sessions, controllers, nonObjTemplatelogLevel) { let applicationConfig = AmorphicContext.applicationConfig; // Retrieve configuration information let config = applicationConfig[path]; if (!config) { throw new Error('S...
javascript
{ "resource": "" }
q49113
processPost
train
function processPost(req, res, sessions, controllers, nonObjTemplatelogLevel) { let session = req.session; let path = url.parse(req.originalUrl, true).query.path; establishServerSession(req, path, false, false, null, sessions, controllers, nonObjTemplatelogLevel) .then(function ff(semotus) { ...
javascript
{ "resource": "" }
q49114
train
function () { if (this.state == 'zombie') { this.expireController(); // Toss anything that might have happened RemoteObjectTemplate.enableSendMessage(true, this.sendMessage); // Re-enable sending this.state = 'live'; this.rootId = null; // Cancel forcing our c...
javascript
{ "resource": "" }
q49115
train
function () { if (RemoteObjectTemplate.getPendingCallCount() == 0 && this.getCookie('session' + this.app) != this.session) { if (this.state != 'zombie') { this.state = 'zombie'; this.expireController(); RemoteObjectTemplate.enableSendMessage(false); ...
javascript
{ "resource": "" }
q49116
train
function () { var self = this; self.activity = false; if (self.heartBeat) { clearTimeout(self.heartBeat); } self.heartBeat = setTimeout(function () { if (self.state == 'live') { if (self.activity) { console.log('Server...
javascript
{ "resource": "" }
q49117
setUpInjectObjectTemplate
train
function setUpInjectObjectTemplate(appName, config, schema) { let amorphicOptions = AmorphicContext.amorphicOptions || {}; let dbConfig = buildDbConfig(appName, config); let connectToDbIfNeedBe = Bluebird.resolve(false); // Default to no need. if (dbConfig.dbName && dbConfig.dbPath) { if (dbCon...
javascript
{ "resource": "" }
q49118
buildDbConfig
train
function buildDbConfig(appName, config) { var dbDriver = fetchFromConfig(appName, config, 'dbDriver') || 'mongo'; var defaultPort = dbDriver === 'mongo' ? 27017 : 5432; return { dbName: fetchFromConfig(appName, config, 'dbName'), dbPath: fetchFromConfig(appName, config, 'dbPa...
javascript
{ "resource": "" }
q49119
fetchFromConfig
train
function fetchFromConfig(appName, config, toFetch) { let lowerCase = toFetch.toLowerCase(); return config.nconf.get(appName + '_' + toFetch) || config.nconf.get(toFetch) || config.nconf.get(lowerCase); }
javascript
{ "resource": "" }
q49120
returnBoundInjectTemplate
train
function returnBoundInjectTemplate(amorphicOptions, config, dbConfig, schema, db) { // Return the bound version so we always keep the config and dbConfig. return injectObjectTemplate.bind(null, amorphicOptions, config, dbConfig, db, schema); }
javascript
{ "resource": "" }
q49121
loadAppConfigToContext
train
function loadAppConfigToContext(appName, config, path, commonPath, initObjectTemplateFunc, sessionStore) { let amorphicOptions = AmorphicContext.amorphicOptions; AmorphicContext.applicationConfig[appName] = { appPath: path, commonPath: commonPath, initObjectTe...
javascript
{ "resource": "" }
q49122
loadTemplates
train
function loadTemplates(appName) { let appConfig = AmorphicContext.applicationConfig[appName] || {}; let applicationSource = AmorphicContext.applicationSource; let applicationSourceMap = AmorphicContext.applicationSourceMap; let controllerPath = (appConfig.appConfig.controller || 'controller.js'); l...
javascript
{ "resource": "" }
q49123
checkTypes
train
function checkTypes(classes) { var classCount = 0, nullType = 0, nullOf = 0, propCount = 0; for (var classKey in classes) { ++classCount; for (var definePropertyKey in classes[classKey].amorphicProperties) { var defineProperty = classes[classKey].amorphicProperties[definePropertyKey]...
javascript
{ "resource": "" }
q49124
establishContinuedServerSession
train
function establishContinuedServerSession(req, controllerPath, initObjectTemplate, path, appVersion, sessionExpiration, session, sessionStore, newControllerId, objectCacheExpiration, newPage, contro...
javascript
{ "resource": "" }
q49125
Remoteable
train
function Remoteable (Base) { return (function n(_super) { __extends(classOne, _super); function classOne() { return _super !== null && _super.apply(this, arguments) || this; } return classOne; }(Base)); }
javascript
{ "resource": "" }
q49126
bindDecorators
train
function bindDecorators (objectTemplate) { // TODO: In what situation would objectTemplate be null and why is it acceptable just to use this as a replacement? objectTemplate = objectTemplate || this; this.Amorphic = objectTemplate; this.amorphicStatic = objectTemplate; /** * Purpose unknown ...
javascript
{ "resource": "" }
q49127
teamOutAction
train
function teamOutAction() { sessionStore.get(sessionId, function aa(_error, expressSession) { if (!expressSession) { log(1, sessionId, 'Session has expired', nonObjTemplatelogLevel); } if (!expressSession || cachedController.controller.__templa...
javascript
{ "resource": "" }
q49128
readFile
train
function readFile(file) { if (file && fs.existsSync(file)) { return fs.readFileSync(file); } return null; }
javascript
{ "resource": "" }
q49129
setupLogger
train
function setupLogger(logger, path, context, applicationConfig) { logger.startContext(context); logger.setLevel(applicationConfig[path].logLevel); if (AmorphicContext.appContext.sendToLog) { logger.sendToLog = AmorphicContext.appContext.sendToLog; } }
javascript
{ "resource": "" }
q49130
getSessionCache
train
function getSessionCache(path, sessionId, keepTimeout, sessions) { let key = path + '-' + sessionId; let session = sessions[key] || {sequence: 1, serializationTimeStamp: null, timeout: null, semotus: {}}; sessions[key] = session; if (!keepTimeout) { if (session.timeout) { clearTimeo...
javascript
{ "resource": "" }
q49131
train
function(isVisible) { var self = this, $textEl = self.$el.find(self.options.toggleTextSelector); if (isVisible) { $textEl.text(self.$el.data('expanded-text')); } else { $textEl.text(self....
javascript
{ "resource": "" }
q49132
train
function(name, path) { return function(requiredPaths, moduleFunction) { var requiredModules = [], pathCount = requiredPaths.length, requiredModule, module, i; for (i = ...
javascript
{ "resource": "" }
q49133
train
function(page) { var oldPage = this.state.currentPage, self = this, deferred = $.Deferred(); this.getPage(page - (1 - this.state.firstPage), {reset: true}).then( function() { self.isStale = false; ...
javascript
{ "resource": "" }
q49134
train
function() { var deferred = $.Deferred(); if (this.isStale) { this.setPage(1) .done(function() { deferred.resolve(); }); } else { deferred.resolve(); ...
javascript
{ "resource": "" }
q49135
train
function(fields, fieldName, displayName) { var newField = {}; newField[fieldName] = { displayName: displayName }; _.extend(fields, newField); }
javascript
{ "resource": "" }
q49136
train
function(fieldName, toggleDirection) { var direction = toggleDirection ? 0 - this.state.order : this.state.order; if (fieldName !== this.state.sortKey || toggleDirection) { this.setSorting(fieldName, direction); this.isStale = true; ...
javascript
{ "resource": "" }
q49137
train
function(fieldName) { return _.has(this.filterableFields, fieldName) && !_.isUndefined(this.filterableFields[fieldName].displayName); }
javascript
{ "resource": "" }
q49138
train
function(fieldName) { return _.has(this.filterableFields, fieldName) && !_.isNull(this.filterableFields[fieldName].value); }
javascript
{ "resource": "" }
q49139
train
function(filterFieldName) { var val = this.getActiveFilterFields(true)[filterFieldName]; return (_.isNull(val) || _.isUndefined(val)) ? null : val; }
javascript
{ "resource": "" }
q49140
train
function(fieldName, value) { var queryStringValue; if (!this.hasRegisteredFilterField(fieldName)) { this.registerFilterableField(fieldName, ''); } this.filterableFields[fieldName].value = value; if (_.isArray(value)) { ...
javascript
{ "resource": "" }
q49141
writeOptimizedImages
train
function writeOptimizedImages(imageData) { return Promise.all( imageData.map(item => pify(fs.writeFile)(item.path, item.data).then(() => item.path) ) ); }
javascript
{ "resource": "" }
q49142
createSizeSuffix
train
function createSizeSuffix(width, height) { let result = String(width); if (height !== undefined) result += `x${String(height)}`; return result; }
javascript
{ "resource": "" }
q49143
getCropper
train
function getCropper(name) { // See http://sharp.dimens.io/en/stable/api-resize/#crop // // Possible attributes of sharp.gravity are north, northeast, east, southeast, south, // southwest, west, northwest, center and centre. if (sharp.gravity[name] !== undefined) { return sharp.gravity[name]; } // The ...
javascript
{ "resource": "" }
q49144
generateSizes
train
function generateSizes(entry, inputDirectory, outputDirectory) { const imageFileName = path.join(inputDirectory, entry.basename); return pify(fs.readFile)(imageFileName).then(imageBuffer => { const sharpFile = sharp(imageBuffer); return Promise.all( entry.sizes.map(size => { const sizeSuffix =...
javascript
{ "resource": "" }
q49145
clearPriorOutput
train
function clearPriorOutput(directory, sourceImageBasename) { const ext = path.extname(sourceImageBasename); const extlessBasename = path.basename(sourceImageBasename, ext); return del(path.join(directory, `${extlessBasename}*.*`)); }
javascript
{ "resource": "" }
q49146
install
train
function install(deps, options, exec) { options = options || {}; const dev = options.dev !== false; const run = options.yarn || isUsingYarn() ? runYarn : runNpm; // options.versions is a min versions mapping, // the list of packages to install will be taken from deps let versions = options.versions || {}; if (_...
javascript
{ "resource": "" }
q49147
runNpm
train
function runNpm(deps, options, exec) { options = options || {}; exec = exec || spawnSync; const args = [ options.remove ? 'uninstall' : 'install', options.dev ? '--save-dev' : '--save', ].concat(deps); return exec('npm', args, { stdio: options.stdio === undefined ? 'inherit' : options.stdio, cwd: options...
javascript
{ "resource": "" }
q49148
runYarn
train
function runYarn(deps, options, exec) { options = options || {}; exec = exec || spawnSync; const add = options.dev ? ['add', '--dev'] : ['add']; const remove = ['remove']; const args = (options.remove ? remove : add).concat(deps); return exec('yarn', args, { stdio: options.stdio === undefined ? 'inherit' : op...
javascript
{ "resource": "" }
q49149
getUnsatisfiedDeps
train
function getUnsatisfiedDeps(deps, versions, options) { const ownDependencies = getOwnDependencies(options); return deps.filter(dep => { const required = versions[dep]; if (required && !semver.validRange(required)) { throw new MrmError( `Invalid npm version: ${required}. Use proper semver range syntax.` ...
javascript
{ "resource": "" }
q49150
getStyleForFile
train
function getStyleForFile(filepath) { const editorconfigFile = findEditorConfig(filepath); if (editorconfigFile) { return editorconfig.parseFromFilesSync(filepath, [ { name: editorconfigFile, contents: readFile(editorconfigFile) }, ]); } return {}; }
javascript
{ "resource": "" }
q49151
format
train
function format(source, style) { if (style.insert_final_newline !== undefined) { const has = hasTrailingNewLine(source); if (style.insert_final_newline && !has) { source += '\n'; } else if (!style.insert_final_newline && has) { source = source.replace(TRAILING_NEW_LINE_REGEXP, ''); } } return source; ...
javascript
{ "resource": "" }
q49152
updateFile
train
function updateFile(filename, content, exists) { fs.mkdirpSync(path.dirname(filename)); fs.writeFileSync(filename, content); log.added(`${exists ? 'Update' : 'Create'} ${filename}`); }
javascript
{ "resource": "" }
q49153
copyFiles
train
function copyFiles(sourceDir, files, options = {}) { const { overwrite = true, errorOnExist } = options; _.castArray(files).forEach(file => { const sourcePath = path.resolve(sourceDir, file); if (!fs.existsSync(sourcePath)) { throw new MrmError(`copyFiles: source file not found: ${sourcePath}`); } const ...
javascript
{ "resource": "" }
q49154
deleteFiles
train
function deleteFiles(files) { _.castArray(files).forEach(file => { if (!fs.existsSync(file)) { return; } log.removed(`Delete ${file}`); fs.removeSync(file); }); }
javascript
{ "resource": "" }
q49155
withRetries
train
async function withRetries(opts, fn) { const maxRetries = opts.maxRetries || 7 const verbose = opts.verbose || false let tryCount = 0 while (tryCount < maxRetries) { try { return await fn() // Do our action. } catch (e) { // Double wait time each failure let waitTime = 1000 * 2**(tryC...
javascript
{ "resource": "" }
q49156
runApp
train
function runApp(config) { const app = express() const token = new Token(config) // Configure rate limiting. Allow at most 1 request per IP every 60 sec. const opts = { points: 1, // Point budget. duration: 60, // Reset points consumption every 60 sec. } const rateLimiter = new RateLimiterMemory(o...
javascript
{ "resource": "" }
q49157
liveTracking
train
async function liveTracking(config) { setupOriginJS(config) const context = await new Context(config).init() let lastLogBlock = getLastBlock(config) let lastCheckedBlock = 0 const checkIntervalSeconds = 5 let start const check = async () => { await withRetrys(async () => { start = new Date() ...
javascript
{ "resource": "" }
q49158
runBatch
train
async function runBatch(opts, context) { const fromBlock = opts.fromBlock const toBlock = opts.toBlock let lastLogBlock = undefined console.log( 'Looking for logs from block ' + fromBlock + ' to ' + (toBlock || 'Latest') ) const eventTopics = Object.keys(context.signatureToRules) const logs = await ...
javascript
{ "resource": "" }
q49159
withRetrys
train
async function withRetrys(fn) { let tryCount = 0 while (true) { try { return await fn() // Do our action. } catch (e) { // Roughly double wait time each failure let waitTime = Math.pow(100, 1 + tryCount / 6) // Randomly jiggle wait time by 20% either way. No thundering herd. wa...
javascript
{ "resource": "" }
q49160
handleLog
train
async function handleLog(log, rule, contractVersion, context) { log.decoded = web3.eth.abi.decodeLog( rule.eventAbi.inputs, log.data, log.topics.slice(1) ) log.contractName = contractVersion.contractName log.eventName = rule.eventName log.contractVersionKey = contractVersion.versionKey log.netwo...
javascript
{ "resource": "" }
q49161
relatedUserResolver
train
function relatedUserResolver(walletAddress, info){ const requestedFields = info.fieldNodes[0].selectionSet.selections const isIdOnly = requestedFields.filter(x => x.name.value !== 'walletAddress') .length === 0 if (isIdOnly) { return { walletAddress: walletAddress } } else { return search.User.get(w...
javascript
{ "resource": "" }
q49162
Mapper
train
function Mapper(mapper, flusher) { Transform.call(this, { objectMode: true, // Patch from 0.11.7 // https://github.com/joyent/node/commit/ba72570eae938957d10494be28eac28ed75d256f highWaterMark: 16 }) this.mapper = mapper this.flusher = flusher }
javascript
{ "resource": "" }
q49163
assert_length
train
function assert_length(buf, name, length) { if(buf.length !== length) throw new Error('expected '+name+' to have length' + length + ', but was:'+buf.length) }
javascript
{ "resource": "" }
q49164
Source
train
function Source(id, callback) { var uri = url.parse(id); if (!uri || (uri.protocol && uri.protocol !== 'overlaydata:')) { return callback('Only the overlaydata protocol is supported'); } var data = id.replace('overlaydata://', ''); var retina = false; var legacy = false; if (data....
javascript
{ "resource": "" }
q49165
numberWithCommas
train
function numberWithCommas(n) { const parts = n.toString().split('.'); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ','); return parts.join('.'); }
javascript
{ "resource": "" }
q49166
timeout
train
function timeout (time, options) { var opts = options || {} var delay = typeof time === 'string' ? ms(time) : Number(time || 5000) var respond = opts.respond === undefined || opts.respond === true return function (req, res, next) { var id = setTimeout(function () { req.timedout = true ...
javascript
{ "resource": "" }
q49167
_initialiseFromFields
train
function _initialiseFromFields(userFields) { if (util.isDefined(userFields.MType)) { var MTypeNo; if (util.isNumber(userFields.MType)) { MTypeNo = userFields.MType; } else if (util.isString(userFields.MType)) { var mhdr_idx = constants.MTYPE_DE...
javascript
{ "resource": "" }
q49168
ClientSSLSecurity
train
function ClientSSLSecurity(key, cert, ca, defaults) { if (key) { if(Buffer.isBuffer(key)) { this.key = key; } else if (typeof key === 'string') { this.key = fs.readFileSync(key); } else { throw new Error('key should be a buffer or a string!'); } } if (cert) { if(Buffer.isBuf...
javascript
{ "resource": "" }
q49169
ClientSSLSecurityPFX
train
function ClientSSLSecurityPFX(pfx, passphrase, defaults) { if (typeof passphrase === 'object') { defaults = passphrase; } if (pfx) { if (Buffer.isBuffer(pfx)) { this.pfx = pfx; } else if (typeof pfx === 'string') { this.pfx = fs.readFileSync(pfx); } else { throw new Error('suppli...
javascript
{ "resource": "" }
q49170
svg
train
function svg(name, attrs, children) { var elem = document.createElementNS(SVG_NS, name); for(var attrName in attrs) { elem.setAttribute(attrName, attrs[attrName]); } if(children) { children.forEach(function(c) { elem.appendChild(c); }); } return ele...
javascript
{ "resource": "" }
q49171
getDialCoords
train
function getDialCoords(radius, startAngle, endAngle) { var cx = GaugeDefaults.centerX, cy = GaugeDefaults.centerY; return { end: getCartesian(cx, cy, radius, endAngle), start: getCartesian(cx, cy, radius, startAngle) }; }
javascript
{ "resource": "" }
q49172
multibase
train
function multibase (nameOrCode, buf) { if (!buf) { throw new Error('requires an encoded buffer') } const base = getBase(nameOrCode) const codeBuf = Buffer.from(base.code) const name = base.name validEncode(name, buf) return Buffer.concat([codeBuf, buf]) }
javascript
{ "resource": "" }
q49173
encode
train
function encode (nameOrCode, buf) { const base = getBase(nameOrCode) const name = base.name return multibase(name, Buffer.from(base.encode(buf))) }
javascript
{ "resource": "" }
q49174
decode
train
function decode (bufOrString) { if (Buffer.isBuffer(bufOrString)) { bufOrString = bufOrString.toString() } const code = bufOrString.substring(0, 1) bufOrString = bufOrString.substring(1, bufOrString.length) if (typeof bufOrString === 'string') { bufOrString = Buffer.from(bufOrString) } const ba...
javascript
{ "resource": "" }
q49175
isEncoded
train
function isEncoded (bufOrString) { if (Buffer.isBuffer(bufOrString)) { bufOrString = bufOrString.toString() } // Ensure bufOrString is a string if (Object.prototype.toString.call(bufOrString) !== '[object String]') { return false } const code = bufOrString.substring(0, 1) try { const base = ...
javascript
{ "resource": "" }
q49176
queryParamsState
train
function queryParamsState(queryParamsArray, controller) { return queryParamsArray.reduce( (state, qp) => { let value = qp.value(controller); state[qp.key] = { value, serializedValue: qp.serializedValue(controller), as: qp.as, defaultValue: qp.defaultValue, chan...
javascript
{ "resource": "" }
q49177
Account
train
function Account (client, opts) { var self = this if (!(self instanceof Account)) return new Account(client, opts) if (!opts) opts = {} self.client = client }
javascript
{ "resource": "" }
q49178
SKBlob
train
function SKBlob (data) { var self = this if (!(self instanceof SKBlob)) return new SKBlob(data) if (!(data instanceof Buffer)) { data = new Buffer(data) } self._data = data self._type = fileType(data) self._isImage = BufferUtils.isImage(data) self._isMPEG4 = BufferUtils.isMPEG4(data) self._isVi...
javascript
{ "resource": "" }
q49179
Friends
train
function Friends (client, opts) { var self = this if (!(self instanceof Friends)) return new Friends(client, opts) if (!opts) opts = {} self.client = client }
javascript
{ "resource": "" }
q49180
Snaps
train
function Snaps (client, opts) { var self = this if (!(self instanceof Snaps)) return new Snaps(client, opts) if (!opts) opts = {} self.client = client }
javascript
{ "resource": "" }
q49181
Stories
train
function Stories (client, opts) { var self = this if (!(self instanceof Stories)) return new Stories(client, opts) if (!opts) opts = {} self.client = client }
javascript
{ "resource": "" }
q49182
SKLocation
train
function SKLocation (params) { var self = this if (!(self instanceof SKLocation)) return new SKLocation(params) self.weather = params['weather'] self.ourStoryAuths = params['our_story_auths'] self.preCacheGeofilters = params['pre_cache_geofilters'] self.filters = params['filters'].map(function (filter) { ...
javascript
{ "resource": "" }
q49183
Request
train
function Request (opts) { var self = this if (!(self instanceof Request)) return new Request(opts) if (!opts) opts = {} self.HTTPMethod = opts.method self.HTTPHeaders = {} self.opts = opts if (opts.method === 'POST') { if (opts.endpoint) { self._initPOST(opts) } else if (opts.url) { ...
javascript
{ "resource": "" }
q49184
train
function(q) { // Prepare var promises = [], loading = 0, values = []; // Create a new promise to handle all requests return pinkyswear(function(pinky) { // Basic request method var method_index = -1, ...
javascript
{ "resource": "" }
q49185
train
function(method) { return function(url, data, options, before) { var index = ++method_index; ++loading; promises.push(qwest(method, pinky.base + url, data, options, before).then(function(xhr, response) { ...
javascript
{ "resource": "" }
q49186
getTemplates
train
function getTemplates(config) { var templates = {}; Object.keys(templatePaths).forEach(function(key) { if (config.templates && (config.templates[key] && config.templates[key] !== true)) { templates[key] = config.templates[key]; } else { templates[key] = fs.readFileSync(__dirname + temp...
javascript
{ "resource": "" }
q49187
transformData
train
function transformData(data, config, done) { data.baseSize = config.baseSize; data.svgPath = config.svgPath.replace("%f", config.svg.sprite); data.pngPath = config.pngPath.replace("%f", config.svg.sprite.replace(/\.svg$/, ".png")); data.svg = data.svg.map(function(item) { item.relHeight = item.height ...
javascript
{ "resource": "" }
q49188
run
train
function run() { var bin = path.resolve(__dirname, '../node_modules/.bin/mocha'); var args = Array.prototype.slice.call(arguments); var fn = args.pop(); var cmd = [bin].concat(args).join(' ') + ' --no-colors'; exec(cmd, fn); }
javascript
{ "resource": "" }
q49189
assertSubstrings
train
function assertSubstrings(str, substrings) { substrings.forEach(function(substring) { assert(str.indexOf(substring) !== -1, str + ' - string does not contain: ' + substring); }); }
javascript
{ "resource": "" }
q49190
patchHooks
train
function patchHooks(hooks) { var original = {}; var restore; hookTypes.map(function(key) { original[key] = global[key]; global[key] = function(title, fn) { // Hooks accept an optional title, though they're // ignored here for simplicity if (!fn) fn = title; hooks[key] = createWra...
javascript
{ "resource": "" }
q49191
createWrapper
train
function createWrapper(fn, ctx) { return function() { return new Promise(function(resolve, reject) { var start = Date.now(); var cb = function(err) { if (err) return reject(err); resolve(Date.now() - start); }; // Wrap generator functions if (fn && fn.constructor.na...
javascript
{ "resource": "" }
q49192
patchUncaught
train
function patchUncaught() { var name = 'uncaughtException'; var originalListener = process.listeners(name).pop(); if (originalListener) { process.removeListener(name, originalListener); } return function() { if (!originalListener) return; process.on(name, originalListener); }; }
javascript
{ "resource": "" }
q49193
_done
train
function _done (cb, message) { var valid = false if (typeof message === 'string') { message = [message] } else if (Object.prototype.toString.call(message) === '[object Array]') { if (message.length === 0) { valid = true } } else { valid = true } if (isFunction(cb)) { if (valid) {...
javascript
{ "resource": "" }
q49194
_customDefinitions
train
function _customDefinitions (type, object) { var errors if (isFunction(definitions[type])) { try { errors = definitions[type](object) } catch (e) { errors = ['Problem with custom definition for '+type+': '+e] } if (typeof result === 'string') { errors = [errors] } if (Obje...
javascript
{ "resource": "" }
q49195
explode
train
function explode (field) { switch (field.type) { case 'structure': field.fields = field.fields.map(explode) break case 'alternation': field.select = explode(field.select) field.choose.forEach(function (option) { option.read.field = explode(option.read.field) ...
javascript
{ "resource": "" }
q49196
validStyles
train
function validStyles(styleAttr) { var result = ''; var styleArray = styleAttr.split(';'); angular.forEach(styleArray, function (value) { var v = value.split(':'); if (v.length === 2) { var key = trim(v[0].toLowerCase()); value = trim(v[1].toLowerCase());...
javascript
{ "resource": "" }
q49197
validCustomTag
train
function validCustomTag(tag, attrs, lkey, value) { // catch the div placeholder for the iframe replacement if (tag === 'img' && attrs['ta-insert-video']) { if (lkey === 'ta-insert-video' || lkey === 'allowfullscreen' || lkey === 'frameborder' || (lkey === 'contenteditble' && value === 'false')) { ...
javascript
{ "resource": "" }
q49198
buildTree
train
function buildTree(memo, data) { if (data.level === memo.level) { memo.pointer.tree.push(data); } else if (data.level > memo.level) { var up = memo.pointer; memo.pointer = memo.pointer.tree[ memo.pointer.tree.length - 1]; memo.pointer.t...
javascript
{ "resource": "" }
q49199
resolveEntityOrId
train
function resolveEntityOrId(entityOrId, entities, schema) { const key = schema.key; let entity = entityOrId; let id = entityOrId; if (isObject(entityOrId)) { const mutableEntity = isImmutable(entity) ? entity.toJS() : entity; id = schema.getId(mutableEntity) || getIn(entity, ['id']); } else { ent...
javascript
{ "resource": "" }