_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q5100
ensureArray
train
function ensureArray(object, key) { if (!object[key]) { object[key] = []; } if (!Array.isArray(object[key])) { throw new Error("Can't perform array operation on non-array field"); } }
javascript
{ "resource": "" }
q5101
registerHook
train
function registerHook(className, hookType, hookFn) { if (!hooks[className]) { hooks[className] = {}; } hooks[className][hookType] = hookFn; }
javascript
{ "resource": "" }
q5102
getHook
train
function getHook(className, hookType) { if (hooks[className] && hooks[className][hookType]) { return hooks[className][hookType]; } return undefined; }
javascript
{ "resource": "" }
q5103
extractOps
train
function extractOps(data) { const ops = {}; _.forIn(data, (attribute, key) => { if (isOp(attribute)) { ops[key] = attribute; delete data[key]; } }); return ops; }
javascript
{ "resource": "" }
q5104
applyOps
train
function applyOps(data, ops, className) { debugPrint('OPS', ops); _.forIn(ops, (value, key) => { const operator = value.__op; if (operator in UPDATE_OPERATORS) { UPDATE_OPERATORS[operator](data, key, value, className); } else { throw new Error(`Unknown update operator: ${key}`); } ...
javascript
{ "resource": "" }
q5105
queryFilter
train
function queryFilter(where) { if (where.$or) { return object => _.reduce(where.$or, (result, subclause) => result || queryFilter(subclause)(object), false); } // Go through each key in where clause return object => _.reduce(where, (result, whereParams, key) => { const match = evaluateObje...
javascript
{ "resource": "" }
q5106
fetchObjectByPointer
train
function fetchObjectByPointer(pointer) { const collection = getCollection(pointer.className); const storedItem = collection[pointer.objectId]; if (storedItem === undefined) { return undefined; } return Object.assign( { __type: 'Object', className: pointer.className }, _.cloneDeep(storedItem) )...
javascript
{ "resource": "" }
q5107
includePaths
train
function includePaths(object, pathsRemaining) { debugPrint('INCLUDE', { object, pathsRemaining }); const path = pathsRemaining.shift(); const target = object && object[path]; if (target) { if (Array.isArray(target)) { object[path] = target.map(pointer => { const fetched = fetchObjectByPointer...
javascript
{ "resource": "" }
q5108
sortQueryresults
train
function sortQueryresults(matches, order) { const orderArray = order.split(',').map(k => { let dir = 'asc'; let key = k; if (k.charAt(0) === '-') { key = k.substring(1); dir = 'desc'; } return [item => deserializeQueryParam(item[key]), dir]; }); const keys = orderArray.map(_.fir...
javascript
{ "resource": "" }
q5109
runHook
train
function runHook(className, hookType, data) { let hook = getHook(className, hookType); if (hook) { const hydrate = (rawData) => { const modelData = Object.assign({}, rawData, { className }); const modelJSON = _.mapValues(modelData, // Convert dates into JSON loadable representations ...
javascript
{ "resource": "" }
q5110
compareWebhooks
train
function compareWebhooks(webhook, name, targetUrl, resource, event, filter, secret) { if ((webhook.name !== name) || (webhook.targetUrl !== targetUrl) || (webhook.resource !== resource) || (webhook.event !== event)) { return false; } // they look pretty identifty, let's check optional fields if (filter) { i...
javascript
{ "resource": "" }
q5111
HTTPError
train
function HTTPError(statusCode, data) { Error.call(this); Error.captureStackTrace(this, this.constructor); /** * Human-readable error name. * * @type {String} */ this.name = http.STATUS_CODES[statusCode]; /** * HTTP status code. * * @type {Number} */ this.statusCode = statusCode; ...
javascript
{ "resource": "" }
q5112
train
function (config) { return _.map(config.features, function(featureDef) { var feature = null , featurePath = null; var featureId = featureDef.$featureId || featureDef.feature; // Try to require the feature from each path listed in `config.featurePaths`. for (var i = 0; i < config.fe...
javascript
{ "resource": "" }
q5113
randomHexString
train
function randomHexString(size) { if (size === 0) { throw new Error('Zero-length randomHexString is useless.'); } if (size % 2 !== 0) { throw new Error('randomHexString size must be divisible by 2.'); } return crypto.randomBytes(size / 2).toString('hex'); }
javascript
{ "resource": "" }
q5114
train
function () { var defaultMinLength = 2, config = {}; if(!this.props.bloodhound) this.props.bloodhound = {}; if(!this.props.typeahead) this.props.typeahead = {}; if(!this.props.datasource) this.props.datasource = {}; var defaults = { bloodhound: { ...
javascript
{ "resource": "" }
q5115
train
function () { var self = this, options = this.initOptions(); var remoteCall = new Bloodhound(options.bloodhound); options.datasource.source = remoteCall; var typeaheadInput = React.findDOMNode(self); if(typeaheadInput) this.typeahead = $(typeaheadInput).type...
javascript
{ "resource": "" }
q5116
readFileOrError
train
function readFileOrError(uri) { var content; try { content = fs.readFileSync(uri, 'utf8'); } catch (err) { return Result.Err(err); } return Result.Ok(content); }
javascript
{ "resource": "" }
q5117
DocumentGraph
train
function DocumentGraph(options) { this.options = object.extend(defaultOptions, options || {}); this._gloss = new Glossary(); // Parse redis cluster configuration in the form of: // "host:port,host:port,host:port" if (this.options.redisCluster) { var addresses = this.options.redisCluster...
javascript
{ "resource": "" }
q5118
train
function(err, results) { if (err) { callback(err); return; } var keyFrequency = parseInt(results[0]); var docFrequency = parseInt(results[1]); var keyDocFrequency = results[2]; // ensure that key frequency is relative to the given documen...
javascript
{ "resource": "" }
q5119
onError
train
function onError(e) { if (!inBrowser) { return {}; } let response = {}; if (e.response) { response = e.response.data; } throw Object.assign({ statusCode: 500, message: 'Request error' }, response); }
javascript
{ "resource": "" }
q5120
train
function(config) { var app = null; try { app = module.exports.createApp(config); } catch (err) { // wrap also synchronous error to promise to have consistent API for catching all errors return Promise.reject(err); } return module.exports.startApp(app); }
javascript
{ "resource": "" }
q5121
train
function(app) { var config = app.config; var testing = config.profile === 'testing'; var starterPromise = startServer(app).then(logStartup); if (!testing) { starterPromise = starterPromise.catch(logError); } return starterPromise; }
javascript
{ "resource": "" }
q5122
recover
train
function recover(rawTx, v, r, s) { const rawTransaction = typeof(rawTx) === 'string' ? new Buffer(stripHexPrefix(rawTx), 'hex') : rawTx; const signedTransaction = rlp.decode(rawTransaction); const raw = []; transactionFields.forEach((fieldInfo, fieldIndex) => { raw[fieldIndex] = signedTransaction[fieldInde...
javascript
{ "resource": "" }
q5123
sign
train
function sign(transaction, privateKey, toObject) { if (typeof transaction !== 'object' || transaction === null) { throw new Error(`[ethjs-signer] transaction input must be a type 'object', got '${typeof(transaction)}'`); } if (typeof privateKey !== 'string') { throw new Error('[ethjs-signer] private key input must ...
javascript
{ "resource": "" }
q5124
insertCollection
train
function insertCollection(modelName, data, db, callback) { callback = callback || {}; //Counters for managing callbacks var tasks = { total: 0, done: 0 }; //Load model var Model = db.model(modelName); //Clear existing collection Model.collection.remove(function(err) { ...
javascript
{ "resource": "" }
q5125
loadObject
train
function loadObject(data, db, callback) { callback = callback || function() {}; var iterator = function(modelName, next){ insertCollection(modelName, data[modelName], db, next); }; async.forEachSeries(Object.keys(data), iterator, callback); }
javascript
{ "resource": "" }
q5126
loadFile
train
function loadFile(file, db, callback) { callback = callback || function() {}; if (file.substr(0, 1) !== '/') { var parentPath = module.parent.filename.split('/'); parentPath.pop(); file = parentPath.join('/') + '/' + file; } load(require(file), db, callback); }
javascript
{ "resource": "" }
q5127
loadDir
train
function loadDir(dir, db, callback) { callback = callback || function() {}; //Get the absolute dir path if a relative path was given if (dir.substr(0, 1) !== '/') { var parentPath = module.parent.filename.split('/'); parentPath.pop(); dir = parentPath.join('/') + '/' + dir; ...
javascript
{ "resource": "" }
q5128
tagElmRelease
train
async function tagElmRelease(config, context) { function exec(command) { context.logger.log(`Running: ${command}`); execSync(command); } const elmPackageJson = JSON.parse(fs.readFileSync('elm.json')); await tag(elmPackageJson.version); const repositoryUrl = await getGitAuthUrl(config); await push(r...
javascript
{ "resource": "" }
q5129
Entry
train
function Entry (content, name, parent) { if (!(this instanceof Entry)) return new Entry(content, name, parent); this._parent = parent; // parent can be a Document or ArrayField this._schema = parent._schema; // the root Document this._name = name; // the field name supplied by the user this._hidden = isHidde...
javascript
{ "resource": "" }
q5130
remove
train
function remove (state, prefix, objectsOrIds, change) { if (Array.isArray(objectsOrIds)) { return Promise.all(objectsOrIds.map(markAsDeleted.bind(null, state, change))) .then(function (docs) { return updateMany(state, docs, null, prefix) }) } return markAsDeleted(state, change, objectsOrIds) ...
javascript
{ "resource": "" }
q5131
Field
train
function Field (field, name, parent) { if (!(this instanceof Field)) return new Field(field, name, parent); debug('field <%s> being built from <%s>', name, field); Entry.call(this, field, name, parent); this._context = parent._context; this._this = parent._this; if (typeof this._content !== 'string') { ...
javascript
{ "resource": "" }
q5132
train
function(results) { var globalScoreSum = 0; var globalScoreCount = 0; var rulesScoresSum = {}; var rulesScoresCount = {}; var rulesValuesSum = {}; var rulesValuesCount = {}; results.forEach(function(result) { // Global score globalScoreSum += result.scoreProfiles....
javascript
{ "resource": "" }
q5133
train
function(phrasesArray) { var deferred = Q.defer(); if (phrasesArray === undefined) { phrasesArray = []; } // Default conditionsObject var conditionsObject = { atLeastOneUrl: { ruleScores: [], ruleValues: [], ignoredRules: [] } }; ...
javascript
{ "resource": "" }
q5134
train
function(bucket, key, cb){ contract(arguments) .params('string', 'string|number', 'function') .end() ; var table = ''; if (bucket.indexOf('allows') != -1) { table = this.prefix + this.buckets.permissions; this.db .select('key', 'value') .from(table) .where({'key': bucket}) .then(f...
javascript
{ "resource": "" }
q5135
train
function(bucket, keys, cb){ contract(arguments) .params('string', 'array', 'function') .end() ; var table = ''; if (bucket.indexOf('allows') != -1) { table = this.prefix + this.buckets.permissions; this.db .select('key', 'value') .from(table) .where({'key': bucket}) .then(function...
javascript
{ "resource": "" }
q5136
train
function(transaction, bucket, key, values){ contract(arguments) .params('array', 'string', 'string|number','string|array|number') .end() ; var self = this; var table = ''; values = Array.isArray(values) ? values : [values]; // we always want to have an array for values transaction.push(function(...
javascript
{ "resource": "" }
q5137
train
function(transaction, bucket, key, values){ contract(arguments) .params('array', 'string', 'string|number','string|array') .end() ; var self = this; var table = ''; values = Array.isArray(values) ? values : [values]; // we always want to have an array for values transaction.push(function(cb){ ...
javascript
{ "resource": "" }
q5138
findAll
train
function findAll (state, prefix, filter) { var options = { include_docs: true } if (prefix) { options.startkey = prefix options.endkey = prefix + '\uffff' } return state.db.allDocs(options) .then(function (res) { var objects = res.rows .filter(isntDesignDoc) .map(function (row...
javascript
{ "resource": "" }
q5139
getRefSchema
train
function getRefSchema (refVal, refType, parent, options, state) { const loader = getLoader(refType, options) if (refType && loader) { let newVal let oldBasePath let loaderValue let filePath let fullRefFilePath if (refType === 'file') { filePath = utils.getRefFilePath(refVal) ful...
javascript
{ "resource": "" }
q5140
addToHistory
train
function addToHistory (state, type, value) { let dest if (type === 'file') { dest = utils.getRefFilePath(value) } else { if (value === '#') { return false } dest = state.current.concat(`:${value}`) } if (dest) { dest = dest.toLowerCase() if (state.history.indexOf(dest) >= 0) { ...
javascript
{ "resource": "" }
q5141
setCurrent
train
function setCurrent (state, type, value) { let dest if (type === 'file') { dest = utils.getRefFilePath(value) } if (dest) { state.current = dest } }
javascript
{ "resource": "" }
q5142
checkLocalCircular
train
function checkLocalCircular (schema) { const dag = new DAG() const locals = traverse(schema).reduce(function (acc, node) { if (!_.isNull(node) && !_.isUndefined(null) && typeof node.$ref === 'string') { const refType = utils.getRefType(node) if (refType === 'local') { const value = utils.get...
javascript
{ "resource": "" }
q5143
MyLdapAuth
train
function MyLdapAuth(opts) { this.opts = opts; assert.ok(opts.url); assert.ok(opts.searchBase); assert.ok(opts.searchFilter); // optional option: tls_ca this.log = opts.log4js && opts.log4js.getLogger('ldapauth'); var clientOpts = {url: opts.url}; if (opts.log4js && opts.verbose) { clientOpts.log4...
javascript
{ "resource": "" }
q5144
push
train
function push (state, docsOrIds) { var pushedObjects = [] var errors = state.db.constructor.Errors return Promise.resolve(state.remote) .then(function (remote) { return new Promise(function (resolve, reject) { if (Array.isArray(docsOrIds)) { docsOrIds = docsOrIds.map(toId) } else { ...
javascript
{ "resource": "" }
q5145
withIdPrefix
train
function withIdPrefix (state, prefix) { var emitter = new EventEmitter() var api = { add: require('./add').bind(null, state, prefix), find: require('./find').bind(null, state, prefix), findAll: require('./find-all').bind(null, state, prefix), findOrAdd: require('./find-or-add').bind(null, state, pr...
javascript
{ "resource": "" }
q5146
getRefValue
train
function getRefValue (ref) { const thing = ref ? (ref.value ? ref.value : ref) : null if (thing && thing.$ref && typeof thing.$ref === 'string') { return thing.$ref } }
javascript
{ "resource": "" }
q5147
getRefPathValue
train
function getRefPathValue (schema, refPath) { let rpath = refPath const hashIndex = refPath.indexOf('#') if (hashIndex >= 0) { rpath = refPath.substring(hashIndex) if (rpath.length > 1) { rpath = refPath.substring(1) } else { rpath = '' } } // Walk through each /-separated path com...
javascript
{ "resource": "" }
q5148
pruneModules
train
function pruneModules(bundle, doneBundles, registry, generator) { const {groups} = generator.options; groups.forEach(group => { const bundles = group.map(bundleId => { return doneBundles.find(b => b.id === bundleId); }).filter(Boolean); pruneGroup(bundles); }); }
javascript
{ "resource": "" }
q5149
find
train
function find (state, prefix, objectsOrIds) { return Array.isArray(objectsOrIds) ? findMany(state, objectsOrIds, prefix) : findOne(state, objectsOrIds, prefix) }
javascript
{ "resource": "" }
q5150
getCredentials
train
function getCredentials(gruntOptions) { if (gruntOptions.authKey && grunt.file.exists('.ftpauth')) { return JSON.parse(grunt.file.read('.ftpauth'))[gruntOptions.authKey]; } else if (gruntOptions.username && gruntOptions.password) { return { username: gruntOptions.username, password: gruntOptions.pas...
javascript
{ "resource": "" }
q5151
pushDirectories
train
function pushDirectories(directories, callback) { var index = 0; /** * Recursive helper used as callback for server.raw(mkd) * @param {error} err - Error message if something went wrong */ var processDir = function processDir (err) { // Fail if any error other then 550 is present, 550 is ...
javascript
{ "resource": "" }
q5152
uploadFiles
train
function uploadFiles(files) { var index = 0, file = files[index]; /** * Recursive helper used as callback for server.raw(put) * @param {error} err - Error message if something went wrong */ var processFile = function processFile (err) { if (err) { grunt.log.warn(messages.f...
javascript
{ "resource": "" }
q5153
getLicenseFromUrl
train
function getLicenseFromUrl (url) { var regex = { opensource: /(http(s)?:\/\/)?(www.)?opensource.org\/licenses\/([A-Za-z0-9\-._]+)$/, spdx: /(http(s)?:\/\/)?(www.)?spdx.org\/licenses\/([A-Za-z0-9\-._]+)$/ } for (var re in regex) { var tokens = url.match(regex[re]) if (tokens) { var license ...
javascript
{ "resource": "" }
q5154
prepareElmRelease
train
async function prepareElmRelease(config, context) { function exec(command) { context.logger.log(`Running: ${command}`); execSync(command, { shell: '/bin/bash' }); } exec(`yarn elm diff`); exec(`yes | yarn elm bump`); }
javascript
{ "resource": "" }
q5155
update
train
function update (state, prefix, objectsOrIds, change) { if (typeof objectsOrIds !== 'object' && !change) { return Promise.reject( new Error('Must provide change') ) } return Array.isArray(objectsOrIds) ? updateMany(state, objectsOrIds, change, prefix) : updateOne(state, objectsOrIds, change...
javascript
{ "resource": "" }
q5156
getColourAt
train
function getColourAt(gradient, p) { p = clamp(p, 0, 0.9999); // FIXME let r = Math.floor(p * (gradient.length - 1)); let q = p * (gradient.length - 1) - r; return Colour.mix(gradient[r + 1], gradient[r], q); }
javascript
{ "resource": "" }
q5157
matchLicense
train
function matchLicense (licenseString) { // Find all textual matches on license text. var normalized = normalizeText(licenseString) var matchingLicenses = [] var license // Check matches of normalized license content against signatures. for (var i = 0; i < licenses.length; i++) { license = licenses[i] ...
javascript
{ "resource": "" }
q5158
getJsonLicense
train
function getJsonLicense (json) { var license = 'nomatch' if (typeof json === 'string') { license = matchLicense(json) || 'nomatch' } else { if (json.url) { license = { name: json.type, url: json.url } } else { license = matchLicense(json.type) } } return license }
javascript
{ "resource": "" }
q5159
off
train
function off (state, eventName, handler) { state.emitter.removeListener(eventName, handler) return state.api }
javascript
{ "resource": "" }
q5160
calculateScaledFontSize
train
function calculateScaledFontSize(width, height) { return Math.round(Math.max(12, Math.min(Math.min(width, height) * 0.75, (0.75 * Math.max(width, height)) / 12))); }
javascript
{ "resource": "" }
q5161
updateOrAdd
train
function updateOrAdd (state, prefix, idOrObjectOrArray, newObject) { return Array.isArray(idOrObjectOrArray) ? updateOrAddMany(state, idOrObjectOrArray, prefix) : updateOrAddOne(state, idOrObjectOrArray, newObject, prefix) }
javascript
{ "resource": "" }
q5162
sendFrame
train
function sendFrame(socket, _frame) { var frame = _frame; if (!_frame.hasOwnProperty('toString')) { frame = new Frame({ 'command': _frame.command, 'headers': _frame.headers, 'body': _frame.body }); } socket.send(frame.toStringOrBuffer()); return true; }
javascript
{ "resource": "" }
q5163
parseCommand
train
function parseCommand(data) { var command, str = data.toString('utf8', 0, data.length); command = str.split('\n'); return command[0]; }
javascript
{ "resource": "" }
q5164
updateAll
train
function updateAll (state, prefix, changedProperties) { var type = typeof changedProperties var docs if (type !== 'object' && type !== 'function') { return Promise.reject(new Error('Must provide object or function')) } var options = { include_docs: true } if (prefix) { options.startkey = pr...
javascript
{ "resource": "" }
q5165
add
train
function add (state, prefix, properties) { return Array.isArray(properties) ? addMany(state, properties, prefix) : addOne(state, properties, prefix) }
javascript
{ "resource": "" }
q5166
removeAll
train
function removeAll (state, prefix, filter) { var docs var options = { include_docs: true } if (prefix) { options.startkey = prefix options.endkey = prefix + '\uffff' } return state.db.allDocs(options) .then(function (res) { docs = res.rows .filter(isntDesignDoc) .map(functi...
javascript
{ "resource": "" }
q5167
visitBundle
train
function visitBundle(file) { if (visitedIndexes[file]) { return; } visitedIndexes[file] = true; // walk deps var bundle = manifest.bundles[manifest.indexes[file]]; bundle.data.forEach(function(module) { Object.keys(module.deps).forEach(function(key...
javascript
{ "resource": "" }
q5168
ArrayField
train
function ArrayField (array, name, parent) { if (!(this instanceof ArrayField)) return new ArrayField(array, name, parent); debug('array <%s> being built', name); Entry.call(this, array, name, parent); this._context = parent._context; this._this = parent._this; this._currVal = {}; var data = this._content...
javascript
{ "resource": "" }
q5169
findOrAdd
train
function findOrAdd (state, prefix, idOrObjectOrArray, properties) { return Array.isArray(idOrObjectOrArray) ? findOrAddMany(state, idOrObjectOrArray, prefix) : findOrAddOne(state, idOrObjectOrArray, properties, prefix) }
javascript
{ "resource": "" }
q5170
pull
train
function pull (state, docsOrIds) { var pulledObjects = [] var errors = state.db.constructor.Errors return Promise.resolve(state.remote) .then(function (remote) { return new Promise(function (resolve, reject) { if (Array.isArray(docsOrIds)) { docsOrIds = docsOrIds.map(toId) } else { ...
javascript
{ "resource": "" }
q5171
Schema
train
function Schema (sc, size) { if (!(this instanceof Schema)) return new Schema(sc); debug('======BUILDING PHASE======'); helpers.validate(sc); debug('schema size=%d being built', size); this._schema = this; this._document = helpers.build(sc, '$root', this); this._state = { // serve as global state inde...
javascript
{ "resource": "" }
q5172
reload
train
function reload(moduleName) { var id = require.resolve(moduleName); var mod = require.cache[id]; if (mod) { var base = path.dirname(mod.filename); // expunge each module cache entry beneath this folder var stack = [mod]; while (stack.length) { var mod = st...
javascript
{ "resource": "" }
q5173
extractConnectionInfo
train
function extractConnectionInfo(opts) { var params = {}; var defaultServer = opts.secureCommands ? { hostname: '127.0.0.1', port: 4445 } : { hostname: 'ondemand.saucelabs.com', port: 80 }; params.hostname = opts.hostname || defaultServer.hostname; params.p...
javascript
{ "resource": "" }
q5174
initBrowser
train
function initBrowser(browserOpts, opts, mode, fileGroup, cb) { var funcName = opts.usePromises ? 'promiseChainRemote': 'remote'; var browser = wd[funcName](extractConnectionInfo(opts)); browser.browserTitle = browserOpts.browserTitle; browser.mode = mode; browser.mode = mode; if (opts.testName)...
javascript
{ "resource": "" }
q5175
getLargestCount
train
function getLargestCount(domain, type) { var retVal = 1; for (var i = 0; i < domain.length; i++) { retVal = Math.max(retVal, type === 'cnv' ? domain[i].cnv : domain[i].count); } return retVal; }
javascript
{ "resource": "" }
q5176
mapValues
train
function mapValues (obj, fn) { return Object.keys(obj).reduce(function (res, key) { res[key] = fn(obj[key], key, obj) return res }, {}) }
javascript
{ "resource": "" }
q5177
formatParameters
train
function formatParameters(params) { var sortedKeys = [], formattedParams = '' // sort the properties of the parameters sortedKeys = _.keys(params).sort() // create a string of key value pairs separated by '&' with '=' assignement for (i = 0; i < sortedKeys.length; i++) { if (i ...
javascript
{ "resource": "" }
q5178
Device
train
function Device(options) { EventEmitter.call(this); // Check required fields. if(!options || !options.id) { throw new Error('ID is required.'); } this.options = options; this.id = options.id; // Default the options and remove whitespace. options.id = (options.id || '').replace(/ /g, ''); optio...
javascript
{ "resource": "" }
q5179
setTemplateContext
train
function setTemplateContext(contextArray) { var newTemplateContext = {}; contextArray.forEach(function(item) { var cleanString = item.slice(options.contextBinderMark.length, -options.contextBinderMark.length), separatedPairs = cleanString.split(':'); newTemplateContext[separatedP...
javascript
{ "resource": "" }
q5180
getTemplateContext
train
function getTemplateContext(file) { var sourceFile = grunt.file.read(file), hasTemplateContext = checkTemplateContext(sourceFile), pattern = new RegExp('(' + options.contextBinderMark + ')(.*?)(' + options.contextBinderMark + ')', 'g'), contextArray; if (!hasTemplateContext) { ...
javascript
{ "resource": "" }
q5181
getWorkingPath
train
function getWorkingPath(file) { var completePath = JSON.stringify(file).slice(2,-2).split('/'), lastPathElement = completePath.pop(), fileDirectory = completePath.splice(lastPathElement).join('/'); return fileDirectory; }
javascript
{ "resource": "" }
q5182
getTemplate
train
function getTemplate(workingPath) { var templateFile = grunt.file.expand({}, workingPath + '/*.' + options.autoTemplateFormat); return templateFile[0]; }
javascript
{ "resource": "" }
q5183
DisplayProps
train
function DisplayProps(visible, alpha, shadow, compositeOperation, matrix) { this.setValues(visible, alpha, shadow, compositeOperation, matrix); // public properties: // assigned in the setValues method. /** * Property representing the alpha that will be applied to a display object. * @property alpha * ...
javascript
{ "resource": "" }
q5184
Bitmap
train
function Bitmap(imageOrUri) { this.DisplayObject_constructor(); // public properties: /** * The image to render. This can be an Image, a Canvas, or a Video. Not all browsers (especially * mobile browsers) support drawing video to a canvas. * @property image * @type HTMLImageElement | HTMLCanvasElemen...
javascript
{ "resource": "" }
q5185
train
function( target ) { $.extend( target, Audio.Busses ) $.extend( target, Audio.Oscillators ) $.extend( target, Audio.Synths ) $.extend( target, Audio.Percussion ) $.extend( target, Audio.Envelopes ) $.extend( target, Audio.FX ) $.extend( target, Audio.Seqs ) $.extend( target, A...
javascript
{ "resource": "" }
q5186
train
function(key, initValue, obj) { var isTimeProp = Audio.Clock.timeProperties.indexOf( key ) > -1, prop = obj.properties[ key ] = { value: isTimeProp ? Audio.Clock.time( initValue ) : initValue, binops: [], parent : obj, name : key, }, mappingName = key...
javascript
{ "resource": "" }
q5187
train
function(ugen) { ugen.mod = ugen.polyMod; ugen.removeMod = ugen.removePolyMod; for( var key in ugen.polyProperties ) { (function( _key ) { var value = ugen.polyProperties[ _key ], isTimeProp = Audio.Clock.timeProperties.indexOf( _key ) > -1 Object.defineProperty(ugen,...
javascript
{ "resource": "" }
q5188
train
function( bus, position ) { if( typeof bus === 'undefined' ) bus = Audio.Master if( this.destinations.indexOf( bus ) === -1 ){ bus.addConnection( this, 1, position ) if( position !== 0 ) { this.destinations.push( bus ) } } return this }
javascript
{ "resource": "" }
q5189
findTab
train
function findTab(patternlab, pattern) { //read the filetypes from the configuration const fileTypes = patternlab.config.plugins['plugin-node-tab'].options.tabsToAdd; //exit if either of these two parameters are missing if (!patternlab) { console.error('plugin-node-tab: patternlab object not provided to fi...
javascript
{ "resource": "" }
q5190
VideoLoader
train
function VideoLoader(loadItem, preferXHR) { this.AbstractMediaLoader_constructor(loadItem, preferXHR, createjs.AbstractLoader.VIDEO); if (createjs.RequestUtils.isVideoTag(loadItem) || createjs.RequestUtils.isVideoTag(loadItem.src)) { this.setTag(createjs.RequestUtils.isVideoTag(loadItem)?loadItem:loadItem.src);...
javascript
{ "resource": "" }
q5191
powerSpectrum
train
function powerSpectrum(amplitudes) { var N = amplitudes.length; return amplitudes.map(function (a) { return (a * a) / N; }); }
javascript
{ "resource": "" }
q5192
updateHeader
train
function updateHeader(fileInfo, data, type, headerLineRegex, options) { const contents = fs.readFileSync(fileInfo.path, 'utf8') || '' const body = contents.split('\n') // assumes all comments at top of template are the header block const preheader = [] while (body.length && !body[0].trim().match(headerLineRe...
javascript
{ "resource": "" }
q5193
train
function(){ $('.entry-content').each(function(i){ var _i = i; $(this).find('img').each(function(){ var alt = this.alt; if (alt != ''){ $(this).after('<span class="caption">'+alt+'</span>'); } $(this).wrap('<a href="'+this.src+'" title="'+alt+'" class="fancybox" rel="gallery'+_i+'" />'); ...
javascript
{ "resource": "" }
q5194
init
train
function init(options) { //Prep and extend the options if (options && (options.allowPageScroll === undefined && (options.swipe !== undefined || options.swipeStatus !== undefined))) { options.allowPageScroll = NONE; } //Check for deprecated options //Ensure that any old click handlers are assigned ...
javascript
{ "resource": "" }
q5195
touchStart
train
function touchStart(jqEvent) { //If we already in a touch event (a finger already in use) then ignore subsequent ones.. if( getTouchInProgress() ) return; //Check if this element matches any in the excluded elements selectors, or its parent is excluded, if so, DON'T swipe if( $(jqEvent.target).clos...
javascript
{ "resource": "" }
q5196
touchMove
train
function touchMove(jqEvent) { //As we use Jquery bind for events, we need to target the original event object //If these events are being programmatically triggered, we don't have an original event object, so use the Jq one. var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent; //If w...
javascript
{ "resource": "" }
q5197
touchEnd
train
function touchEnd(jqEvent) { //As we use Jquery bind for events, we need to target the original event object //If these events are being programmatically triggered, we don't have an original event object, so use the Jq one. var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent, touches = e...
javascript
{ "resource": "" }
q5198
touchCancel
train
function touchCancel() { // reset the variables back to default values fingerCount = 0; endTime = 0; startTime = 0; startTouchesDistance=0; endTouchesDistance=0; pinchZoom=1; //If we were in progress of tracking a possible multi touch end, then re set it. cancelMultiFingerRelease(); ...
javascript
{ "resource": "" }
q5199
touchLeave
train
function touchLeave(jqEvent) { var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent; //If we have the trigger on leave property set.... if(options.triggerOnTouchLeave) { phase = getNextPhase( PHASE_END ); triggerHandler(event, phase); } }
javascript
{ "resource": "" }