_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q13500
Schema
train
function Schema(config, data) { const controllers = data.controllers; const length = controllers.length; this.FullyTyped = FullyTyped; // apply controllers to this schema for (let i = 0; i < length; i++) controllers[i].call(this, config); // add additional properties if (config._extension_ && typeof config._extension_ === 'object') { const self = this; Object.keys(config._extension_).forEach(function(key) { self[key] = config._extension_[key]; }); } // store protected data with schema const protect = Object.assign({}, data); // create and store hash const options = getNormalizedSchemaConfiguration(this); protect.hash = crypto .createHash('sha256') .update(JSON.stringify(prepareForHash(options))) .digest('hex'); instances.set(this, protect); /** * @name Schema#config * @type {object} */ Object.defineProperty(this, 'config', { get: function() { return util.copy(config); } }); }
javascript
{ "resource": "" }
q13501
build
train
function build(base, config) { var result = resolver(base); Object.keys(config).forEach(function (key) { var value = config[key]; if (typeof value === "string") { result[key] = resolver(result(value, true)); } else if (Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "object") { result[key] = build(result(value[0], true), value[1]); } else { throw new TypeError("Invalid value at: " + key); } }); return result; }
javascript
{ "resource": "" }
q13502
populateApiFromInterface
train
function populateApiFromInterface(api, iface) { Object.keys(iface).forEach(function (key) { api.add(key, iface[key]); }); }
javascript
{ "resource": "" }
q13503
router
train
function router(rpc, handlers, req, res) { var $ = rpc.$; var api = rpc.api; var request = api.handle(req.method, req.url); var dom = domain.create(); // the request handler doesn't exit // TODO: hoist response logic if (!request) { res.statusCode = 404; res.end(); return; } var context = new Context(); // TODO: hoist to own module var handle = request.handle; var params = {}; // TODO: hoist logic to 'union' module var key; for(key in request.params) params[key] = request.params[key]; for(key in request.query) params[key] = request.query[key]; var future = $.future(); future.setWritable(res); future.setReadable(req); // TODO: extract request making logic res.setHeader('Transfer-Encoding' , 'chunked'); res.setHeader('Content-Type' , 'application/json'); dom.on('error', function (err) { var statusCode = err.statusCode; // only catch known errors, re-throw unexpected errors if (!statusCode) throw err; // TODO: hoist response logic res.statusCode = statusCode; res.write(JSON.stringify(err)); res.end(); }); // domain should handle all route errors dom.run(function () { handlers[handle](future, params, context); }); }
javascript
{ "resource": "" }
q13504
addSimpleMethod
train
function addSimpleMethod(name, msg, failureIsError) { LockdClient.prototype[name] = function(objName, cb) { var self = this; self.transport.request(util.format(msg, objName), 1, function(err, lines) { self._processResponseLine(cb, err, lines && lines[0], failureIsError); }); }; }
javascript
{ "resource": "" }
q13505
runSingleBrowser
train
function runSingleBrowser(location, remote, platform, options) { var capabilities = {}; Object.keys(platform).forEach(function (key) { capabilities[key] = platform[key]; }); var extraCapabilities = typeof options.capabilities === 'function' ? options.capabilities(platform) : (options.capabilities || {}); Object.keys(extraCapabilities).forEach(function (key) { capabilities[key] = extraCapabilities[key]; }); return retry(function (err) { var driver = getDriver(remote, capabilities, { mode: 'async', debug: options.debug, httpDebug: options.httpDebug, }); return driver._session().then(function () { return driver; }); }, 4, function (attempt) { return attempt * attempt * 5000; }, {debug: options.debug}).then(function (driver) { return runDriver(location, driver, { name: options.name, jobInfo: typeof options.jobInfo === 'function' ? options.jobInfo(platform) : options.jobInfo, allowExceptions: options.allowExceptions, testComplete: options.testComplete, testPassed: options.testPassed, timeout: options.timeout, debug: options.debug }).then(function (result) { return result; }); }); }
javascript
{ "resource": "" }
q13506
Cache
train
function Cache (cache, options) { if (arguments.length === 1) { if (cache.hasOwnProperty('normalizeKey') || cache.hasOwnProperty('transform')) { options = cache; cache = {}; } } options = options || {}; this.cache = cache || {}; this.normalizeKey = options.normalizeKey || function (key) { return key; }; this.transform = options.transform || function (value) { return value; }; }
javascript
{ "resource": "" }
q13507
train
function(attrs) { attrs = attrs || {}; attrs.state = attrs.state || {}; // Build our class name var cName = cfgClasses("mdl-button--", ["raised", "fab", "mini-fab", "icon", "colored", "primary", "accent"], attrs.state) + cfgClasses("mdl-js-", ["ripple-effect"], attrs.state); return attrsConfig({ className: "mdl-button mdl-js-button" + cName }, attrs); }
javascript
{ "resource": "" }
q13508
train
function(ctrl, attrs) { attrs = mButton.attrs(attrs); // If there is a href, we assume this is a link button return m(attrs.cfg.href? 'a': 'button', attrExclude(attrs.cfg, ['text']), (attrs.state.fab || attrs.state.icon? m('i', {className: "material-icons"}, attrs.cfg.text): attrs.cfg.text) ); }
javascript
{ "resource": "" }
q13509
train
function(attrs) { attrs = attrs || {}; attrs.state = attrs.state || {}; return attrsConfig({ className: "mdl-js-snackbar mdl-snackbar" }, attrs); }
javascript
{ "resource": "" }
q13510
tlid__xtro
train
function tlid__xtro(str) { var r = new Object(); r.tlid = "-1"; r.src = str; r.txt = ""; // r.deco = ""; if (tlid__has(str)) { r.tlid = tlid__xtr(str); r.txt = str.replace(r.tlid + " ", "") // try to clear out the double space .replace(r.tlid, "") // if ending the string, well we remove it .replace("@tlid ", ""); //remove the decorator } return r; }
javascript
{ "resource": "" }
q13511
train
function (obj, fn) { for (var i in obj) { if (typeof obj[i] === 'object') { obj[i] = parse(obj[i], fn); } else { obj[i] = fn(obj[i], i); } } return obj; }
javascript
{ "resource": "" }
q13512
changeKeys
train
function changeKeys (src, dest) { for (var i in src) { if (typeof src[i] === 'object') { dest[escapedSingleQuotes + i + escapedSingleQuotes] = {}; changeKeys(src[i], dest[escapedSingleQuotes + i + escapedSingleQuotes]); } else { dest[escapedSingleQuotes + i + escapedSingleQuotes] = src[i]; } } return dest; }
javascript
{ "resource": "" }
q13513
errorsMiddleware
train
function errorsMiddleware(req, res, next) { var errors = []; res.addError = function(location, name, description) { if (["body", "header", "url", "querystring"].indexOf(location) === -1) { throw new Error('"' + location + '" is not a valid location. ' + 'Should be one of "header", "body", "url" or ' + '"querystring".'); } errors.push({ location: location, name: name, description: description }); }; res.sendError = function(location, name, description) { if (typeof location !== "undefined") { res.addError(location, name, description); } res.json(400, {status: "errors", errors: errors}); }; res.hasErrors = function() { return errors.length !== 0; }; next(); }
javascript
{ "resource": "" }
q13514
train
function (internalInstance, transaction, updateBatchNumber) { if (internalInstance._updateBatchNumber !== updateBatchNumber) { // The component's enqueued batch number should always be the current // batch or the following one. process.env.NODE_ENV !== 'production' ? warning(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : void 0; return; } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement); } } internalInstance.performUpdateIfNecessary(transaction); if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } }
javascript
{ "resource": "" }
q13515
train
function (publicInstance, completeState, callback) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState'); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; // Future-proof 15.5 if (callback !== undefined && callback !== null) { ReactUpdateQueue.validateCallback(callback, 'replaceState'); if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } } enqueueUpdate(internalInstance); }
javascript
{ "resource": "" }
q13516
cps
train
function cps(fun) { /** * @param {...*} args * @param {Function} callback */ return function () { var args = Array.prototype.slice.call(arguments); var callback = args.pop(); var result; try { result = fun.apply(this, args); } catch (err) { callback(err); return; } callback(null, result); } }
javascript
{ "resource": "" }
q13517
setIceServers
train
function setIceServers() { if(stunServers) { for(var num = 0; num < stunServers.length; num++) { connConfig['iceServers'].push({'urls':'stun:'+stunServers[num]}); } } }
javascript
{ "resource": "" }
q13518
iceCandidateCallback
train
function iceCandidateCallback(e) { if(e.candidate != null) { if(scope.onIceCandidate) { scope.onIceCandidate(scope,JSON.stringify({'ice': e.candidate})); } } }
javascript
{ "resource": "" }
q13519
onStateChange
train
function onStateChange(e) { if(scope._conn) { if(scope._conn.iceConnectionState == "connected") { if(scope.onConnected) { scope.onConnected(scope); } } if(scope._conn.iceConnectionState == "failed" || scope._conn.iceConnectionState == "disconnected") { if(scope.onConnectionFail) { scope.onConnectionFail(scope); } if(scope.type == "offer") { scope.createOffer(); } } if(scope._conn.iceConnectionState == "closed") { if(scope.onClosed) { scope.onClosed(scope); } scope.dispose(); } } }
javascript
{ "resource": "" }
q13520
remoteStreamCallback
train
function remoteStreamCallback(e) { scope.remoteStream = e.stream; if(scope.onRemoteStream) { scope.onRemoteStream(scope.remoteStream); } }
javascript
{ "resource": "" }
q13521
ondatachannel
train
function ondatachannel(e) { if(e) { scope._data = e.channel; } else { scope._data = scope._conn.createDataChannel("data"); } scope._data.onopen = function() { if(scope._data) { if(scope._data.readyState == "open") { if(scope.onChannelState) { scope.onChannelState(scope,'open'); } } } }; scope._data.onmessage = function(e) { if(e.data instanceof ArrayBuffer) { if(scope.onBytesMessage) { scope.onBytesMessage(scope,e.data); } } else { if(scope.onMessage) { var char = Number(e.data[0]); if(char == MessageType.MESSAGE) { scope.onMessage(scope,JSON.parse(e.data.substring(1,e.data.length))); } else { scope.onMessage(scope,e.data); } } } } scope._data.onclose = function(e) { if(scope.onChannelState) { scope.onChannelState(scope,'closed'); } } scope._data.onerror = function(e) { if(scope.onError) { scope.onError(e); } } }
javascript
{ "resource": "" }
q13522
expandSmartyPathAttr
train
function expandSmartyPathAttr(content, tagName, attrName, file) { var attrReg = new RegExp('((?:^|\\s)' + her.util.pregQuote(attrName) + '\\s*=\\s*)(([\"\']).*?\\3)', 'ig'); content = tagFilter.filterTag(content, tagName, smarty_left_delimiter, smarty_right_delimiter, function (outter, attr) { attr = attr.replace(attrReg, function (all, preCodeHolder, valueCodeHolder) { var info = her.util.stringQuote(valueCodeHolder); var path = info.rest; var ret = info.quote + her.uri.getId(path, file.dirname).id + info.quote; return preCodeHolder + ret; }); outter = smarty_left_delimiter + tagName + attr + smarty_right_delimiter; return outter; }); return content; }
javascript
{ "resource": "" }
q13523
deserializeParameter
train
function deserializeParameter(server, name, value, schema) { if (!schema) return value; const type = schemaType(schema); if (!type) server.log('req-params', 'Indeterminate schema type for parameter ' + name, schema); if (type === 'array') { const format = schema.hasOwnProperty('collectionFormat') ? schema.collectionFormat : 'csv'; const delimiter = format === 'csv' ? ',' : format === 'ssv' ? ' ' : format === 'tsv' ? '\t' : format === 'pipes' ? '|' : ','; value = value.split(delimiter); if (!schema.items) return value; return value.map(item => { return deserializeParameter(server, 'items for ' + name, item, schema.items); }); } else if (type === 'boolean') { return !(value === 'false' || value === 'null' || value === '0' || value === ''); } else if (type === 'integer' && rxInteger.test(value)) { return parseInt(value); } else if (type === 'number' && rxNumber.test(value)) { return parseFloat(value); } else { return value; } }
javascript
{ "resource": "" }
q13524
schemaType
train
function schemaType(schema) { let type; if (schema.hasOwnProperty('type')) { type = schema.type; } else if (schema.hasOwnProperty('properties') || schema.hasOwnProperty('allOf') || schema.hasOwnProperty('additionalProperties')) { type = 'object'; } else if (schema.hasOwnProperty('items')) { type = 'array'; } switch (type) { case 'array': case 'boolean': case 'file': case 'integer': case 'number': case 'object': case 'string': return type; } }
javascript
{ "resource": "" }
q13525
ObjectId
train
function ObjectId(bytes) { if (Buffer.isBuffer(bytes)) { if (bytes.length != 12) throw new Error("Buffer-based ObjectId must be 12 bytes") this.bytes = bytes } else if (typeof bytes == 'string') { if (bytes.length != 24) throw new Error("String-based ObjectId must be 24 bytes") if (!/^[0-9a-f]{24}$/i.test(bytes)) throw new Error("String-based ObjectId must in hex-format:" + bytes) this.bytes = fromHex(bytes) } else if (typeof bytes !== 'undefined') { throw new Error("Unrecognized type: "+bytes) } else { var timestamp = (Date.now() / 1000) & 0xFFFFFFFF inc = ~~inc+1 // keep as integer this.bytes = new Buffer([ timestamp>>24, timestamp>>16, timestamp>>8, timestamp, machineAndPid[0], machineAndPid[1], machineAndPid[2], machineAndPid[3], machineAndPid[4], inc>>16, inc>>8, inc ]) } }
javascript
{ "resource": "" }
q13526
train
function( path ) { var parts = path.split( rpathsplit ), ns = munit.ns, assert; // Grep for nested path module munit.each( parts, function( part ) { if ( assert = ns[ part ] ) { ns = assert.ns; } else { throw new munit.AssertionError( "Module path not found '" + path + "'", munit._getModule ); } }); return assert; }
javascript
{ "resource": "" }
q13527
train
function( name, options, callback ) { var ns = munit.ns, parts = name.split( rpathsplit ), finalPart = parts.pop(), opts = munit.extend( true, {}, munit.defaults.settings ), assert = null, path = ''; // Filter through all parents parts.forEach(function( mod ) { // Update the path if ( path.length ) { path += '.'; } path += mod; // Assign assert module if ( ! ns[ mod ] ) { assert = ns[ mod ] = new munit.Assert( path, assert, opts ); } // Trickle down the path assert = ns[ mod ]; ns = assert.ns; opts = munit.extend( true, {}, opts, assert.options ); }); // Module already exists, update it if ( ns[ finalPart ] ) { assert = ns[ finalPart ]; // Test module is already in use, code setup is wrong if ( assert.callback ) { throw new munit.AssertionError( "'" + name + "' module has already been created", munit._createModule ); } assert.options = munit.extend( true, {}, opts, options ); assert.callback = callback; } else { options = munit.extend( true, {}, opts, options ); assert = ns[ finalPart ] = new munit.Assert( name, assert, options, callback ); } // Return the assertion module for use return assert; }
javascript
{ "resource": "" }
q13528
train
function( name, depends, callback ) { if ( ( ! munit.isString( depends ) && ! munit.isArray( depends ) ) || ! depends.length ) { throw new Error( "Depends argument not found" ); } return munit._module( name, { depends: depends }, callback ); }
javascript
{ "resource": "" }
q13529
train
function( name, handle ) { if ( munit.isObject( name ) ) { return munit.each( name, function( fn, method ) { munit.custom( method, fn ); }); } // Ensure that name can be used if ( munit.customReserved.indexOf( name ) > -1 ) { throw new Error( "'" + name + "' is a reserved name and cannot be added as a custom assertion test" ); } // Send off to assertion module for attachment munit.Assert.prototype[ name ] = handle; munit.each( munit.ns, function( mod ) { mod.custom( name, handle ); }); }
javascript
{ "resource": "" }
q13530
train
function( time ) { var h, m, s; if ( time > TIME_MINUTE ) { m = parseInt( time / TIME_MINUTE, 10 ); s = ( time % TIME_MINUTE ) / TIME_SECOND; return m + 'mins, ' + s + 's'; } else if ( time > TIME_SECOND ) { return ( time / TIME_SECOND ) + 's'; } else { return time + 'ms'; } }
javascript
{ "resource": "" }
q13531
train
function( string ) { return ( string || '' ).replace( ramp, "&amp;" ) .replace( rquote, "&quot;" ) .replace( rsquote, "&#039;" ) .replace( rlt, "&lt;" ) .replace( rgt, "&gt;" ); }
javascript
{ "resource": "" }
q13532
train
function( code, e, message ) { var callback = munit.render.callback; // Force a numeric code for the first parameter if ( ! munit.isNumber( code ) ) { throw new Error( "Numeric code parameter required for munit.exit" ); } // Allow code, message only arguments if ( message === undefined && munit.isString( e ) ) { message = e; e = null; } // Messaging if ( munit.isString( message ) ) { munit.color.red( message ); } // Force an error object for callbacks if ( ! munit.isError( e ) ) { e = new Error( message || 'munit exited' ); } e.code = code; // Only print out stack trace on an active process if ( munit.render.state !== munit.RENDER_STATE_COMPLETE ) { munit.log( e.stack ); } // Callback takes priority if ( callback ) { munit.render.callback = undefined; callback( e, munit ); } // No callback, end the process else { munit._exit( code ); } }
javascript
{ "resource": "" }
q13533
AssertionError
train
function AssertionError( message, startFunc ) { var self = this; self.name = 'Assertion Error'; self.message = message; if ( Error.captureStackTrace ) { Error.captureStackTrace( self, startFunc ); } }
javascript
{ "resource": "" }
q13534
buildFromString
train
function buildFromString({ declaration, name, mapActionType }) { if (typeof declaration === 'string') { return arg => ({ type: mapActionType(name), [declaration]: arg, }); } return null; }
javascript
{ "resource": "" }
q13535
buildFromArray
train
function buildFromArray({ declaration, name, mapActionType }) { if (Array.isArray(declaration)) { return (...args) => declaration.reduce( (result, key, index) => Object.assign( result, { [key]: args[index] } ), { type: mapActionType(name) } ); } return null; }
javascript
{ "resource": "" }
q13536
buildFromObject
train
function buildFromObject({ declaration, name, mapActionType }) { if (typeof declaration === 'object') { return () => ensureActionType(declaration, name, mapActionType); } return null; }
javascript
{ "resource": "" }
q13537
train
function () { var html = template(); var div = document.createElement('div'); div.innerHTML = html.trim(); var searchBar = this.applySearcbarEvents(div.firstChild); searchBar = this.setDefaultSearchTerm(searchBar); return searchBar; }
javascript
{ "resource": "" }
q13538
train
function (searchbar) { var that = this; var button = searchbar.querySelector('button[type=submit]'); var search = searchbar.querySelector('input[type=search]'); if (typeof button === 'undefined') { return searchbar; } button.onclick = function (ev) { ev.preventDefault(); that.emitter.emit('search-request', search); }; return searchbar; }
javascript
{ "resource": "" }
q13539
render
train
function render(code, data) { var js = '```js' + code + '```' return `<div class="vomit-snippet"><div class="column">${marked(js)}</div><div class="column"><script> (function() {${code}document.currentScript.parentElement.appendChild(component(${JSON.stringify(data.data)})) })()</script></div></div>` }
javascript
{ "resource": "" }
q13540
route
train
function route(name, titleToken, options) { var path, match; if (name instanceof RouteMeta) { return name; } if (name) { match = name.match(/^([^@]+)(?:@(.*))?$/); name = match[1]; path = match[2]; if (path === undefined) { path = name === 'index' ? '/' : name; } else if (path === '') { path = '/'; } else if (path === '*') { path = '/*wildcard'; } } else { path = '/'; } return RouteMeta.create({ name: name || 'application', path: path, routerTitleToken: {value: titleToken}, options: options || {} }); }
javascript
{ "resource": "" }
q13541
train
function (target) { if (this.get('isResource') && !this.get('indexChild')) { // add index route if it does not exist this._route('index'); } this.get('children').forEach(function (meta) { var args, methodName, isResource; args = [meta.get('name'), {path: meta.get('path')}]; methodName = meta.get('methodName'); isResource = meta.get('isResource'); if (isResource) { args.push(meta.get('mapFunction')); } console[isResource && console.group ? 'group' : 'log']( '[enhanced-router] defining ' + meta ); target[methodName].apply(target, args); if (isResource && console.group) { console.groupEnd(); } }); }
javascript
{ "resource": "" }
q13542
train
function (name, titleToken, options) { var child; if (!this.get('isResource')) { this.set('isResource', true); } child = route(name, titleToken, options, this); child.set('parent', this); this.get('children').pushObject(child); return this; }
javascript
{ "resource": "" }
q13543
train
function () { var routes = Array.prototype.slice.call(arguments); if (routes.length) { Ember.A(routes).forEach(function (child) { this._route(child); }, this); } else { if (!this.get('isResource')) { this.set('isResource', true); } } return this; }
javascript
{ "resource": "" }
q13544
train
function (options) { var Router, args; if (this.get('parent')) { throw new Error('Only the root route may be exported as an Ember router.'); } args = slice.call(arguments); if (!args.length || args[args.length - 1] instanceof Ember.Mixin) { args.push(options = {}); } else { options = args[args.length - 1]; } options._enhancedRouterRootMeta = this; Router = Ember.Router.extend.apply(Ember.Router, args); Router.map(this.get('mapFunction')); return Router; }
javascript
{ "resource": "" }
q13545
fuf
train
function fuf(target, source, options = {}) { return new Promise((resolve, reject) => { if (!target) { return reject(new Error('the target path is required')) } if (!source) { return reject(new Error('the source path is required')) } if (options && MATCHES.indexOf(options.match) === -1) { return reject(new Error(`options.match should be one of the following values: ${MATCHES.join(', ')}.`)) } options = { ...defaults, ...options } Promise.all([ pglob(target, { nodir: true, ignore: source }), findSourceFiles(source), ]).then(([targetFiles, sourceFiles]) => { // By default all source files are considered unused. const unused = sourceFiles.map(file => ({ ...file })) // We loop through all files looking for unused files matches, when we // found a match we removed it from the unused bag. const results = targetFiles.map(file => { return fs.readFile(file) .then(data => { const matches = findMatches(data.toString(), unused.map(u => u[options.match])) matches.forEach(match => { // Remove match from unused. unused.splice(unused.findIndex(u => u[options.match] === match.needle), 1) // Remove match from source files. sourceFiles.splice(sourceFiles.findIndex(f => f[options.match] === match.needle), 1) }) }) }) Promise .all(results) .then(() => { resolve({ unused }) }) }).catch(reject) }) }
javascript
{ "resource": "" }
q13546
pglob
train
function pglob(pattern, options) { return new Promise((resolve, reject) => { glob(pattern, options, (error, files) => { if (error) { return reject(error) } resolve(files) }) }) }
javascript
{ "resource": "" }
q13547
chrootSpawn
train
function chrootSpawn(command, argv, opts, callback) { argv = [opts.uid, opts.gid, command].concat(argv) const options = { cwd: opts.cwd, env: opts.env, stdio: 'inherit' } proc.spawn(`${__dirname}/chrootSpawn`, argv, options).on('exit', callback) }
javascript
{ "resource": "" }
q13548
mkdirMountInfo
train
function mkdirMountInfo(info, callback) { utils.mkdirMount(info.path, info.type, info.flags, info.extras, callback) }
javascript
{ "resource": "" }
q13549
create
train
function create(upperdir, callback) { var workdir = upperdir.split('/') var user = workdir.pop() var workdir = workdir.join('/')+'/.workdirs/'+user mkdirp(workdir, '0100', function(error) { if(error && error.code !== 'EEXIST') return callback(error) // Craft overlayed filesystem var type = 'overlay' var extras = { lowerdir: '/', upperdir: upperdir, workdir : workdir } utils.mkdirMount(upperdir, type, MS_NOSUID, extras, function(error) { if(error) return callback(error) var arr = [ { path: upperdir+'/dev', flags: MS_BIND, extras: {devFile: '/tmp/dev'} }, { path: upperdir+'/proc', flags: MS_BIND, extras: {devFile: '/proc'} }, { path: upperdir+'/tmp', type: 'tmpfs', flags: MS_NODEV | MS_NOSUID } ] each(arr, mkdirMountInfo, callback) }) }) }
javascript
{ "resource": "" }
q13550
clas
train
function clas(elem, className) { /** * @param {boolean} [val] * @returns {boolean|undefined} */ return function() { if (arguments.length) { elem.classList[arguments[0] ? "add" : "remove"](className); } else { return elem.classList.has(className); } } }
javascript
{ "resource": "" }
q13551
formatStr
train
function formatStr(str, values) { values = values || {}; if (typeof str !== 'string') { return str; } return str.replace(FORMAT_REGEXP, (m0, m1, m2) => (m1 === '%' ? "%{" + m2 + "}" : values[m2])); }
javascript
{ "resource": "" }
q13552
train
function( keyCode, strokesPerSnapshotExceeded ) { var keyGroup = UndoManager.getKeyGroup( keyCode ), // Count of keystrokes in current a row. // Note if strokesPerSnapshotExceeded will be exceeded, it'll be restarted. strokesRecorded = this.strokesRecorded[ keyGroup ] + 1; strokesPerSnapshotExceeded = ( strokesPerSnapshotExceeded || strokesRecorded >= this.strokesLimit ); if ( !this.typing ) onTypingStart( this ); if ( strokesPerSnapshotExceeded ) { // Reset the count of strokes, so it'll be later assigned to this.strokesRecorded. strokesRecorded = 0; this.editor.fire( 'saveSnapshot' ); } else { // Fire change event. this.editor.fire( 'change' ); } // Store recorded strokes count. this.strokesRecorded[ keyGroup ] = strokesRecorded; // This prop will tell in next itaration what kind of group was processed previously. this.previousKeyGroup = keyGroup; }
javascript
{ "resource": "" }
q13553
train
function() { // Stack for all the undo and redo snapshots, they're always created/removed // in consistency. this.snapshots = []; // Current snapshot history index. this.index = -1; this.currentImage = null; this.hasUndo = false; this.hasRedo = false; this.locked = null; this.resetType(); }
javascript
{ "resource": "" }
q13554
train
function( onContentOnly, image, autoFireChange ) { var editor = this.editor; // Do not change snapshots stack when locked, editor is not ready, // editable is not ready or when editor is in mode difference than 'wysiwyg'. if ( this.locked || editor.status != 'ready' || editor.mode != 'wysiwyg' ) return false; var editable = editor.editable(); if ( !editable || editable.status != 'ready' ) return false; var snapshots = this.snapshots; // Get a content image. if ( !image ) image = new Image( editor ); // Do nothing if it was not possible to retrieve an image. if ( image.contents === false ) return false; // Check if this is a duplicate. In such case, do nothing. if ( this.currentImage ) { if ( image.equalsContent( this.currentImage ) ) { if ( onContentOnly ) return false; if ( image.equalsSelection( this.currentImage ) ) return false; } else if ( autoFireChange !== false ) { editor.fire( 'change' ); } } // Drop future snapshots. snapshots.splice( this.index + 1, snapshots.length - this.index - 1 ); // If we have reached the limit, remove the oldest one. if ( snapshots.length == this.limit ) snapshots.shift(); // Add the new image, updating the current index. this.index = snapshots.push( image ) - 1; this.currentImage = image; if ( autoFireChange !== false ) this.refreshState(); return true; }
javascript
{ "resource": "" }
q13555
train
function( isUndo ) { var snapshots = this.snapshots, currentImage = this.currentImage, image, i; if ( currentImage ) { if ( isUndo ) { for ( i = this.index - 1; i >= 0; i-- ) { image = snapshots[ i ]; if ( !currentImage.equalsContent( image ) ) { image.index = i; return image; } } } else { for ( i = this.index + 1; i < snapshots.length; i++ ) { image = snapshots[ i ]; if ( !currentImage.equalsContent( image ) ) { image.index = i; return image; } } } } return null; }
javascript
{ "resource": "" }
q13556
train
function( newImage ) { // Do not change snapshots stack is locked. if ( this.locked ) return; if ( !newImage ) newImage = new Image( this.editor ); var i = this.index, snapshots = this.snapshots; // Find all previous snapshots made for the same content (which differ // only by selection) and replace all of them with the current image. while ( i > 0 && this.currentImage.equalsContent( snapshots[ i - 1 ] ) ) i -= 1; snapshots.splice( i, this.index - i + 1, newImage ); this.index = i; this.currentImage = newImage; }
javascript
{ "resource": "" }
q13557
train
function() { if ( this.locked ) { // Decrease level of lock and check if equals 0, what means that undoM is completely unlocked. if ( !--this.locked.level ) { var update = this.locked.update; this.locked = null; // forceUpdate was passed to lock(). if ( update === true ) this.update(); // update is instance of Image. else if ( update ) { var newImage = new Image( this.editor, true ); if ( !update.equalsContent( newImage ) ) this.update(); } } } }
javascript
{ "resource": "" }
q13558
onTypingStart
train
function onTypingStart( undoManager ) { // It's safe to now indicate typing state. undoManager.typing = true; // Manually mark snapshot as available. undoManager.hasUndo = true; undoManager.hasRedo = false; undoManager.onChange(); }
javascript
{ "resource": "" }
q13559
train
function( evt ) { // Block undo/redo keystrokes when at the bottom/top of the undo stack (#11126 and #11677). if ( CKEDITOR.tools.indexOf( keystrokes, evt.data.getKeystroke() ) > -1 ) { evt.data.preventDefault(); return; } // Cleaning tab functional keys. this.keyEventsStack.cleanUp( evt ); var keyCode = evt.data.getKey(), undoManager = this.undoManager; // Gets last record for provided keyCode. If not found will create one. var last = this.keyEventsStack.getLast( keyCode ); if ( !last ) { this.keyEventsStack.push( keyCode ); } // We need to store an image which will be used in case of key group // change. this.lastKeydownImage = new Image( undoManager.editor ); if ( UndoManager.isNavigationKey( keyCode ) || this.undoManager.keyGroupChanged( keyCode ) ) { if ( undoManager.strokesRecorded[ 0 ] || undoManager.strokesRecorded[ 1 ] ) { // We already have image, so we'd like to reuse it. undoManager.save( false, this.lastKeydownImage ); undoManager.resetType(); } } }
javascript
{ "resource": "" }
q13560
train
function() { // Input event is ignored if paste/drop event were fired before. if ( this.ignoreInputEvent ) { // Reset flag - ignore only once. this.ignoreInputEvent = false; return; } var lastInput = this.keyEventsStack.getLast(); // Nothing in key events stack, but input event called. Interesting... // That's because on Android order of events is buggy and also keyCode is set to 0. if ( !lastInput ) { lastInput = this.keyEventsStack.push( 0 ); } // Increment inputs counter for provided key code. this.keyEventsStack.increment( lastInput.keyCode ); // Exceeded limit. if ( this.keyEventsStack.getTotalInputs() >= this.undoManager.strokesLimit ) { this.undoManager.type( lastInput.keyCode, true ); this.keyEventsStack.resetInputs(); } }
javascript
{ "resource": "" }
q13561
train
function( evt ) { var undoManager = this.undoManager, keyCode = evt.data.getKey(), totalInputs = this.keyEventsStack.getTotalInputs(); // Remove record from stack for provided key code. this.keyEventsStack.remove( keyCode ); // Second part of the workaround for IEs functional keys bug. We need to check whether something has really // changed because we blindly mocked the keypress event. // Also we need to be aware that lastKeydownImage might not be available (#12327). if ( UndoManager.ieFunctionalKeysBug( keyCode ) && this.lastKeydownImage && this.lastKeydownImage.equalsContent( new Image( undoManager.editor, true ) ) ) { return; } if ( totalInputs > 0 ) { undoManager.type( keyCode ); } else if ( UndoManager.isNavigationKey( keyCode ) ) { // Note content snapshot has been checked in keydown. this.onNavigationKey( true ); } }
javascript
{ "resource": "" }
q13562
train
function( skipContentCompare ) { var undoManager = this.undoManager; // We attempt to save content snapshot, if content didn't change, we'll // only amend selection. if ( skipContentCompare || !undoManager.save( true, null, false ) ) undoManager.updateSelection( new Image( undoManager.editor ) ); undoManager.resetType(); }
javascript
{ "resource": "" }
q13563
train
function() { var editor = this.undoManager.editor, editable = editor.editable(), that = this; // We'll create a snapshot here (before DOM modification), because we'll // need unmodified content when we got keygroup toggled in keyup. editable.attachListener( editable, 'keydown', function( evt ) { that.onKeydown( evt ); // On IE keypress isn't fired for functional (backspace/delete) keys. // Let's pretend that something's changed. if ( UndoManager.ieFunctionalKeysBug( evt.data.getKey() ) ) { that.onInput(); } }, null, null, 999 ); // Only IE can't use input event, because it's not fired in contenteditable. editable.attachListener( editable, ( CKEDITOR.env.ie ? 'keypress' : 'input' ), that.onInput, that, null, 999 ); // Keyup executes main snapshot logic. editable.attachListener( editable, 'keyup', that.onKeyup, that, null, 999 ); // On paste and drop we need to ignore input event. // It would result with calling undoManager.type() on any following key. editable.attachListener( editable, 'paste', that.ignoreInputEventListener, that, null, 999 ); editable.attachListener( editable, 'drop', that.ignoreInputEventListener, that, null, 999 ); // Click should create a snapshot if needed, but shouldn't cause change event. // Don't pass onNavigationKey directly as a listener because it accepts one argument which // will conflict with evt passed to listener. // #12324 comment:4 editable.attachListener( editable.isInline() ? editable : editor.document.getDocumentElement(), 'click', function() { that.onNavigationKey(); }, null, null, 999 ); // When pressing `Tab` key while editable is focused, `keyup` event is not fired. // Which means that record for `tab` key stays in key events stack. // We assume that when editor is blurred `tab` key is already up. editable.attachListener( this.undoManager.editor, 'blur', function() { that.keyEventsStack.remove( 9 /*Tab*/ ); }, null, null, 999 ); }
javascript
{ "resource": "" }
q13564
train
function( keyCode ) { if ( typeof keyCode != 'number' ) { return this.stack.length - 1; // Last index or -1. } else { var i = this.stack.length; while ( i-- ) { if ( this.stack[ i ].keyCode == keyCode ) { return i; } } return -1; } }
javascript
{ "resource": "" }
q13565
train
function( keyCode ) { if ( typeof keyCode == 'number' ) { var last = this.getLast( keyCode ); if ( !last ) { // %REMOVE_LINE% throw new Error( 'Trying to reset inputs count, but could not found by keyCode: ' + keyCode + '.' ); // %REMOVE_LINE% } // %REMOVE_LINE% last.inputs = 0; } else { var i = this.stack.length; while ( i-- ) { this.stack[ i ].inputs = 0; } } }
javascript
{ "resource": "" }
q13566
train
function() { var i = this.stack.length, total = 0; while ( i-- ) { total += this.stack[ i ].inputs; } return total; }
javascript
{ "resource": "" }
q13567
train
function () { $.fn.mediumInsert.settings.enabled = false; $.fn.mediumInsert.insert.$el.find('.mediumInsert-buttons').addClass('hide'); }
javascript
{ "resource": "" }
q13568
train
function () { $.fn.mediumInsert.settings.enabled = true; $.fn.mediumInsert.insert.$el.find('.mediumInsert-buttons').removeClass('hide'); }
javascript
{ "resource": "" }
q13569
train
function (addon) { var editor = $.fn.mediumInsert.settings.editor, buttonLabels = (editor && editor.options) ? editor.options.buttonLabels : ''; var buttons; if($.fn.mediumInsert.settings.enabled) { buttons = '<div class="mediumInsert-buttons">'+ '<a class="mediumInsert-buttonsShow">+</a>'+ '<ul class="mediumInsert-buttonsOptions medium-editor-toolbar medium-editor-toolbar-active">'; } else { buttons = '<div class="mediumInsert-buttons hide">'+ '<a class="mediumInsert-buttonsShow">+</a>'+ '<ul class="mediumInsert-buttonsOptions medium-editor-toolbar medium-editor-toolbar-active">'; } if (Object.keys($.fn.mediumInsert.settings.addons).length === 0) { return false; } if (typeof addon === 'undefined') { $.each($.fn.mediumInsert.settings.addons, function (i) { buttons += '<li>' + addons[i].insertButton(buttonLabels) + '</li>'; }); } else { buttons += '<li>' + addons[addon].insertButton(buttonLabels) + '</li>'; } buttons += '</ul></div>'; return buttons; }
javascript
{ "resource": "" }
q13570
update
train
function update(item, model, data, funcParams) { var working = []; var definedByData = []; _.forEach(data, function(value, key) { if (_.isFunction(value)) { working.push(Promise.resolve(value()).then(function(val) { item[key] = val; })); } else item[key] = value; definedByData.push(value); }); _.forEach(model.itemDef, function(value, key) { if (value && value.__precalc) { var func = value.__precalc, previousVal = data[key]; working.push(Promise.resolve(func.call(item, previousVal, funcParams || {})).then(function(val) { item[key] = (val && val._stWrapped) ? val.val : val; })); } // if the property has not been set from the itemDef yet. This allows item def properties to be changed else if (!_.has(item, key) || definedByData.indexOf(key) !== -1) item[key] = value; }); return Promise.all(working); }
javascript
{ "resource": "" }
q13571
serverProperties
train
function serverProperties(item, model, props) { var result = {}; var toRefresh = []; _.forEach(props || item, function(val, key) { if (val == null) return; if (val._isModelItem) { result[key] = val.id; toRefresh.push(val); } else if (_.isArray(val)) { result[key] = _.map(val, function(item) { if (item._isModelItem) { toRefresh.push(item); return item.id; } return item; }); } else if (_.has(model.itemDef, key)) { if (_.has(model.itemDef[key], '__connection')) result[key] = val; } else result[key] = val; }); return { properties: result, refresh: toRefresh }; }
javascript
{ "resource": "" }
q13572
create
train
function create(item, model, data) { var serverProps = serverProperties(item, model, data).properties; return utils.socketPut(model.io, model.url + '/create/', serverProps).then(function(response) { _.merge(serverProps, response); return update(item, model, serverProps); }).then(function() { // Refresh all items that were referenced - some of their properties might change return Promise.all(_.map(serverProps.refresh, function(item) { return item.refresh(); })); }); }
javascript
{ "resource": "" }
q13573
modelItem
train
function modelItem(data, model) { var res = {}; utils.defineProperties(res, { _isModelItem: { value: true }, model: { value: model.value }, update: { value: function(data, sync) { if (sync == null) sync = true; return update(res, model, data).then(function() { if (!sync) return; return res.save(); }); } }, save: { value: function() { if (_.has(res, 'id')) { var props = serverProperties(res, model); return utils.socketPost(model.io, model.url + '/update/' + res.id, props.properties).then(function() { return Promise.all(_.map(props.refresh, function(item) { return item.refresh(); })); }); } return create(res, model); } }, refresh: { value: function() { if (!_.has(res, 'id')) return create(res, model); return utils.socketGet(model.io, model.url + '/' + res.id).then(function(data) { return update(res, model, data, { noRefresh: true }); }); } }, delete: { value: function() { model._removeItem(res); return utils.socketDelete(model.io, model.url, { id: res.id }); } }, matches: { value: function(query) { return utils.socketGet(model.io, model.url, query).then(function(r) { for (var i = 0; i < r.length; i++) { if (r[i].id === res.id) return true; } return false; }); } }, then: { value: function() { return res.ready.then.apply(res.ready, arguments); } }, catch: { value: function() { return res.ready.catch.apply(res.ready, arguments); } } }); res.ready = Promise.resolve(); update(res, model, data || {}); return res; }
javascript
{ "resource": "" }
q13574
train
function(name, opt_path) { var path = opt_path || "/"; /** * Sets the cookie * @param {string} value value for cookie * @param {number?} opt_days number of days until cookie * expires. Default = none */ this.set = function(value, opt_days) { if (value === undefined) { this.erase(); return; } // Cordova/Phonegap doesn't support cookies so use localStorage? if (window.hftSettings && window.hftSettings.inApp) { window.localStorage.setItem(name, value); return; } var expires = ""; opt_days = opt_days || 9999; var date = new Date(); date.setTime(Date.now() + Math.floor(opt_days * 24 * 60 * 60 * 1000)); // > 32bits. Don't use | 0 expires = "; expires=" + date.toGMTString(); var cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=" + path; document.cookie = cookie; }; /** * Gets the value of the cookie * @return {string?} value of cookie */ this.get = function() { // Cordova/Phonegap doesn't support cookies so use localStorage? if (window.hftSettings && window.hftSettings.inApp) { return window.localStorage.getItem(name); } var nameEQ = encodeURIComponent(name) + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; ++i) { var c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) === 0) { return decodeURIComponent(c.substring(nameEQ.length, c.length)); } } }; /** * Erases the cookie. */ this.erase = function() { if (window.hftSettings && window.hftSettings.inApp) { return window.localStorage.removeItem(name); } document.cookie = this.set(" ", -1); }; }
javascript
{ "resource": "" }
q13575
SimpleLogger
train
function SimpleLogger() { /* This class is a singleton */ if (arguments.callee._singletonInstance) { return arguments.callee._singletonInstance; } arguments.callee._singletonInstance = this; EventEmitter.call(this); // First, some basic loglevels. These can be overridden by the developer if desired. this.LOGLEVELS = { 'fatal': 0, 'error': 100, 'warning': 200, 'debug': 300, 'info': 400, 'trace': 500 }; // defaults to debug. this.loglevel = 'debug'; this.getLogLevelValue = function() { return this.LOGLEVELS[this.loglevel]; }; this.log = function(level, message, fn) { var logNumber = this.LOGLEVELS[level]; if (logNumber <= this.getLogLevelValue()) { this.emit('log', level, message); this.emit(level, message); if (!_.isUndefined(fn) && !_.isNull(fn)) { fn(message); } } }; this.on('log', function(level, message) { console.log(level + ": " + message); }) }
javascript
{ "resource": "" }
q13576
activate
train
function activate () { if (_active) return node _active = true debug('activated') if (!external) { _masterBroker.bind() _masterResolver.bind() } if (!node.isReady) _seekForMaster() return node }
javascript
{ "resource": "" }
q13577
deactivate
train
function deactivate () { if (!_active || _deactivating) return node debug('deactivating') if (external) { _active = false _subConnection.disconnect() _pubConnection.disconnect() node.emit('deactivated') } else { _deactivating = true let ensuredMaster = Promise.resolve() const isMaster = _subConnection.master && _subConnection.master.name === _name if (isMaster) { debug(`I'm the master node. I will try to elect another master before disconnecting.`) let advertiseId = `zz-zzzzzzzz-${_id}` ensuredMaster = _masterResolver .resolve(advertiseId) .then(master => { debug(`successfully elected a new master: ${master.name}`) try { _masterBroker.signalNewMaster(master) } catch (e) { console.log(e) } }) .catch(() => { debug(`failed to elect a new master. Disconnecting anyway.`) }) } ensuredMaster .then(() => { _subConnection.disconnect() _pubConnection.disconnect() _masterResolver.unbind() let timeout = isMaster ? 1000 : 1 setTimeout(() => { debug('deactivated') node.emit('deactivated') _masterBroker.unbind() }, timeout) }) } return node }
javascript
{ "resource": "" }
q13578
publish
train
function publish (channel, ...args) { if (!isString(channel)) throw new TypeError(`${_debugStr}: .publish(channel, [...args]) channel MUST be a string`) if (~internalChannels.indexOf(channel)) { console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot publish in it`) return node } if (!_pubConnection.connected) { console.warn(`${_debugStr} cannot publish on bus.`) return node } _pubConnection.publish(channel, ...args) return node }
javascript
{ "resource": "" }
q13579
unsubscribe
train
function unsubscribe (channels) { if (!isArray(channels)) channels = [channels] if (!every(channels, isString)) throw new TypeError(`${_debugStr}: .unsubscribe([channels]) channels must be represented by strings`) channels.forEach(channel => { if (~internalChannels.indexOf(channel)) { console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot unsubscribe from it.`) return } _subConnection.unsubscribe([channel]) }) return node }
javascript
{ "resource": "" }
q13580
_validateSettings
train
function _validateSettings (settings) { let { host, external, voteTimeout, electionPriority, coordinationPort } = settings if (!host || !isString(host)) throw new TypeError(ctorMessage('host is mandatory and should be a string.')) if (!isInteger(coordinationPort) || coordinationPort <= 0) throw new TypeError(ctorMessage('settings.coordinationPort should be a positive integer.')) if (!external) { if (!isInteger(voteTimeout) || voteTimeout <= 0) throw new TypeError(ctorMessage('settings.voteTimeout should be a positive integer.')) if (!isInteger(electionPriority) || electionPriority < 0 || electionPriority > 99) throw new TypeError(ctorMessage('settings.electionPriority should be an integer between 0 and 99.')) } }
javascript
{ "resource": "" }
q13581
findAll
train
function findAll (tree, test) { var found = test(tree) ? [tree] : [] if (isNode(tree)) { if (tree.children.length > 0) { tree.children.forEach(function (child) { found = found.concat(findAll(child, test)) }) } } return found }
javascript
{ "resource": "" }
q13582
quote
train
function quote(string) { var _Object$assign var quoteChar = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '"' if (quoteChar.length > 1 && process.env.NODE_ENV !== 'production') { console.error('quote: `quoteChar` is recommended as single character, but ' + JSON.stringify(quoteChar) + '.') } return _quote( string, quoteChar, getEscapable(quoteChar), Object.assign( {}, commonMeta, ((_Object$assign = {}), (_Object$assign[quoteChar] = '\\' + quoteChar), _Object$assign) ) ) }
javascript
{ "resource": "" }
q13583
cloneValue
train
function cloneValue(value, traversedValues) { if (!(value instanceof Object)) { return value } if (value instanceof Boolean) { return new Boolean(value.valueOf()) } if (value instanceof Number) { return new Number(value.valueOf()) } if (value instanceof String) { return new String(value.valueOf()) } if (value instanceof Date) { return new Date(value.valueOf()) } if (value instanceof RegExp) { return new RegExp(value.source, value.flags) } if ((typeof Blob === "function") && (value instanceof Blob)) { return value // immutable } if ((typeof File === "function") && (value instanceof File)) { return value // immutable } if ((typeof FileList === "function") && (value instanceof FileList)) { return value // immutable } if ((typeof ArrayBuffer === "function") && (value instanceof ArrayBuffer)) { return value.slice() } if ((typeof DataView === "function") && (value instanceof DataView)) { return new DataView( value.buffer.slice(), value.byteOffset, value.byteLength ) } let isTypedArray = TYPED_ARRAY_TYPES.some(type => value instanceof type) if (isTypedArray) { return value.subarray() } if ((typeof ImageData === "function") && (value instanceof ImageData)) { return new ImageData(value.data, value.width, value.height) } if ((typeof ImageBitmap === "function") && (value instanceof ImageBitmap)) { return value } if (value instanceof Array) { return cloneArray(value, traversedValues) } if (value instanceof Map) { return cloneMap(value, traversedValues) } if (value instanceof Set) { return cloneSet(value, traversedValues) } if (isPlainObjectOrEntity(value)) { return cloneObject(value, traversedValues) } throw new Error(`Unsupported argument type: ${value}`) }
javascript
{ "resource": "" }
q13584
cloneArray
train
function cloneArray(source, traversedValues) { let clone = [] traversedValues.set(source, clone) cloneStructure( source.keys(), key => source[key], (key, value) => clone[key] = value, traversedValues ) return clone }
javascript
{ "resource": "" }
q13585
cloneMap
train
function cloneMap(source, traversedValues) { let clone = new Map() traversedValues.set(source, clone) cloneStructure( source.keys(), key => source.get(key), (key, value) => clone.set(key, value), traversedValues ) return clone }
javascript
{ "resource": "" }
q13586
cloneSet
train
function cloneSet(source, traversedValues) { let clone = new Set() traversedValues.set(source, clone) cloneStructure( source.values(), entry => undefined, entry => clone.add(entry), traversedValues ) return clone }
javascript
{ "resource": "" }
q13587
cloneObject
train
function cloneObject(source, traversedValues) { let clone = {} traversedValues.set(source, clone) cloneStructure( Object.keys(source), key => source[key], (key, value) => clone[key] = value, traversedValues ) return clone }
javascript
{ "resource": "" }
q13588
cloneStructure
train
function cloneStructure(keys, getter, setter, traversedValues) { for (let key of keys) { let value = getter(key) let keyClone if (key instanceof Object) { if (traversedValues.has(key)) { keyClone = traversedValues.get(key) } else { keyClone = cloneValue(key, traversedValues) traversedValues.set(key, keyClone) } } else { keyClone = key } if (value instanceof Object) { if (traversedValues.has(value)) { setter(keyClone, traversedValues.get(value)) } else { let clonedValue = cloneValue(value, traversedValues) traversedValues.set(value, clonedValue) setter(keyClone, clonedValue) } } else { setter(keyClone, value) } } }
javascript
{ "resource": "" }
q13589
getStagedFiles
train
function getStagedFiles(callback) { const options = [ 'diff', '--cached', '--name-only', '--diff-filter=ACM' ] execFile('git', options, (err, stdout) => { if (err) return callback(err) const stagedFiles = stdout .split('\n') .filter(filename => filename.match(/.js$/)) callback(null, stagedFiles) }) }
javascript
{ "resource": "" }
q13590
lintFiles
train
function lintFiles(files) { const eslint = new CLIEngine() const report = eslint.executeOnFiles(files) return { text: friendlyFormatter(report.results), errorCount: report.errorCount, } }
javascript
{ "resource": "" }
q13591
isSupportedElement
train
function isSupportedElement( element, mode ) { if ( mode == CKEDITOR.ELEMENT_MODE_INLINE ) return element.is( CKEDITOR.dtd.$editable ) || element.is( 'textarea' ); else if ( mode == CKEDITOR.ELEMENT_MODE_REPLACE ) return !element.is( CKEDITOR.dtd.$nonBodyContent ); return 1; }
javascript
{ "resource": "" }
q13592
initComponents
train
function initComponents( editor ) { // Documented in dataprocessor.js. editor.dataProcessor = new CKEDITOR.htmlDataProcessor( editor ); // Set activeFilter directly to avoid firing event. editor.filter = editor.activeFilter = new CKEDITOR.filter( editor ); loadSkin( editor ); }
javascript
{ "resource": "" }
q13593
updateEditorElement
train
function updateEditorElement() { var element = this.element; // Some editor creation mode will not have the // associated element. if ( element && this.elementMode != CKEDITOR.ELEMENT_MODE_APPENDTO ) { var data = this.getData(); if ( this.config.htmlEncodeOutput ) data = CKEDITOR.tools.htmlEncode( data ); if ( element.is( 'textarea' ) ) element.setValue( data ); else element.setHtml( data ); return true; } return false; }
javascript
{ "resource": "" }
q13594
train
function( commandName, data ) { var command = this.getCommand( commandName ); var eventData = { name: commandName, commandData: data, command: command }; if ( command && command.state != CKEDITOR.TRISTATE_DISABLED ) { if ( this.fire( 'beforeCommandExec', eventData ) !== false ) { eventData.returnValue = command.exec( eventData.commandData ); // Fire the 'afterCommandExec' immediately if command is synchronous. if ( !command.async && this.fire( 'afterCommandExec', eventData ) !== false ) return eventData.returnValue; } } // throw 'Unknown command name "' + commandName + '"'; return false; }
javascript
{ "resource": "" }
q13595
train
function() { var keystrokes = this.keystrokeHandler.keystrokes, newKeystrokes = CKEDITOR.tools.isArray( arguments[ 0 ] ) ? arguments[ 0 ] : [ [].slice.call( arguments, 0 ) ], keystroke, behavior; for ( var i = newKeystrokes.length; i--; ) { keystroke = newKeystrokes[ i ]; behavior = 0; // It may be a pair of: [ key, command ] if ( CKEDITOR.tools.isArray( keystroke ) ) { behavior = keystroke[ 1 ]; keystroke = keystroke[ 0 ]; } if ( behavior ) keystrokes[ keystroke ] = behavior; else delete keystrokes[ keystroke ]; } }
javascript
{ "resource": "" }
q13596
transform
train
function transform() { for (var _len = arguments.length, matrices = Array(_len), _key = 0; _key < _len; _key++) { matrices[_key] = arguments[_key]; } matrices = Array.isArray(matrices[0]) ? matrices[0] : matrices; var multiply = function multiply(m1, m2) { return { a: m1.a * m2.a + m1.c * m2.b, c: m1.a * m2.c + m1.c * m2.d, e: m1.a * m2.e + m1.c * m2.f + m1.e, b: m1.b * m2.a + m1.d * m2.b, d: m1.b * m2.c + m1.d * m2.d, f: m1.b * m2.e + m1.d * m2.f + m1.f }; }; switch (matrices.length) { case 0: throw new Error('no matrices provided'); case 1: return matrices[0]; case 2: return multiply(matrices[0], matrices[1]); default: var _matrices = matrices, _matrices2 = _toArray(_matrices), m1 = _matrices2[0], m2 = _matrices2[1], rest = _matrices2.slice(2); var m = multiply(m1, m2); return transform.apply(undefined, [m].concat(_toConsumableArray(rest))); } }
javascript
{ "resource": "" }
q13597
correctQuestionMarkAndAnd
train
function correctQuestionMarkAndAnd(url) { var baseURL = url; // Remove && mistake baseURL = baseURL.replace(new RegExp('&&', 'g'), '&'); // Ends width ? if (new RegExp('[\?]$').test(baseURL)) { // Do nothing } else { // Does not end on ? // Contains ? if (baseURL.includes('?')) { // Ends width & if (new RegExp('[\&]$').test(baseURL)) { // Do nothing } else { // Does not end on & // Add & baseURL += '&'; } } else { // Does not contain on ? // Count of & var countOfAnd = baseURL.split('&').length - 1; // Ends with & if (new RegExp('[\&]$').test(baseURL)) { if (countOfAnd === 1) { // Remove & baseURL = baseURL.slice(0, -1); // Add ? baseURL += '?'; } else { // Replace first & with ? baseURL = baseURL.replace('&', '?'); } } else { // Does not contain on ? ends not on & // Contains one or more & if (countOfAnd > 1) { // Replace first & with ? baseURL = baseURL.replace('&', '?'); // Add & baseURL += '&'; } else { // Does not contain & // Add ? baseURL += '?'; } } } } return baseURL; }
javascript
{ "resource": "" }
q13598
removeParameters
train
function removeParameters(url) { var baseURL = url; // Iterate over all parameters for (var int = 0; int < params.length; int++) { // Remove parameter baseURL = baseURL.replace(new RegExp(params[int] + '=[^&]*&', 'ig'), ''); } return baseURL; }
javascript
{ "resource": "" }
q13599
determineBaseURL
train
function determineBaseURL(url) { var baseURL; // Check if url is set if (url) { // Remove whitespace baseURL = url.trim(); baseURL = correctHttpAndHttps(baseURL); baseURL = correctQuestionMarkAndAnd(baseURL); baseURL = removeParameters(baseURL); } else { // Throw error (no url) throw new Error('The url parameter is not set.'); } return baseURL; }
javascript
{ "resource": "" }