_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q43200
train
function (milliseconds) { if (milliseconds === undefined) { milliseconds = this._timeout; } var self = this; if (self._timeout !== milliseconds) { self._timeout = milliseconds; if (self._timer) { clearTimeout(this._timer); self._timer = null; } if (milliseconds) { this._timer = setTimeout(function () { self._timer = null; if (!self.finished) { var error = new core.Error({ code: 'timeout', message: 'Promise has timeout' }); /*if (self.getPromise().cancel) { self.getPromise().cancel(error); } else { self.emitError(error); }*/ if (this._canceller) { self.cancel(error); } else { self.emitError(error); } } }, milliseconds); } } return this; }
javascript
{ "resource": "" }
q43201
train
function (target, property) { return perform(target, function (target) { return target.get(property); }, function (target) { return target[property]; }); }
javascript
{ "resource": "" }
q43202
train
function (target, methodName, args) { return perform(target, function (target) { return target.apply(methodName, args); }, function (target) { return target[methodName].apply(target, args); }); }
javascript
{ "resource": "" }
q43203
train
function (target, property, value) { return perform(target, function (target) { return target.set(property, value); }, function (target) { target[property] = value; return value; }); }
javascript
{ "resource": "" }
q43204
train
function (asyncFunction, callbackNotDeclared) { var arity = asyncFunction.length; return function () { var deferred = new Deferred(), args = slice.call(arguments), callback; if (callbackNotDeclared && !args[args.length + 1] instanceof Function) { arity = args.length + 1; } callback = args[arity - 1]; args.splice(arity); args[arity - 1] = function (error, result) { if (error) { deferred.emitError(error); } else { if (args.length > 2) { // if there are multiple success values, we return an array args.shift(1); deferred.emitSuccess(args); } else { deferred.emitSuccess(result); } } }; asyncFunction.apply(this, args); //Node old school if (callback) { deferred.then( function (result) { callback(Promise.NO_ERROR, result); }, function (error) { callback(error, Promise.NO_RESULT); } ); } return deferred.getPromise(); }; }
javascript
{ "resource": "" }
q43205
DemoDevice
train
function DemoDevice(){ var _device = {}; _device[DEVICE.ModelManufacturer] = "Internet of Protocols Alliance"; _device[DEVICE.ModelManufacturerUrl] = "http://iopa.io"; _device[DEVICE.ModelName] = "npm install iopa-devices"; _device[DEVICE.ModelNumber] = "iopa-devices"; _device[DEVICE.ModelUrl] = "http://github.com/iopa-io/iopa-devices"; _device[DEVICE.PlatformId] = "LOCALHOST"; _device[DEVICE.PlatformName] = "Iopa Device Stick"; _device[DEVICE.PlatformFirmware] = packageVersion; _device[DEVICE.PlatformOS] = require('os').type() + "/" + require('os').release(); _device[DEVICE.Id] = "12345-67890"; _device[DEVICE.Type] = "urn:io.iopa:demo:devices"; _device[DEVICE.Version] = packageVersion; _device[DEVICE.Location] = [37.7833, 122.4167]; _device[DEVICE.LocationName] = "San Francisco, USA"; _device[DEVICE.Currency] = "USD"; _device[DEVICE.Region] = "Home"; _device[DEVICE.Policy] = null; _device[DEVICE.Url] = "coap://localhost"; _device[DEVICE.Resources] = []; var _res = {}; _res[RESOURCE.TypeName] = "IOPA Demo Projector"; _res[RESOURCE.Type] = "urn:io.iopa:resource:projector"; _res[RESOURCE.Interface] = "if.switch.binary"; _res[RESOURCE.Path] = "/media/projector"; _res[RESOURCE.Name] = "Projector 1"; _res[RESOURCE.Value] = false; _device[DEVICE.Resources].push(_res); this._device = _device; }
javascript
{ "resource": "" }
q43206
train
function(arrPathFromRoot) { if (arrPathFromRoot) { let routes = {}; for (let pathFromRoot of arrPathFromRoot) { routes['/' + pathFromRoot] = { get: function(req, res) { web.utils.serveStaticFile(path.join(web.conf.publicDir, pathFromRoot), res); } } } return routes; } return null; }
javascript
{ "resource": "" }
q43207
transformData
train
function transformData(data, headers, status, fns) { if (isFunction(fns)) return fns(data, headers, status); forEach(fns, function(fn) { data = fn(data, headers, status); }); return data; }
javascript
{ "resource": "" }
q43208
treeSorter
train
function treeSorter(node) { if(node[options.childsProp]) { node[options.childsProp].forEach(function(node) { treeSorter(node); }); node[options.childsProp].sort(function childSorter(a, b) { var result; if('undefined' === typeof a[options.sortProp]) { result = (options.sortDesc ? 1 : -1); } else if('undefined' === typeof b[options.sortProp]) { result = (options.sortDesc ? -1 : 1); } else { result = a[options.sortProp] > b[options.sortProp] ? (options.sortDesc ? -1 : 1) : (options.sortDesc ? 1 : -1); } return result; }); } }
javascript
{ "resource": "" }
q43209
train
function( userId ) { return this.memory.createRoom( userId ) .then( function( id ) { rooms[ id ] = room( this.memory, id ); return promise.resolve( rooms[ id ] ); }.bind( this ), function() { return promise.reject( 'could not get a roomID to create a room' ); }); }
javascript
{ "resource": "" }
q43210
train
function( userId, id ) { return this.memory.joinRoom( userId, id ) .then( function( id ) { if( rooms[ id ] === undefined ) { rooms[ id ] = room( this.memory, id ); } return promise.resolve( rooms[ id ] ); }.bind( this )); }
javascript
{ "resource": "" }
q43211
train
function( userId ) { return this.memory.getPublicRoom() .then(function( roomId ) { if ( roomId ) { return this.enter( userId, roomId); } else { return promise.reject( 'Could not find a public room' ); } }.bind(this)); }
javascript
{ "resource": "" }
q43212
train
function( userId, id ) { return this.memory.leaveRoom( userId, id ) .then( function( numUsers ) { if( numUsers == 0 ) { // remove all listeners from room since there should be one rooms[ id ].removeAllListeners(); rooms[ id ].setPrivate(); delete rooms[ id ]; return promise.resolve( null ); } else { return promise.resolve( rooms[ id ] ); } }); }
javascript
{ "resource": "" }
q43213
getProperties
train
function getProperties() { return analytics.management.webproperties.listAsync({ auth: auth, accountId: accountId }) .then((properties) => { logger.debug('got properties', JSON.stringify(properties, null, 4)); return _.map(properties.items, (property) => { return _.pick(property, 'id', 'name'); }); }); }
javascript
{ "resource": "" }
q43214
getViews
train
function getViews(property, options) { logger.debug('getting views for', property); return analytics.management.profiles.listAsync({ auth: auth, accountId: accountId, webPropertyId: property.id }) .then((profiles) => { // If we're not grouping by view, then only include the default view // named "All Web Site Data". Otherwise the counts can potentially be // duplicated. if (options.metagroup !== 'view') { profiles.items = _.where(profiles.items, {name: 'All Web Site Data'}); } return _.map(profiles.items, (profile) => { return { webPropertyId: property.id, webProperty: property.name, viewId: profile.id, view: profile.name }; }); }); }
javascript
{ "resource": "" }
q43215
get
train
function get(ids) { var els = [], el; if (o.typeOf(ids) !== 'array') { ids = [ids]; } var i = ids.length; while (i--) { el = o.get(ids[i]); if (el) { els.push(el); } } return els.length ? els : null; }
javascript
{ "resource": "" }
q43216
train
function(config, runtimes) { var up, runtime; up = new plupload.Uploader(config); runtime = o.Runtime.thatCan(up.getOption().required_features, runtimes || config.runtimes); up.destroy(); return runtime; }
javascript
{ "resource": "" }
q43217
normalizeArguments
train
function normalizeArguments() { const a = arguments; if (debug) debugLog(`normalizeArguments: arguments:${util.inspect(arguments)}`); if (debug) debugLog(`normalizeArguments: a0: ${a[0]} a1:${a[1]} a2:${a[2]} a3:${a[3]}`); if (debug) debugLog(`normalizeArguments: a0: ${typeof a[0]} a1:${typeof a[1]} a2:${typeof a[2]} a3:${typeof a[3]}`); if (debug) { debugLog(`normalizeArguments:` + ` a0: ${typeof a[0]} a1:${typeof a[1]} a2:${Array.isArray(a[2])} a3:${typeof a[3]}`); } let args = { name : '', description : '', prereqs : [], /* eslint-disable no-empty-function */ action : function action() {}, /* eslint-enable no-empty-function */ }; if ((a.length === 4) && (typeof a[3] === 'function') && (Array.isArray(a[2])) && (typeof a[1] === 'string') && (typeof a[0] === 'string')) { // all 4 arguments provided and of the correct type args.name = a[0]; args.description = a[1]; args.prereqs = a[2]; args.action = a[3]; } else if ((a.length === 3) && (typeof a[2] === 'function') && (Array.isArray(a[1])) && (typeof a[0] === 'string')) { // only 3 arguments types string, array, function args.name = a[0]; args.prereqs = a[1]; args.action = a[2]; } else if ((a.length === 3) && (typeof a[2] === 'function') && (typeof a[1] === 'string') && (typeof a[0] === 'string')) { // only 3 arguments types string string, function args.name = a[0]; args.description = a[1]; args.action = a[2]; } else if ((a.length === 2) && (typeof a[1] === 'function') && (typeof a[0] === 'string')) { // only 2 arguments - they must be - types string, function args.name = a[0]; args.action = a[1]; } else { args = undefined; } return args; }
javascript
{ "resource": "" }
q43218
loadPreloadedTasks
train
function loadPreloadedTasks(taskCollection) { const preTasks = [ { name : 'help', description : 'list all tasks', prerequisites : [], action : function actionHelp() { /* eslint-disable no-console */ console.log('this is the help task running '); /* eslint-enable no-console */ }, }, ]; const collection = loadTasksFromArray(preTasks, taskCollection); return collection; }
javascript
{ "resource": "" }
q43219
requireTasks
train
function requireTasks(yakefile, taskCollection) { const debug = false; globals.globalTaskCollection = taskCollection; if (debug) debugLog(`loadTasks: called ${yakefile}`); /* eslint-disable global-require */ require(yakefile); /* eslint-disable global-require */ const newTaskCollection = globals.globalTaskCollection; return newTaskCollection; // no copy - untidy functional programming }
javascript
{ "resource": "" }
q43220
train
function (item, arr, options) { debug('Match'); debug('Item: %s', item); debug('Array: %s', arr); debug('Options: %o', options); // normal item match (case-sensitive) let found = arr.indexOf(item) > -1; // case insensitive test if only item not found in case-sensitive mode if (options.caseInsensitive || (options.caseInsensitive && !found)) { debug('Checking case-insensitive too...'); arr.map(target => { if (target.toLowerCase() === item.toLowerCase()) { found = true; } }); } debug('Found: %s', found); return found; }
javascript
{ "resource": "" }
q43221
train
function(changedModel, options) { // Don't update unless the model is different var newModel = model.syncMonitor.get('model'); if (_.isEqual(JSON.parse(JSON.stringify(model)), JSON.parse(JSON.stringify(newModel)))) { log.info('monitorListener.noChanges', t.className, newModel); return; } // Disconnect if the model was deleted or the ID isn't the same var isDeleted = (_.size(newModel) === 0); if (isDeleted || newModel.id !== modelId) { log.info('modelListener.deleted', t.className, newModel); disconnectListeners(); } // Forward changes to the model (including server-side delete) var newOpts = {isSyncChanging:true}; if (isDeleted) { log.info('modelListener.deleting', t.className, newModel); model.clear(newOpts); } else { // Make sure the model is set to exactly the new contents (vs. override) log.info('modelListener.setting', t.className, newModel); model.clear({silent:true}); model.set(newModel, newOpts); } }
javascript
{ "resource": "" }
q43222
db
train
function db(op, fn){ if(!indexedDB){ return fn(new Error('store `indexeddb` not supported by this browser')); } if(typeof op === 'function'){ fn = op; op = 'readwrite'; } if(source !== null){ return fn(null, source.transaction(module.exports.prefix, op).objectStore(module.exports.prefix)); } var req = indexedDB.open(module.exports.prefix, 1); req.onerror = function(e){ fn(e); }; req.onupgradeneeded = function(){ // First time setup: create an empty object store req.result.createObjectStore(module.exports.prefix); }; req.onsuccess = function() { source = req.result; db(op, fn); }; }
javascript
{ "resource": "" }
q43223
main
train
function main(env, print, cb) { var dir = env.opts.directory || path.resolve(env.cwd, 'artifacts/jslint'), lines = [], count = 0, total = 0; function perOffense(o) { var evidence = o.evidence.trim(); count += 1; total += 1; lines.push(fmt(' #%d %d,%d: %s', count, o.line, o.col, o.msg)); if (evidence) { lines.push(' ' + evidence); } } /** * invoked by lintifier.doneYet() * @param {object|string|null} offenses * @param {string} msg "Done. no lint found..." */ function reporter(offenses, msg) { var files, summary, writeErr; if (('string' === typeof offenses) || offenses instanceof Error) { cb(offenses); return; } function perFile(pathname) { count = 0; lines.push(pathname); offenses[pathname].forEach(perOffense); lines.push(''); // blank line } if (offenses) { // accumulate report in lines array files = Object.keys(offenses); files.forEach(perFile); summary = getSummary(total, files.length); if (env.opts.print) { lines.unshift('JSLint Report', ''); print(lines.join(EOL)); } else { writeErr = writeHtmlFile(dir, getHtml(lines, summary)); } // has errors cb(writeErr || summary); } else { // is lint free cb(null, msg); } } return reporter; }
javascript
{ "resource": "" }
q43224
readonly
train
function readonly (stream) { var rs = stream._readableState || {} var opts = {} if (typeof stream.read !== 'function') { throw new Error('not a readable stream') } ['highWaterMark', 'encoding', 'objectMode'].forEach(function (p) { opts[p] = rs[p] }) var readOnly = new Readable(opts) var waiting = false stream.on('readable', function () { if (waiting) { waiting = false readOnly._read() } }) readOnly._read = function (size) { var buf while ((buf = stream.read(size)) !== null) { if (!readOnly.push(buf)) { return } } waiting = true } stream.once('end', function () { readOnly.push(null) }) stream.on('close', function () { readOnly.emit('close') }) stream.on('error', function (err) { readOnly.emit('error', err) }) return readOnly }
javascript
{ "resource": "" }
q43225
setupEvent
train
function setupEvent(event_type) { var event = void 0; if (exists(document.createEvent)) { // modern browsers event = document.createEvent('HTMLEvents'); event.initEvent(event_type, true, true); } else if (exists(document.createEventObject)) { // IE9- event = document.createEventObject(); event.eventType = event_type; event.eventName = event_type; } return event; }
javascript
{ "resource": "" }
q43226
fireEvent
train
function fireEvent(target_object, event, event_type) { var on_event_type = 'on' + event_type; if (exists(target_object.dispatchEvent)) { // modern browsers target_object.dispatchEvent(event); } else if (exists(target_object.fireEvent)) { // IE9- target_object.fireEvent(on_event_type, event); } else if (exists(target_object[event_type])) { target_object[event_type](); } else if (exists(target_object[on_event_type])) { target_object[on_event_type](); } }
javascript
{ "resource": "" }
q43227
simulateEvent
train
function simulateEvent(target_object, event_type) { if (!exists(target_object)) { throw new TypeError('simulateEvent: target object must be defined'); } if (typeof event_type !== 'string') { throw new TypeError('simulateEvent: event type must be a string'); } var event = setupEvent(event_type); fireEvent(target_object, event, event_type); }
javascript
{ "resource": "" }
q43228
setupMouseEvent
train
function setupMouseEvent(properties) { var event = document.createEvent('MouseEvents'); event.initMouseEvent(properties.type, properties.canBubble, properties.cancelable, properties.view, properties.detail, properties.screenX, properties.screenY, properties.clientX, properties.clientY, properties.ctrlKey, properties.altKey, properties.shiftKey, properties.metaKey, properties.button, properties.relatedTarget); return event; }
javascript
{ "resource": "" }
q43229
simulateMouseEvent
train
function simulateMouseEvent(target_object) { var custom_properties = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var properties = sanitizeProperties(custom_properties); var event = setupMouseEvent(properties); target_object.dispatchEvent(event); }
javascript
{ "resource": "" }
q43230
onText
train
function onText (text) { if (!current || !text) return; titles.push(text); self.emit('title', text); }
javascript
{ "resource": "" }
q43231
extend
train
function extend(obj) { for(var i=1,len=arguments.length;i<len;i++) { var props = arguments[i]; for(var p in props) { if(props.hasOwnProperty(p)) { obj[p] = props[p]; } } } return obj; }
javascript
{ "resource": "" }
q43232
inherit
train
function inherit(x, props) { var r = Object.create(x); return extend(r, props); }
javascript
{ "resource": "" }
q43233
train
function(grammar, ruleName) { grammar = this._apply("anything"); ruleName = this._apply("anything"); var foreign = inherit(grammar, { bt: this.bt.borrow() }); var ans = foreign._apply(ruleName); this.bt.take_back(); // return the borrowed input stream return ans; }
javascript
{ "resource": "" }
q43234
_not
train
function _not(expr) { var state = this.bt.current_state(); try { var r = expr.call(this) } catch (f) { this.bt.catch_mismatch(f); this.bt.restore(state); return true } this.bt.mismatch("Negative lookahead didn't match got " + r); }
javascript
{ "resource": "" }
q43235
_lookahead
train
function _lookahead(expr) { var state = this.bt.current_state(), ans = expr.call(this); this.bt.restore(state); return ans }
javascript
{ "resource": "" }
q43236
train
function() { var state = this.bt.current_state(); for(var i=0,len=arguments.length; i<len; i++) { try { return arguments[i].call(this) } catch (f) { this.bt.catch_mismatch(f); this.bt.restore(state); } } this.bt.mismatch("All alternatives failed"); }
javascript
{ "resource": "" }
q43237
train
function(rule) { var state = this.bt.current_state(); try { return rule.call(this); } catch(f) { this.bt.catch_mismatch(f); this.bt.restore(state); } }
javascript
{ "resource": "" }
q43238
GELFManager
train
function GELFManager(options) { if (typeof options === 'undefined') options = {}; for (k in GELFManager.options) if (typeof options[k] === 'undefined') options[k] = GELFManager.options[k]; this.debug = options.debug; this.chunkTimeout = options.chunkTimeout; this.gcTimeout = options.gcTimeout; EventEmitter.call(this); this.chunksPool = {}; process.nextTick(this._gc.bind(this)); }
javascript
{ "resource": "" }
q43239
parentFolder
train
function parentFolder(fullPath) { var isFile = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; // If no path passed in, use the file path of the // caller. if (!fullPath) { fullPath = module.parent.filename; isFile = true; } var pathObj = _path2['default'].parse(fullPath); if (isFile) { return pathObj.dir.split(_path2['default'].sep).slice(-1)[0]; } return pathObj.name; }
javascript
{ "resource": "" }
q43240
train
function() { var obj = arguments[0], args = Array.prototype.slice.call(arguments, 1); function copy(destination, source) { for (var property in source) { if (source[property] && source[property].constructor && source[property].constructor === Object) { destination[property] = destination[property] || {}; copy(destination[property], source[property]); } else { destination[property] = source[property]; } } return destination; } for(var i in args) { copy(obj, args[i]); } return obj; }
javascript
{ "resource": "" }
q43241
train
function(proto) { function F() {} this.merge(F.prototype, proto || {}, (function() { var Events = function() {}; Events.prototype = EventEmitter.prototype; return new Events(); })()); return new F(); }
javascript
{ "resource": "" }
q43242
splitByDot
train
function splitByDot(str) { var result = []; var s = ""; for (var i = 0; i < str.length; i++) { if (str[i] == "\\" && str[i+1] == ".") { i++; s += "."; continue; } if (str[i] == ".") { result.push(s); s = ""; continue; } s += str[i]; } if (s) { result.push(s); } return result; }
javascript
{ "resource": "" }
q43243
normilizeSquareBrackets
train
function normilizeSquareBrackets(str) { var m; while ((m = reSqrBrackets.exec(str))) { var header = m[1] ? m[1] + '.' : ''; var body = m[2].replace(/\./g, "\\."); var footer = m[3] || ''; str = header + body + footer; } return str; }
javascript
{ "resource": "" }
q43244
ArrayLoader
train
function ArrayLoader(posts) { var self = this; posts.forEach(function (post, index) { if (!('id' in post)) { post.id = index; } }); process.nextTick(function () { self.emit('load', posts); }); }
javascript
{ "resource": "" }
q43245
train
function( options ){ options = options || {}; options.$db = cOptions.db; options.$dbName = cOptions.database; options.$model = cOptions.model; return new cOptions.cls( options ); }
javascript
{ "resource": "" }
q43246
report
train
function report(items, heading) { grunt.log.subhead(heading); if (items.length > 0) { grunt.log.error(grunt.log.wordlist(items, {separator: '\n'})); } else { grunt.log.ok(); } }
javascript
{ "resource": "" }
q43247
obj
train
function obj(argv, callback) { var uri = argv[2]; if (argv[3]) { util.put(argv[2], '<> <> """' + argv[3] + '""" .', function(err, callback){ if (err) { console.error(err); } else { console.log('put value : ' + argv[3]); } }); } else { var wss = 'wss://' + uri.split('/')[2] + '/'; var s = new ws(wss, { origin: 'http://websocket.org' }); s.on('open', function open() { s.send('sub ' + uri); }); s.on('close', function close() { console.log('disconnected'); }); s.on('message', function message(data, flags) { var a = data.split(' '); if (a.length && a[0] === 'pub') { util.getAll(a[1], function(err, res) { if (err) { callback(err); } else { callback(null, res[res.length-1].object.value); } }); } }); } }
javascript
{ "resource": "" }
q43248
bin
train
function bin(argv) { obj(argv, function(err, res) { if (err) { console.log(err); } else { console.log(res); } }); }
javascript
{ "resource": "" }
q43249
validateAttributes
train
function validateAttributes( modelName, attributes = {}, errors = [] ) { if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) { throw new TypeError( "definition of attributes must be object" ); } const names = Object.keys( attributes ); const handlers = {}; for ( let i = 0, length = names.length; i < length; i++ ) { const name = names[i]; const attribute = attributes[name]; if ( !attribute.type ) { attribute.type = "string"; } const type = Types.selectByName( attribute.type ); if ( !type ) { throw new TypeError( `invalid attribute type "${attribute.type}" in attribute "${name}" of model "${modelName}"` ); } if ( type.checkDefinition( attribute, errors ) ) { handlers[name] = type; } } return handlers; }
javascript
{ "resource": "" }
q43250
compileCoercionMap
train
function compileCoercionMap( attributes ) { if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) { throw new TypeError( "definition of attributes must be object" ); } const coercions = {}; const attributeNames = Object.keys( attributes ); for ( let ai = 0, aLength = attributeNames.length; ai < aLength; ai++ ) { const attributeName = attributeNames[ai]; const attribute = attributes[attributeName]; ( function( name, handler, definition ) { coercions[name] = value => handler.coerce( value, definition ); } )( attributeName, Types.selectByName( attribute.type ), attribute ); } return coercions; }
javascript
{ "resource": "" }
q43251
compileCoercion
train
function compileCoercion( attributes ) { if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) { throw new TypeError( "definition of attributes must be object" ); } const attributeNames = Object.keys( attributes ); const numAttributes = attributeNames.length; const coercion = []; for ( let ai = 0; ai < numAttributes; ai++ ) { const attributeName = attributeNames[ai]; const attribute = attributes[attributeName]; const handler = Types.selectByName( attribute.type ); const { args, body } = extractBody( handler.coerce ); if ( args.length < 2 ) { throw new TypeError( `coerce() of ModelType for handling ${attribute.type} values must accept two arguments` ); } coercion[ai] = ` { let ${args[0]} = __props["${attributeName}"]; const ${args[1]} = __attrs["${attributeName}"]; { ${body.replace( ptnTrailingReturn, ( all, term ) => `__props["${attributeName}"] = ${term.trim()};` )} } } `; } // eslint-disable-next-line no-new-func return new Function( ` const __attrs = this.constructor.schema.attributes; const __props = this.properties; ${coercion.join( "" )} ` ); }
javascript
{ "resource": "" }
q43252
compileValidator
train
function compileValidator( attributes ) { if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) { throw new TypeError( "definition of attributes must be object" ); } const attributeNames = Object.keys( attributes ); const numAttributes = attributeNames.length; const validation = []; for ( let ai = 0; ai < numAttributes; ai++ ) { const attributeName = attributeNames[ai]; const attribute = attributes[attributeName]; const handler = Types.selectByName( attribute.type ); const { args, body } = extractBody( handler.isValid ); if ( args.length < 4 ) { throw new TypeError( `isValid() of ModelType for handling ${attribute.type} values must accept four arguments` ); } validation[ai] = ` { const ${args[0]} = "${attributeName}"; let ${args[1]} = __props["${attributeName}"]; const ${args[2]} = __attrs["${attributeName}"]; const ${args[3]} = __errors; { ${body} } } `; } // eslint-disable-next-line no-new-func return new Function( ` const __attrs = this.constructor.schema.attributes; const __props = this.properties; const __errors = []; ${validation.join( "" )} return __errors; ` ); }
javascript
{ "resource": "" }
q43253
compileDeserializer
train
function compileDeserializer( attributes ) { if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) { throw new TypeError( "definition of attributes must be object" ); } const attributeNames = Object.keys( attributes ); const numAttributes = attributeNames.length; const deserialization = new Array( 2 * numAttributes ); let write = 0; for ( let ai = 0; ai < numAttributes; ai++ ) { const attributeName = attributeNames[ai]; const attribute = attributes[attributeName]; const handler = Types.selectByName( attribute.type ); let sourceName; // append deserialize() method of current attribute's type handler { const { args, body } = extractBody( handler.deserialize ); if ( args.length < 1 ) { throw new TypeError( `deserialize() of ModelType for handling ${attribute.type} values must accept one argument` ); } if ( body.replace( ptnTrailingReturn, "" ).trim().length ) { sourceName = "$$d"; deserialization[write++] = ` { let ${args[0]} = $$s["${attributeName}"]; { ${body.replace( ptnTrailingReturn, ( all, term ) => `$$d["${attributeName}"] = ${term.trim()};` )} } } `; } else { sourceName = "$$s"; } } // append coerce() method of current attribute's type handler { const { args, body } = extractBody( handler.coerce ); if ( args.length < 2 ) { throw new TypeError( `coerce() of ModelType for handling ${attribute.type} values must accept two arguments` ); } deserialization[write++] = ` { let ${args[0]} = ${sourceName}["${attributeName}"]; const ${args[1]} = $$attrs["${attributeName}"]; { ${body.replace( ptnTrailingReturn, ( all, term ) => `$$d["${attributeName}"] = ${term.trim()};` )} } } `; } } deserialization.splice( write ); // eslint-disable-next-line no-new-func return new Function( "$$input", "$$attrs", ` if ( !$$attrs || typeof $$attrs !== "object" ) { throw new TypeError( "missing definition of attributes required for deserialization" ); } const $$s = $$input && typeof $$input === "object" ? $$input : {}; const $$d = {}; ${deserialization.join( "" )} return $$d; ` ); }
javascript
{ "resource": "" }
q43254
train
function( editor ) { var elementPath = editor.elementPath(), activePath = elementPath && elementPath.elements, pathMember, ret; // IE8: upon initialization if there is no path elementPath() returns null. if ( elementPath ) { for ( var i = 0; i < activePath.length; i++ ) { pathMember = activePath[ i ]; if ( !ret && pathMember.getName() == 'span' && pathMember.hasAttribute( 'dir' ) && pathMember.hasAttribute( 'lang' ) ) ret = pathMember; } } return ret; }
javascript
{ "resource": "" }
q43255
train
function(actionName) { self[actionName] = function() { var args = arguments; self._stack.push({action : actionName, args : args}); return self; }; }
javascript
{ "resource": "" }
q43256
train
function(actionName, action, resourcePath) { // prefix function to set rest values var identify = function(req, res, next) { res.set('XX-Powered-By', 'Restpress'); req.resource = self; req.actionName = actionName; req.action = action; next(); }; self[actionName] = function() { if (identify) { // insert identify as second argument // This is to be done only once [].unshift.call(arguments, identify); identify = null; } // insert actionPath as first argument [].unshift.call(arguments, resourcePath + action.route); // Hack for restify where 'delete' method is 'del' var appMethod = action.method; if (appMethod == 'delete' && typeof self.app[appMethod] !== 'function' && typeof self.app['del'] === 'function') { appMethod = 'del'; } // Call express app VERB function self.app[appMethod].apply(self.app, arguments); // return this for chaining return self; }; }
javascript
{ "resource": "" }
q43257
train
function(req, res, next) { res.set('XX-Powered-By', 'Restpress'); req.resource = self; req.actionName = actionName; req.action = action; next(); }
javascript
{ "resource": "" }
q43258
populateStack
train
function populateStack(stack, rootPath, files, callback) { stack.unshift(...files .filter(file => file.stats.isDirectory()) .map(file => path.join(rootPath, file.path))); async.nextTick(callback, null, files); }
javascript
{ "resource": "" }
q43259
processStackItem
train
function processStackItem(out, stack, rootPath, userFilter, readMode) { // Initialize a new file object. const initFile = (dirPath) => { return (fileName, callback) => { const filePath = path.join(dirPath, fileName); fs.stat(filePath, (error, stats) => { async.nextTick(callback, error, { path: path.relative(rootPath, filePath), stats, }); }); }; }; // Filter supported files. const filterSupported = () => { return (file, callback) => { const keep = file.stats.isFile() || file.stats.isDirectory(); async.nextTick(callback, null, keep); }; }; // Filter output files. const filterOutput = () => { return (file, callback) => { const keep = file.stats.isFile() && userFilter(file); async.nextTick(callback, null, keep); }; }; // Read a file's data. const readData = () => { return (file, callback) => { const filePath = path.join(rootPath, file.path); read(filePath, readMode, (error, data) => { async.nextTick(callback, error, Object.assign({}, file, { data })); }); }; }; return (callback) => { const dirPath = stack.shift(); async.waterfall([ cb => fs.readdir(dirPath, cb), (fileNames, cb) => async.map(fileNames, initFile(dirPath), cb), (files, cb) => async.filter(files, filterSupported(), cb), (files, cb) => populateStack(stack, rootPath, files, cb), (files, cb) => async.filter(files, filterOutput(), cb), (files, cb) => async.map(files, readData(), cb), ], (error, result) => { if (error) { async.nextTick(callback, error); return; } out.push(...result); async.nextTick(callback, null); }); }; }
javascript
{ "resource": "" }
q43260
tween
train
function tween(a, b){ var string = [] var keys = [] var from = [] var to = [] var cursor = 0 var m while (m = number.exec(b)) { if (m.index > cursor) string.push(b.slice(cursor, m.index)) to.push(Number(m[0])) keys.push(string.length) string.push(null) cursor = number.lastIndex } if (cursor < b.length) string.push(b.slice(cursor)) while (m = number.exec(a)) from.push(Number(m[0])) return function frame(n){ var i = keys.length while (i--) string[keys[i]] = from[i] + (to[i] - from[i]) * n return string.join('') } }
javascript
{ "resource": "" }
q43261
safeEndingTags
train
function safeEndingTags(content) { var MJElements = [].concat(WHITELISTED_GLOBAL_TAG); (0, _forEach2.default)(_extends({}, _MJMLElementsCollection2.default, _MJMLHead2.default), function (element, name) { var tagName = element.tagName || name; MJElements.push(tagName); }); var safeContent = (0, _parseAttributes2.default)(MJElements, content.replace(/\$/g, '&#36;')); (0, _concat2.default)(_MJMLElementsCollection.endingTags, _MJMLHead.endingTags).forEach(function (tag) { safeContent = safeContent.replace(regexTag(tag), _dom2.default.replaceContentByCdata(tag)); }); return safeContent; }
javascript
{ "resource": "" }
q43262
mjmlElementParser
train
function mjmlElementParser(elem, content) { if (!elem) { throw new _Error.NullElementError('Null element found in mjmlElementParser'); } var findLine = content.substr(0, elem.startIndex).match(/\n/g); var lineNumber = findLine ? findLine.length + 1 : 1; var tagName = elem.tagName.toLowerCase(); var attributes = (0, _mapValues2.default)(_dom2.default.getAttributes(elem), function (val) { return decodeURIComponent(val); }); var element = { tagName: tagName, attributes: attributes, lineNumber: lineNumber }; if (_MJMLElementsCollection.endingTags.indexOf(tagName) !== -1) { var $local = _dom2.default.parseXML(elem); element.content = (0, _removeCDATA2.default)($local(tagName).html().trim()); } else { var children = _dom2.default.getChildren(elem); element.children = children ? (0, _compact2.default)((0, _filter2.default)(children, function (child) { return child.tagName; }).map(function (child) { return mjmlElementParser(child, content); })) : []; } return element; }
javascript
{ "resource": "" }
q43263
runSauceLabs
train
function runSauceLabs(location, remote, options) { var capabilities = options.capabilities; if (remote === 'browserstack') { var user = options.username || process.env.BROWSER_STACK_USERNAME; var key = options.accessKey || process.env.BROWSER_STACK_ACCESS_KEY; if (!user || !key) { return Promise.reject(new Error('You must provide `username` and `accessKey` as options ' + 'or set "BROWSER_STACK_USERNAME" and "BROWSER_STACK_ACCESS_KEY" in your ' + 'environment variables.')); } remote = 'http://hub-cloud.browserstack.com/wd/hub'; capabilities = function (platform) { var result = {}; Object.keys(options.capabilities || {}).forEach(function (key) { result[key] = options.capabilities[key]; }); Object.keys(platform).forEach(function (key) { result[key] = platform[key]; }); result['browserstack.user'] = user; result['browserstack.key'] = key; return result; }; } return (options.platforms ? Promise.resolve(options.platforms) : getPlatforms({ filterPlatforms: options.filterPlatforms, choosePlatforms: options.choosePlatforms })).then(function (platforms) { return runBrowsers(location, remote, { name: options.name, parallel: options.parallel || 3, platforms: platforms, throttle: options.throttle, capabilities: capabilities, debug: options.debug, httpDebug: options.httpDebug, jobInfo: options.jobInfo, allowExceptions: options.allowExceptions, testComplete: options.testComplete, testPassed: options.testPassed, bail: options.bail, timeout: options.timeout, onStart: options.onStart, onQueue: options.onQueue, onResult: options.onResult, onBrowserResults: options.onBrowserResults }); }); }
javascript
{ "resource": "" }
q43264
writeHeader
train
function writeHeader(buffer, offset, size, opCode) { offset = binary.writeInt(buffer, offset, size) offset = binary.writeInt(buffer, offset, 0) offset = binary.writeInt(buffer, offset, 0) offset = binary.writeInt(buffer, offset, opCode) return offset }
javascript
{ "resource": "" }
q43265
train
function (elem, offsetParent) { var offset, parentOffset if (window.jQuery) { if (!offsetParent) { return window.jQuery(elem).position() } offset = window.jQuery(elem).offset() parentOffset = window.jQuery(offsetParent).offset() // Get element offset relative to offsetParent return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left } } parentOffset = { top: 0, left: 0 } // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if (window.getComputedStyle(elem).position === 'fixed' ) { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect() } else { if (!offsetParent) { // Get *real* offsetParent offsetParent = position.offsetParent(elem) } // Get correct offsets offset = offsetFunc(elem) if (offsetParent.nodeName !== 'HTML') { parentOffset = offsetFunc(offsetParent) } // Add offsetParent borders parentOffset.top += parseInt(window.getComputedStyle(offsetParent).borderTopWidth, 10) parentOffset.left += parseInt(window.getComputedStyle(offsetParent).borderLeftWidth, 10) } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - parseInt(window.getComputedStyle(elem).marginTop, 10), left: offset.left - parentOffset.left - parseInt(window.getComputedStyle(elem).marginLeft, 10) } }
javascript
{ "resource": "" }
q43266
Definition
train
function Definition (factoryName, factory) { var configDefaults = {} var deps = [] return { /** * Calls the factory for each arguments and returns * the list of tasks that just got created. * * @params {Object} * @returns {Array} */ add: function add () { var configs = _(arguments).toArray().flatten(true).value() if (configs.length === 0) { // by adding an empty object // we'll create a task that has no alias // that's useful for Definition that are not // really tasks creators (e.g the help task) configs = [{}] } var addedTasks = _(configs) .map(function (config) { return _.assign({}, configDefaults, config) }) .map(function (config) { var taskName = name(factoryName, config.alias) var deps = _(factory(config, options())).flatten(true).filter(_.identity).value() var fn = _.isFunction(_.last(deps)) ? deps.pop() : _.noop gulp.task(taskName, deps, fn) return taskName }) .run() if (gulp.tasks[factoryName] == null || gulp.tasks[factoryName].$root) { gulp.task(factoryName, deps.concat(tasks(factoryName + ':'))) gulp.tasks[factoryName].$root = true } return addedTasks }, /** * Sets the factory's default config. * * @param {Object} config * @returns {{add: add, defaults: defaults, before: before}} */ defaults: function defaults (config) { configDefaults = config return this }, /** * Getter/setter that add tasks to run before any factory's task. * * @returns {*} */ before: function before () { if (arguments.length) { deps = arguments[0] return this } return deps } } }
javascript
{ "resource": "" }
q43267
main
train
function main () { var taskList = _(arguments).toArray().flatten(true).value() gulp.task('default', taskList) return this }
javascript
{ "resource": "" }
q43268
tasks
train
function tasks (taskName) { var taskList = _.keys(gulp.tasks) if (taskName == null) { return taskList } return _.filter(taskList, function (task) { return _.startsWith(task, taskName) }) }
javascript
{ "resource": "" }
q43269
train
function() { var deferred = Q.defer(); try { request .get(getRepoUrl('releases')) .set('Authorization', 'token ' + config.token) .then(function(res) { logRequestSuccess(res); deferred.resolve(res.body); }, function(err) { logRequestError(err); deferred.reject(err.message); }); } catch(err) { console.log(err); deferred.reject(err.message); } return deferred.promise; }
javascript
{ "resource": "" }
q43270
train
function( query, excludeRoot, fromTop ) { var evaluator; if ( typeof query == 'string' ) evaluator = function( node ) { return node.getName() == query; }; if ( query instanceof CKEDITOR.dom.element ) evaluator = function( node ) { return node.equals( query ); }; else if ( CKEDITOR.tools.isArray( query ) ) evaluator = function( node ) { return CKEDITOR.tools.indexOf( query, node.getName() ) > -1; }; else if ( typeof query == 'function' ) evaluator = query; else if ( typeof query == 'object' ) evaluator = function( node ) { return node.getName() in query; }; var elements = this.elements, length = elements.length; excludeRoot && length--; if ( fromTop ) { elements = Array.prototype.slice.call( elements, 0 ); elements.reverse(); } for ( var i = 0; i < length; i++ ) { if ( evaluator( elements[ i ] ) ) return elements[ i ]; } return null; }
javascript
{ "resource": "" }
q43271
train
function( tag ) { var holder; // Check for block context. if ( tag in CKEDITOR.dtd.$block ) { // Indeterminate elements which are not subjected to be splitted or surrounded must be checked first. var inter = this.contains( CKEDITOR.dtd.$intermediate ); holder = inter || ( this.root.equals( this.block ) && this.block ) || this.blockLimit; return !!holder.getDtd()[ tag ]; } return true; }
javascript
{ "resource": "" }
q43272
isActive
train
function isActive() { try { var key = '___session is active___'; return session.get(key) || session.set(key, true); } catch (err) { return false; } }
javascript
{ "resource": "" }
q43273
train
function (event) { event.preventDefault(); if (!currentElement) { return; } var newHeight = currentElement.data('startHeight') + (event.pageY - currentElement.data('startY')); currentElement.parent().height(newHeight); }
javascript
{ "resource": "" }
q43274
assign
train
function assign() { var result = {}; var args = Array.prototype.slice.call(arguments); for(var i = 0; i < args.length; i++) { var obj = args[i]; if(typeof obj !== 'object') { continue; } for(var key in obj) { if(obj.hasOwnProperty(key)) { result[key] = obj[key]; } } obj = void 0; } return result; }
javascript
{ "resource": "" }
q43275
train
function(err, results) { if(options.headers) { // Set some headers so we can track what's going on var headers = { 'X-Throttled': results.throttled, 'X-Throttle-Remaining': Math.max(options.limit - results.count, 0) }; if (results.expiresAt) { headers['X-Throttle-Reset'] = results.expiresAt; } res.set(headers); } if (err) { // Unknown error next(err); return; } else if (results.throttled) { if(logger) { // Log it logger.warn( '%s - ResponseThrottled for %s seconds - %s requests exceeded %s within %s seconds', ip, options.ban, results.count, options.limit, options.period); } // Let the client know this is forbidden res.status(403); // Create a human readable error var banLength = moment.duration(options.ban, 'seconds').humanize(); next('Warning: Too many requests. You have been throttled for ' + banLength + '. ' + 'Try again ' + moment(results.expiresAt).fromNow()); return; } else { // All is good next(); return; } }
javascript
{ "resource": "" }
q43276
train
function(key, data) { var currentData; currentData = settings[key]; if ((currentData != null) && _.isObject(currentData)) { settings[key] = _.extend(data, settings[key]); } else if (currentData == null) { settings[key] = data; } }
javascript
{ "resource": "" }
q43277
train
function(key, data) { var currentData; currentData = settings[key] || {}; settings[key] = _.extend(currentData, data); }
javascript
{ "resource": "" }
q43278
train
function (err) { var storage = getStorage(); if (storage && storage.errors) { storage.errors.push(err); return localStorage.setItem([config.nameSpace], JSON.stringify(storage)); } }
javascript
{ "resource": "" }
q43279
searchArray
train
function searchArray(list, value) { var index = list.indexOf(value); if (index === -1) return false; return value; }
javascript
{ "resource": "" }
q43280
searchBase
train
function searchBase(base) { var basename = path.resolve(base, modulename); // return no path var filename = searchArray(dirMap, basename); if (filename) return filename; // return .js path filename = searchArray(dirMap, basename + '.js'); if (filename) return filename; // return .json path filename = searchArray(dirMap, basename + '.json'); if (filename) return filename; // if input was an path, do search more if (isPath) return false; // resolve and return /package.json path if (packageMap[basename]) { return packageMap[basename]; } return searchArray(dirMap, basename + '/index.js'); }
javascript
{ "resource": "" }
q43281
buildPackage
train
function buildPackage(callback) { var dirMap = self.build.dirMap, i = dirMap.length, filepath, pkgName = '/package.json', pkgLength = pkgName.length, list = []; // search dirmap for package.json while(i--) { filepath = dirMap[i]; if (filepath.slice(filepath.length - pkgLength, filepath.length) === pkgName) { list.push(filepath); } } function resolvePackage(filepath, callback) { var dirname = filepath.slice(0, filepath.length - pkgLength); var fullpath = path.resolve(self.piccolo.get('modules'), './' + filepath); var response = { key: dirname }; fs.readFile(fullpath, 'utf8', function (error, content) { if (error) return callback(error, null); // remove BOM content = removeBOM(content); // use index if filepath is empty var filepath; if (content === '') { filepath = path.resolve(dirname, 'index.js'); } // read JSON file var result; try { result = JSON.parse(content); } catch (e) { return callback(e, null); } if (result.main) { filepath = path.resolve(dirname, result.main); } else { filepath = path.resolve(dirname, './index.js'); } // check that file exist var fullpath = path.resolve(self.piccolo.get('modules'), './' + filepath); fs.exists(fullpath, function (exist) { response.value = exist ? filepath : false; callback(null, response); }); }); } // read all package.json files and resolve the filepath async.map(list, resolvePackage, function (error, list) { if (error) return callback(error, null); var final = {}; list.forEach(function (obj) { final[obj.key] = obj.value; }); // save resolved packageMap self.build.packageMap = final; callback(null, null); }); }
javascript
{ "resource": "" }
q43282
buildMap
train
function buildMap() { var dependencies = self.build.dependencies = {}; var cacheTime = self.cache.stats; var buildTime = self.build.mtime; Object.keys(cacheTime).forEach(function (filepath) { buildTime[filepath] = cacheTime[filepath].getTime(); }); // deep resolve all dependencies self.build.dirMap.forEach(function (filename) { var list = []; // the result array will be filled by his function deepResolve(self, filename, list); // dry result array var result = dependencies[filename] = []; var i = list.length; while(i--) { if (result.indexOf(list[i]) === -1) { result.push(list[i]); } } }); }
javascript
{ "resource": "" }
q43283
train
function() { var cert = this.keychain.getCertPem(); if (!cert) { throw new CError('missing certificate').log(); } var tmp = this.getDate() + '::' + cert + '::' + SECRET_CLIENT; var hmac = forge.hmac.create(); hmac.start('sha256', SECRET); hmac.update(tmp); return hmac.digest().toHex(); }
javascript
{ "resource": "" }
q43284
train
function() { if (this.getMode() !== mode) { throw new CError('unexpected mode').log(); } var cert; try { cert = this.keychain.getCertPem(); } catch (e) { throw new CError({ body: { code: 'ImATeapot', message: 'missing certificate', cause: e } }).log('body'); } if (!cert) { throw new CError('missing certificate').log(); } var out = { mode: this.getMode(), cert: cert }; if (this.getSid()) { out.sid = this.getSid(); } return out; }
javascript
{ "resource": "" }
q43285
blockFilter
train
function blockFilter( isOutput, fillEmptyBlock ) { return function( block ) { // DO NOT apply the filler if it's a fragment node. if ( block.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT ) return; cleanBogus( block ); var shouldFillBlock = typeof fillEmptyBlock == 'function' ? fillEmptyBlock( block ) : fillEmptyBlock; if ( shouldFillBlock !== false && isEmptyBlockNeedFiller( block ) ) { block.add( createFiller( isOutput ) ); } }; }
javascript
{ "resource": "" }
q43286
brFilter
train
function brFilter( isOutput ) { return function( br ) { // DO NOT apply the filer if parent's a fragment node. if ( br.parent.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT ) return; var attrs = br.attributes; // Dismiss BRs that are either bogus or eol marker. if ( 'data-cke-bogus' in attrs || 'data-cke-eol' in attrs ) { delete attrs [ 'data-cke-bogus' ]; return; } // Judge the tail line-break BR, and to insert bogus after it. var next = getNext( br ), previous = getPrevious( br ); if ( !next && isBlockBoundary( br.parent ) ) append( br.parent, createFiller( isOutput ) ); else if ( isBlockBoundary( next ) && previous && !isBlockBoundary( previous ) ) createFiller( isOutput ).insertBefore( next ); }; }
javascript
{ "resource": "" }
q43287
maybeBogus
train
function maybeBogus( node, atBlockEnd ) { // BR that's not from IE<11 DOM, except for a EOL marker. if ( !( isOutput && !CKEDITOR.env.needsBrFiller ) && node.type == CKEDITOR.NODE_ELEMENT && node.name == 'br' && !node.attributes[ 'data-cke-eol' ] ) { return true; } var match; // NBSP, possibly. if ( node.type == CKEDITOR.NODE_TEXT && ( match = node.value.match( tailNbspRegex ) ) ) { // We need to separate tail NBSP out of a text node, for later removal. if ( match.index ) { ( new CKEDITOR.htmlParser.text( node.value.substring( 0, match.index ) ) ).insertBefore( node ); node.value = match[ 0 ]; } // From IE<11 DOM, at the end of a text block, or before block boundary. if ( !CKEDITOR.env.needsBrFiller && isOutput && ( !atBlockEnd || node.parent.name in textBlockTags ) ) return true; // From the output. if ( !isOutput ) { var previous = node.previous; // Following a line-break at the end of block. if ( previous && previous.name == 'br' ) return true; // Or a single NBSP between two blocks. if ( !previous || isBlockBoundary( previous ) ) return true; } } return false; }
javascript
{ "resource": "" }
q43288
cleanBogus
train
function cleanBogus( block ) { var bogus = []; var last = getLast( block ), node, previous; if ( last ) { // Check for bogus at the end of this block. // e.g. <p>foo<br /></p> maybeBogus( last, 1 ) && bogus.push( last ); while ( last ) { // Check for bogus at the end of any pseudo block contained. if ( isBlockBoundary( last ) && ( node = getPrevious( last ) ) && maybeBogus( node ) ) { // Bogus must have inline proceeding, instead single BR between two blocks, // is considered as filler, e.g. <hr /><br /><hr /> if ( ( previous = getPrevious( node ) ) && !isBlockBoundary( previous ) ) bogus.push( node ); // Convert the filler into appropriate form. else { createFiller( isOutput ).insertAfter( node ); node.remove(); } } last = last.previous; } } // Now remove all bogus collected from above. for ( var i = 0 ; i < bogus.length ; i++ ) bogus[ i ].remove(); }
javascript
{ "resource": "" }
q43289
isEmptyBlockNeedFiller
train
function isEmptyBlockNeedFiller( block ) { // DO NOT fill empty editable in IE<11. if ( !isOutput && !CKEDITOR.env.needsBrFiller && block.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT ) return false; // 1. For IE version >=8, empty blocks are displayed correctly themself in wysiwiyg; // 2. For the rest, at least table cell and list item need no filler space. (#6248) if ( !isOutput && !CKEDITOR.env.needsBrFiller && ( document.documentMode > 7 || block.name in CKEDITOR.dtd.tr || block.name in CKEDITOR.dtd.$listItem ) ) { return false; } var last = getLast( block ); return !last || block.name == 'form' && last.name == 'input' ; }
javascript
{ "resource": "" }
q43290
isEmpty
train
function isEmpty( node ) { return node.type == CKEDITOR.NODE_TEXT && !CKEDITOR.tools.trim( node.value ) || node.type == CKEDITOR.NODE_ELEMENT && node.attributes[ 'data-cke-bookmark' ]; }
javascript
{ "resource": "" }
q43291
isBlockBoundary
train
function isBlockBoundary( node ) { return node && ( node.type == CKEDITOR.NODE_ELEMENT && node.name in blockLikeTags || node.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT ); }
javascript
{ "resource": "" }
q43292
train
function(regex, text){ var nextIndex = 0; var result = []; var execResult; while ((execResult = regex.exec(text))!== null) { result.push({ start: execResult.index, matchLength: execResult[0].length}); } return { next: function(){ return nextIndex < result.length ? result[nextIndex++] : null; } }; }
javascript
{ "resource": "" }
q43293
lambdaError
train
function lambdaError(fn, settings){ var log = (settings && settings.log === false ? false : true); var map = (settings && settings.map ? settings.map : undefined); var exclude = (settings && settings.exclude ? settings.exclude : undefined); return (event, context, callback) => { fn(event, context, (err, result) => { if(err){ if(log){ console.error(Errors.stack(err)); } if(typeof err !== 'object'){ console.error('Error must be an object:', err); err = new InvalidErrorValue(err); } return callback(Errors.json(err, false, map, exclude)); } return callback(null, result); }); }; }
javascript
{ "resource": "" }
q43294
asyncd
train
function asyncd(pw, evts, fname, args) { var es = Array.isArray(evts) ? evts : [evts]; for (var i = 0; i < es.length; i++) { if (es[i]) { defer(asyncCb.bind(es[i])); } } function asyncCb() { var argsp = args && args.length ? [this] : null; if (argsp) { argsp.push.apply(argsp, args); pw[fname].apply(pw, argsp); } else pw[fname](this); } return pw; }
javascript
{ "resource": "" }
q43295
defer
train
function defer(cb) { if (!defer.nextLoop) { var ntv = typeof setImmediate === 'function'; defer.nextLoop = ntv ? setImmediate : function setImmediateShim(cb) { if (defer.obj) { if (!defer.cbs.length) { defer.obj.setAttribute('cnt', 'inc'); } defer.cbs.push(cb); } else { setTimeout(cb, 0); } }; if (!ntv && typeof MutationObserver === 'object' && typeof document === 'object') { defer.cbs = []; defer.obj = document.createElement('div'); defer.ob = new MutationObserver(function mutations() { for (var cbl = defer.cbs.slice(), i = defer.cbs.length = 0, l = cbl.length; i < l; i++) { cbl[i](); } }).observe(defer.obj, { attributes: true }); } } return defer.nextLoop.call(null, cb); }
javascript
{ "resource": "" }
q43296
merge
train
function merge(dest, src, ctyp, nou, non) { if (!src || typeof src !== 'object') return dest; var keys = Object.keys(src); var i = keys.length, dt; while (i--) { if (isNaN(keys[i]) && src.hasOwnProperty(keys[i]) && (!nou || (nou && typeof src[keys[i]] !== 'undefined')) && (!non || (non && src[keys[i]] !== null))) { if (ctyp && dest[keys[i]] != null && (dt = typeof dest[keys[i]]) !== 'undefined' && dt !== typeof src[keys[i]]) { continue; } dest[keys[i]] = src[keys[i]]; } } return dest; }
javascript
{ "resource": "" }
q43297
props
train
function props(dest, pds, src, isrc, ndflt, nm, nmsrc) { var asrt = nm && src; if (asrt) assert.ok(dest, 'no ' + nm); var i = pds.length; while (i--) { if (asrt) prop(dest, pds[i], src, isrc, ndflt, nm, nmsrc); else prop(dest, pds[i], src, isrc, ndflt); } return dest; }
javascript
{ "resource": "" }
q43298
prop
train
function prop(dest, pd, src, isrc, ndflt, nm, nmsrc) { if (nm && src) { assert.strictEqual(dest[pd.n], src[pd.n], (nm ? nm + '.' : '') + pd.n + ': ' + dest[pd.n] + ' !== ' + (nmsrc ? nmsrc + '.' : '') + pd.n + ': ' + src[pd.n]); } else { var dtyp = (dest && typeof dest[pd.n]) || '', vtyp, v, useObj = pd.v && Array.isArray(pd.v); if (dtyp === 'undefined') v = (src && (isrc || pd.i) && (!useObj || typeof src[pd.n] === 'object') ? src[pd.n] : null) || (ndflt ? undefined : pd.d); else if (!useObj && dtyp === 'number') v = typeof pd.l === 'number' && dest[pd.n] < pd.l ? pd.l : typeof pd.h === 'number' && dest[pd.n] > pd.h ? pd.h : undefined; else if (useObj && dtyp === 'object') v = props(dest[pd.n], pd.v, src[pd.n], isrc, ndflt, nm, nmsrc); if ((vtyp = typeof v) !== 'undefined' && (!pd.r || !!~pd.r.indexOf(v))) { if (!pd.c || (vtyp === typeof pd.c && Array.isArray(pd.c) === Array.isArray(v))) dest[pd.n] = v; } } return dest; }
javascript
{ "resource": "" }
q43299
train
function(el){ var self = this; var $input = $('input.tokenSearch', el); var suggestions = new can.List([]); this.viewModel.attr('searchInput', $input); // http://loopj.com/jquery-tokeninput/ $input.tokenInput(suggestions, { theme: 'facebook', placeholder:'Search...', preventDuplicates: true, allowFreeTagging:true, tokenLimit:3, allowTabOut:false, /** * onResult is used to pre-process suggestions. * In our case we want to show current item if there is no results. */ onResult: function (item) { if($.isEmptyObject(item)){ var tempObj={ id: $('input:first', el).val(), name: $('input:first', el).val()}; return [tempObj]; }else{ return item; } }, /** * onAdd is used to maintain the suggestion dropdown box and the searchTerms in the scope. * It is called internally by the jquery.tokenInput plugin when either the enter key * is pressed in the input box or a selection is made in the suggestions dropdown. */ onAdd: function (item) { // Check if it already exists in the suggestions list. Duplicates aren't allowed. var exists = false; for(var j = 0; j < suggestions.length; j++){ if(suggestions[j].attr('name').toLowerCase() === item.name.toLowerCase()){ exists=true; break; } } // If it didn't exist, add it to the list of suggestions and the searchTerms. if(!exists){ suggestions.push(item); } // We are using searchTerms's setter to execute the filter, so have to set the property (not just update): var searchTerms = self.viewModel.attr('searchTerms').attr().concat(item.name); self.viewModel.attr('searchTerms', searchTerms); }, /** * onDelete is used to remove items from searchTerms in the scope. It is called internally * by the jquery.tokenInput plugin when a tag gets removed from the input box. */ onDelete: function (item) { var searchTerms = self.viewModel.attr('searchTerms').attr(), searchTerm = item && (item.id || item.name || item); searchTerms.splice(searchTerms.indexOf(searchTerm), 1); // We are using searchTerms's setter to execute the filter, so have to set the property (not just update): self.viewModel.attr('searchTerms', searchTerms); } }); }
javascript
{ "resource": "" }