_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q41400
train
function (resolved, val) { var should = (negate ? (new Assertion(val)).not : (new Assertion(val)) ); if (storedAssertions[0][0] !== 'throw' && !resolved) { throw val; } var result = storedAssertions.reduce(function (accum, cur) { // 'throw' must immediately follow 'eventually' if it is used if (cur[0] === 'throw') { // should.throw is a special case; it expects a function // that it will then call to discern whether an error was thrown // or not, but we have a (potentially) rejected value of a promise, // so we need to wrap that value in a function for should.throw to call var obj = accum.obj; accum.obj = function () { if (resolved) { return obj; } else { throw obj; } }; } // this block is separated from the above intentionally; // the above deals with putting the data in the expected format, // while this deals with whether or not to throw an error if (cur[0] === 'throw') { // these conditions are acceptable: // resolved === true && negate === true - promise succeeded, throw check is negated // resolved === false && negate !== true - promise rejected, throw check is not negated if (resolved === !!accum.negate) { caught = true; } else { throw new AssertionError({ message: 'Expected promise to be ' + (negate ? 'resolved' : 'rejected') + ' but instead it was ' + (resolved ? 'resolved' : 'rejected') + ' with ' + inspect(val), actual: val }); } } if (cur.length === 1) { // assertion was a getter, apply to current value return accum[cur[0]]; } else { // assertion was a function, apply to current value return accum[cur[0]].apply(accum, cur[1]); } }, should); // call .should on our resolved value to begin the assertion chain if (!resolved && !caught) { throw new AssertionError({ message: 'Promise was rejected unexpectedly with ' + inspect(val), actual: val }); } return result; }
javascript
{ "resource": "" }
q41401
train
function () { var self = this; $(this.scope) .on('click.fndtn.clearing', 'ul[data-clearing] li', function (e, current, target) { var current = current || $(this), target = target || current, next = current.next('li'), settings = self.get_data(current.parent()), image = $(e.target); e.preventDefault(); if (!settings) self.init(); // if clearing is open and the current image is // clicked, go to the next image in sequence if (target.hasClass('visible') && current[0] === target[0] && next.length > 0 && self.is_open(current)) { target = next; image = target.find('img'); } // set current and target to the clicked li if not otherwise defined. self.open(image, current, target); self.update_paddles(target); }) .on('click.fndtn.clearing', '.clearing-main-next', function (e) { this.nav(e, 'next') }.bind(this)) .on('click.fndtn.clearing', '.clearing-main-prev', function (e) { this.nav(e, 'prev') }.bind(this)) .on('click.fndtn.clearing', this.settings.close_selectors, function (e) { Foundation.libs.clearing.close(e, this) }) .on('keydown.fndtn.clearing', function (e) { this.keydown(e) }.bind(this)); $(window).on('resize.fndtn.clearing', function () { this.resize() }.bind(this)); this.settings.init = true; return this; }
javascript
{ "resource": "" }
q41402
Mesh
train
function Mesh(context, isStatic, numVerts, numIndices, vertexAttribs) { //TODO: use options here... if (!numVerts) throw "numVerts not specified, must be > 0"; BaseObject.call(this, context); this.gl = this.context.gl; this.numVerts = null; this.numIndices = null; this.vertices = null; this.indices = null; this.vertexBuffer = null; this.indexBuffer = null; this.verticesDirty = true; this.indicesDirty = true; this.indexUsage = null; this.vertexUsage = null; /** * @property * @private */ this._vertexAttribs = null; /** * The stride for one vertex _in bytes_. * * @property {Number} vertexStride */ this.vertexStride = null; this.numVerts = numVerts; this.numIndices = numIndices || 0; this.vertexUsage = isStatic ? this.gl.STATIC_DRAW : this.gl.DYNAMIC_DRAW; this.indexUsage = isStatic ? this.gl.STATIC_DRAW : this.gl.DYNAMIC_DRAW; this._vertexAttribs = vertexAttribs || []; this.indicesDirty = true; this.verticesDirty = true; //determine the vertex stride based on given attributes var totalNumComponents = 0; for (var i=0; i<this._vertexAttribs.length; i++) totalNumComponents += this._vertexAttribs[i].offsetCount; this.vertexStride = totalNumComponents * 4; // in bytes this.vertices = new Float32Array(this.numVerts); this.indices = new Uint16Array(this.numIndices); //add this VBO to the managed cache this.context.addManagedObject(this); this.create(); }
javascript
{ "resource": "" }
q41403
train
function() { this.gl = this.context.gl; var gl = this.gl; this.vertexBuffer = gl.createBuffer(); //ignore index buffer if we haven't specified any this.indexBuffer = this.numIndices > 0 ? gl.createBuffer() : null; this.dirty = true; }
javascript
{ "resource": "" }
q41404
train
function(shader) { var gl = this.gl; var offset = 0; var stride = this.vertexStride; //bind and update our vertex data before binding attributes this._updateBuffers(); //for each attribtue for (var i=0; i<this._vertexAttribs.length; i++) { var a = this._vertexAttribs[i]; //location of the attribute var loc = a.location === null ? shader.getAttributeLocation(a.name) : a.location; //TODO: We may want to skip unfound attribs // if (loc!==0 && !loc) // console.warn("WARN:", a.name, "is not enabled"); //first, enable the vertex array gl.enableVertexAttribArray(loc); //then specify our vertex format gl.vertexAttribPointer(loc, a.numComponents, a.type || gl.FLOAT, a.normalize, stride, offset); //and increase the offset... offset += a.offsetCount * 4; //in bytes } }
javascript
{ "resource": "" }
q41405
train
function(name, numComponents, location, type, normalize, offsetCount) { this.name = name; this.numComponents = numComponents; this.location = typeof location === "number" ? location : null; this.type = type; this.normalize = Boolean(normalize); this.offsetCount = typeof offsetCount === "number" ? offsetCount : this.numComponents; }
javascript
{ "resource": "" }
q41406
writeJSON
train
function writeJSON(file, json){ var s = file.split("."); if (s.length > 0) { var ext = s[s.length - 1]; if (ext != "json"){ file = file + ".json"; } } fs.writeFileSync(file, JSON.stringify(json)); }
javascript
{ "resource": "" }
q41407
getDirectories
train
function getDirectories(path){ return fs.readdirSync(path).filter(function (file) { return fs.statSync(path + "/" + file).isDirectory(); }); }
javascript
{ "resource": "" }
q41408
create
train
function create(options) { return knex(extend({ client: "pg", debug: debug(), connection: connection(), pool: pool() }, options)); }
javascript
{ "resource": "" }
q41409
connection
train
function connection() { return { ssl: JSON.parse(JSON.stringify(process.env.DATABASE_SSL || "")), host: process.env.DATABASE_HOST || "localhost", user: process.env.DATABASE_USER || "", charset: process.env.DATABASE_CHARSET || "utf8", password: process.env.DATABASE_PASS || "", database: process.env.DATABASE_NAME || "" }; }
javascript
{ "resource": "" }
q41410
type
train
function type (response) { return value => { if (!(value instanceof Error)) { response.setHeader( 'Content-Type', lookup(typeof value === 'object' ? 'json' : 'text') ) } return value instanceof Array ? JSON.stringify(value) : value } }
javascript
{ "resource": "" }
q41411
status
train
function status (res) { return err => { const code = err.statusCode error(res, code || 500) if (!code) console.log(err) } }
javascript
{ "resource": "" }
q41412
callbacks
train
function callbacks(err) { var fn = route.callbacks[i++]; try { if ('route' == err) { nextRoute(); } else if (err && fn) { if (fn.length < 4) return callbacks(err); fn(err, req, res, callbacks); } else if (fn) { if (fn.length < 4) return fn(req, res, callbacks); callbacks(); } else { nextRoute(err); } } catch (err) { callbacks(err); } }
javascript
{ "resource": "" }
q41413
clear
train
function clear (node) { const replace = node.cloneNode(false); node.parentNode.replaceChild(replace, node); return replace; }
javascript
{ "resource": "" }
q41414
loadHandler
train
function loadHandler (event) { const target = event.target; // change the link to the new file link.setAttribute('href', target.result); // make sure checkbox is no longer checked checkbox.checked = false; // make link not hidden link.style.display = ''; // make delete checkbox not hidden deleter.style.display = ''; // image uploaded if (file.type.match('image.*')) { // create image const image = new Image(); image.title = file.name; image.src = target.result; // replace file--link contents link = clear(link); link.appendChild(image); } else { // non-image file link.textContent = file.name; } }
javascript
{ "resource": "" }
q41415
uploadHandler
train
function uploadHandler (event) { const target = event.target; if (target.files && target.files[0]) { file = target.files[0]; const reader = new FileReader(); reader.addEventListener('load', loadHandler); reader.readAsDataURL(file); } }
javascript
{ "resource": "" }
q41416
checkboxHandler
train
function checkboxHandler (event) { const target = event.target; if (target.checked) { link.style.display = 'none'; if (upload.value) { upload.value = ''; link = clear(link); } } else { link.style.display = ''; } }
javascript
{ "resource": "" }
q41417
construct
train
function construct(data) { const basepath = process.cwd(); const files = data.map((f) => { const fullpath = p.join(basepath, f); const src = fs.readFileSync(fullpath, 'utf8'); const t = yaml.load(src, { schema: YAML_FILES_SCHEMA, filename: fullpath }); return t; }); const t = files.reduce((m, f) => merge(m, f)); return t; }
javascript
{ "resource": "" }
q41418
plugin
train
function plugin(cb) { return function(css) { if (lodash.isFunction(cb)) { var token = cb(css.source.input.file); if (!lodash.isNull(token)) { css.eachRule(function(rule) { if (!areSelectorsValid(rule.selectors, token)) { throw rule.error('Wrong selector'); } }); } } } }
javascript
{ "resource": "" }
q41419
areSelectorsValid
train
function areSelectorsValid(selectors, token) { return lodash.every(selectors, function(selector) { if (lodash.isRegExp(token)) { return token.test(lodash.trim(selector)); } else { return lodash.startsWith(lodash.trim(selector), token); } }); }
javascript
{ "resource": "" }
q41420
cleanAlphabet
train
function cleanAlphabet(alphabet) { return alphabet.split('').filter(function (item, pos, self) { return self.indexOf(item) === pos; }).join(''); }
javascript
{ "resource": "" }
q41421
generate
train
function generate(index) { return index instanceof _bigInteger2.default ? (0, _generateBigInt2.default)(index, alphabet) : (0, _generateInt2.default)(index, alphabet); }
javascript
{ "resource": "" }
q41422
number
train
function number() { const number = document.createElement('div') document.body.appendChild(number) number.innerHTML = rand(1000) number.style.fontSize = '300%' number.style.position = 'fixed' number.style.left = number.style.top = '50%' number.style.color = 'red' number.style.opacity = 1 return number }
javascript
{ "resource": "" }
q41423
train
function(message) { var pack = { toMaster: true, toWorkers: false, toSource: false, message: message, source: process.pid } dispatch(pack) }
javascript
{ "resource": "" }
q41424
train
function(pack) { if (pack.toSource !== false || pack.source !== process.pid) { CALLBACK(pack.message) } }
javascript
{ "resource": "" }
q41425
train
function(pack) { if (cluster.isMaster) { if (pack.toWorkers === true) { for (var key in cluster.workers) { cluster.workers[key].send(pack) } } } else { if (pack.toMaster === true || pack.toWorkers === true) { process.send(pack) } } }
javascript
{ "resource": "" }
q41426
train
function(process, callback) { if (callback !== undefined && typeof callback === 'function') { CALLBACK = callback } if (cluster.isMaster) { process.on('message', masterHandler) } else { process.on('message', workerHandler) } }
javascript
{ "resource": "" }
q41427
func
train
function func(declarations, functions, functionMatcher, parseArgs) { if (!declarations) return; if (false !== parseArgs) parseArgs = true; declarations.forEach(function(decl){ if ('comment' == decl.type) return; var generatedFuncs = [], result, generatedFunc; while (decl.value.match(functionMatcher)) { decl.value = decl.value.replace(functionMatcher, function(_, name, args){ if (parseArgs) { args = args.split(/\s*,\s*/).map(strip); } else { args = [strip(args)]; } // Ensure result is string result = '' + functions[name].apply(decl, args); // Prevent fall into infinite loop like this: // // { // url: function(path) { // return 'url(' + '/some/prefix' + path + ')' // } // } // generatedFunc = {from: name, to: name + getRandomString()}; result = result.replace(functionMatcherBuilder(name), generatedFunc.to + '($2)'); generatedFuncs.push(generatedFunc); return result; }); } generatedFuncs.forEach(function(func) { decl.value = decl.value.replace(func.to, func.from); }) }); }
javascript
{ "resource": "" }
q41428
error500
train
function error500(options) { options = _.merge({}, DEF_CONFIG, options); // pre-compile underscore template if available if (typeof options.template === 'string' && options.template.length > 0) { options.template = _.template(options.template); } return function (err, req, res, next) { console.error('uncaught express error:', err); DEBUG && debug(err.stack); var error = _.extend({ status: err.status || options.status, code: err.code || options.code, message: err.message || String(err), cause: err.cause }, options.mappings[err.name], options.mappings[err.code]); if (options.stack) { error.stack = (err.stack && err.stack.split('\n')) || []; } res.status(error.status); switch (req.accepts(['json', 'html'])) { case 'json': return res.json(error); case 'html': if (typeof options.template === 'function') { res.type('html'); return res.send(options.template({error: error})); } return res.render(options.view, {error: error}); } return res.send(util.inspect(error)); }; }
javascript
{ "resource": "" }
q41429
parse
train
function parse(meta) { if (typeof meta !== 'string') { throw new Error('`Parse`\'s first argument should be a string') } return meta.split(/[\r\n]/) .filter(function (line) { // remove blank line return /\S+/.test(line) && line.indexOf('==UserScript==') === -1 && line.indexOf('==/UserScript==') === -1 }) .reduce(function (obj, line) { var arr = line.trim().replace(/^\/\//, '').trim().split(/\s+/) var key = arr[0].slice(1) var value = arr.slice(1).join(' ') if (isUndefined(obj[key])) { obj[key] = value } else if (Array.isArray(obj[key])) { obj[key].push(value) } else { obj[key] = [obj[key], value] } return obj }, {}) }
javascript
{ "resource": "" }
q41430
stringify
train
function stringify(obj) { if (!isObject(obj)) { throw new Error('`Stringify`\'s first argument should be an object') } var meta = Object.keys(obj) .map(function (key) { return getLine(key, obj[key]) }).join('') return '// ==UserScript==\n' + meta + '// ==/UserScript==\n' }
javascript
{ "resource": "" }
q41431
addOutProperty
train
function addOutProperty(out, directory, extensions) { out[directory] = { extensions: extensions }; Object.defineProperty( out[directory], 'directory', { get: function () { return Config.fileLoaderDirs[directory]; }, set: function (value) { Config.fileLoaderDirs[directory] = value; }, enumerable: true, configurable: false } ); out[directory].directory = out[directory].directory || directory; }
javascript
{ "resource": "" }
q41432
arraySubtraction
train
function arraySubtraction(arrA, arrB) { arrA = arrA.slice(); for (let i = 0; i < arrB.length; ++i) { arrA = arrA.filter(function (value) { return value !== arrB[i]; }); } return arrA; }
javascript
{ "resource": "" }
q41433
getDirFromPublicPath
train
function getDirFromPublicPath(file) { return path.posix.dirname( path.posix.normalize( path.posix.sep + file.path().replace( new RegExp( '^' + escapeStringRegExp(path.resolve(Config.publicPath)) ), '' ).split(path.sep).join(path.posix.sep) ) ); }
javascript
{ "resource": "" }
q41434
replaceTplTag
train
function replaceTplTag(dirFromPublicPath, tag, replacements, templateFileLog) { let tagPath = tag.replace(new RegExp(tplTagPathRegExpStr), '$1'); let tagPathFromPublicPath = path.posix.resolve(dirFromPublicPath, tagPath); if ( tagPathFromPublicPath in replacements && replacements.hasOwnProperty(tagPathFromPublicPath) ) { let result = ( path.posix.isAbsolute(tagPath) ? replacements[tagPathFromPublicPath] : path.posix.relative( dirFromPublicPath, replacements[tagPathFromPublicPath] ) ); templateFileLog.addTemplateTagLog(tag, result); return result; } templateFileLog.addTemplateTagLog(tag); return tag; }
javascript
{ "resource": "" }
q41435
getCompiledContent
train
function getCompiledContent(file, fragments, tags, replacements, templateFileLog) { let content = ''; let fragmentStep = numberOfTplTagRegExpParts + 1; let dirFromPublicPath = getDirFromPublicPath(file); let i = 0; for (; i < tags.length; ++i) { content += fragments[i * fragmentStep]; content += replaceTplTag( dirFromPublicPath, tags[i], replacements, templateFileLog ); } content += fragments[i * fragmentStep]; return content; }
javascript
{ "resource": "" }
q41436
compileTemplate
train
function compileTemplate(file, replacements, templateFileLog) { file = File.find(path.resolve(file)); let content = file.read(); let tags = content.match(new RegExp(tplTagRegExpStr, 'g')); if (tags && tags.length) { content = getCompiledContent( file, content.split(new RegExp(tplTagRegExpStr)), tags, replacements, templateFileLog ); file.write(content); } }
javascript
{ "resource": "" }
q41437
processTemplates
train
function processTemplates(templates) { var templateProcessingLog = logger.createTemplateProcessingLog(); var replacements = Mix.manifest.get(); for (let template in templates) { if (templates.hasOwnProperty(template)) { // Copy to target fs.copySync(template, templates[template]); // Compile compileTemplate( templates[template], replacements, templateProcessingLog.addTemplateFileLog( template, templates[template] ) ); } } templateProcessingLog.print(); }
javascript
{ "resource": "" }
q41438
watchFile
train
function watchFile(file, callback) { let absolutePath = File.find(file).path(); let watcher = chokidar .watch( absolutePath, { persistent: true } ) .on( 'change', function () { if (typeof callback === 'function') { callback(file); } watcher.unwatch(absolutePath); watchFile(file, callback); } ) ; }
javascript
{ "resource": "" }
q41439
notify
train
function notify(message) { if (Mix.isUsing('notifications')) { let contentImage = path.join(__dirname, '../img/sunshine.png'); notifier.notify({ title: 'The Extension of Laravel Mix', message: message, contentImage: contentImage, icon: (os.platform() === 'win32' || os.platform() === 'linux') ? contentImage : undefined }); } }
javascript
{ "resource": "" }
q41440
TX
train
function TX(client, channel){ EE.call(this); this.client = client; this.channel = channel; this.id = channel.$getId(); return this; }
javascript
{ "resource": "" }
q41441
executeCallback
train
function executeCallback(cb, arg) { var r = cb(arg) if(r !== undefined && !isLikeAFuture(r) ) throw Error("Value returned from then or catch ("+r+") is *not* a Future. Callback: "+cb.toString()) return r }
javascript
{ "resource": "" }
q41442
batchLoop
train
function batchLoop(){ var promisesArray = createBatchJobs(); Q[qFunction](promisesArray).then(function(batchResult){ if(qFunction === "allSettled"){ batchResult = batchResult.filter(function(res){return res.state === "fulfilled"}).map(function(item){return item.value;}) } results = results.concat(batchResult); //these are upserted, let's check the next ones if(!disableLogs) { console.log("This squad is done, " + dataCopy.length + " items remaining"); } if(dataCopy.length == 0){ if(!disableLogs){ console.log("Finished the batch loop"); } deferred.resolve(results); }else{ batchLoop(); } }).catch(function(e){ if(!disableLogs) { console.error(e); } deferred.reject(results); }); }
javascript
{ "resource": "" }
q41443
createBatchJobs
train
function createBatchJobs(){ var promises = []; for(var i=0;i<squadSize && dataCopy.length > 0;i++){ var item = dataCopy.shift(); promises.push(worker(item)); } return promises; }
javascript
{ "resource": "" }
q41444
fetchAll
train
async function fetchAll(connection, query, params){ // execute query const [result] = await _query(connection, query, params); // entry found ? return result || []; }
javascript
{ "resource": "" }
q41445
analyze
train
function analyze (fileSourceData) { var analysis = new Analysis(); for (let sample of fileSourceData) { if (saysHelloWorld(sample.text)) { analysis.addError({ line: sample.line, message: 'At least try to look like you didn\'t copy the demo code!' }); } } return analysis; }
javascript
{ "resource": "" }
q41446
onMouseDown
train
function onMouseDown(event, env, isSideEffectsDisabled) { mouse.down(event, env ? env.camera : null); if (!env || isSideEffectsDisabled) { return; } if (mouse.keys[1] && !mouse.keys[3]) { let focusedObject = focusObject(env.library, env.camera, env.selector); if (env.selector.selectFocused()) { events.triggerSelect(focusedObject); } } }
javascript
{ "resource": "" }
q41447
onMouseUp
train
function onMouseUp(event, env, isSideEffectsDisabled) { mouse.up(event); if (!env || isSideEffectsDisabled) { return; } if (objectMoved) { if(env.selector.isSelectedEditable()) { events.triggerObjectChange(env.selector.getSelectedObject()); } objectMoved = false; } }
javascript
{ "resource": "" }
q41448
onMouseMove
train
function onMouseMove(event, env, isSideEffectsDisabled) { event.preventDefault(); mouse.move(event, env ? env.camera : null); if (!env || isSideEffectsDisabled) { return; } if(mouse.keys[1] && !mouse.keys[3]) { moveObject(env.library, env.camera, env.selector); } else { focusObject(env.library, env.camera, env.selector); } }
javascript
{ "resource": "" }
q41449
rotateObject
train
function rotateObject(obj, rotation, order) { let originRotation = obj.rotation.clone(); obj.rotation.setFromVector3(originRotation.toVector3().add(rotation), order); if (obj.isCollided()) { obj.rotation.setFromVector3(originRotation.toVector3(), originRotation.order); return false; } obj.updateBoundingBox(); events.triggerObjectChange(obj); return true; }
javascript
{ "resource": "" }
q41450
taskMaker
train
function taskMaker(gulp) { if (!gulp) { throw new Error('Task maker: No gulp instance provided.'); } const maker = { createTask, }; return maker; function createTask(task) { gulp.task( task.name, task.desc || false, task.fn, task.help ); return maker; } }
javascript
{ "resource": "" }
q41451
getFiles
train
function getFiles(folder = srcFolder){ let all = []; let f = fs.readdirSync(folder); for(file of f){ all.push(path.join(folder,file)) if(fs.lstatSync(path.join(folder,file)).isDirectory()){ all = all.concat(getFiles(path.join(folder,file))); } } return all; }
javascript
{ "resource": "" }
q41452
train
function(map, terms) { for (var i = 0, l = terms.length; i < l; i++) { var curTerm = terms[i]; map = map[curTerm]; if (!map || curTerm === map) { return false; // no change } else if (isString(map)) { applyChange(terms, map, i); return true; } } // if we reach this place, it is a directory applyChange(terms, map['.'] || "index.js", terms.length); return true; }
javascript
{ "resource": "" }
q41453
onConnection
train
function onConnection(socket) { var endpoint = new http2.Endpoint(log, 'SERVER', {}); endpoint.pipe(socket).pipe(endpoint); endpoint.on('stream', function(stream) { stream.on('headers', function(headers) { var path = headers[':path']; var filename = join(__dirname, path); // Serving server.js from cache. Useful for microbenchmarks. if (path == cachedUrl) { stream.headers({ ':status': 200 }); stream.end(cachedFile); } // Reading file from disk if it exists and is safe. else if ((filename.indexOf(__dirname) === 0) && exists(filename) && stat(filename).isFile()) { stream.headers({ ':status': 200 }); // If they download the certificate, push the private key too, they might need it. if (path === '/localhost.crt') { var push = stream.promise({ ':method': 'GET', ':scheme': headers[':scheme'], ':authority': headers[':authority'], ':path': '/localhost.key' }); push.headers({ ':status': 200 }); read(join(__dirname, '/localhost.key')).pipe(push); } read(filename).pipe(stream); } // Otherwise responding with 404. else { stream.headers({ ':status': 404 }); stream.end(); } }); }); }
javascript
{ "resource": "" }
q41454
train
function (device, desc) { EventEmitter.call(this); if (TRACE && DETAIL) { logger.info({ method: "UpnpService", device: device, desc: desc, }, "called"); } this.device = device; this.ok = true; this.forgotten = false try { this.serviceType = desc.serviceType[0]; this.serviceId = desc.serviceId[0]; this.controlUrl = desc.controlURL[0]; this.eventSubUrl = desc.eventSubURL[0]; this.scpdUrl = desc.SCPDURL[0]; // actions that can be performed on this service this.actions = {}; // variables that represent state on this service. this.stateVariables = {}; var u = url.parse(device.location); this.host = u.hostname; this.port = u.port; this.subscriptionTimeout = 30; // 60; } catch (x) { logger.error({ method: "UpnpService", cause: "maybe a bad UPnP response - we'll ignore this device", exception: x, device: device, desc: desc, }, "unexpected exception"); this.ok = false; return; } }
javascript
{ "resource": "" }
q41455
train
function () { var tmp = this.elements[0*4+1]; this.elements[0*4+1] = this.elements[1*4+0]; this.elements[1*4+0] = tmp; tmp = this.elements[0*4+2]; this.elements[0*4+2] = this.elements[2*4+0]; this.elements[2*4+0] = tmp; tmp = this.elements[0*4+3]; this.elements[0*4+3] = this.elements[3*4+0]; this.elements[3*4+0] = tmp; tmp = this.elements[1*4+2]; this.elements[1*4+2] = this.elements[2*4+1]; this.elements[2*4+1] = tmp; tmp = this.elements[1*4+3]; this.elements[1*4+3] = this.elements[3*4+1]; this.elements[3*4+1] = tmp; tmp = this.elements[2*4+3]; this.elements[2*4+3] = this.elements[3*4+2]; this.elements[3*4+2] = tmp; return this; }
javascript
{ "resource": "" }
q41456
train
function (node, callback) { return on.makeMultiHandle([ on(node, 'click', callback), on(node, 'keyup:Enter', callback) ]); }
javascript
{ "resource": "" }
q41457
train
function (node, callback) { // important note! // starts paused // var bHandle = on(node.ownerDocument.documentElement, 'click', function (e) { var target = e.target; if (target.nodeType !== 1) { target = target.parentNode; } if (target && !node.contains(target)) { callback(e); } }); var handle = { state: 'resumed', resume: function () { setTimeout(function () { bHandle.resume(); }, 100); this.state = 'resumed'; }, pause: function () { bHandle.pause(); this.state = 'paused'; }, remove: function () { bHandle.remove(); this.state = 'removed'; } }; handle.pause(); return handle; }
javascript
{ "resource": "" }
q41458
onDomEvent
train
function onDomEvent (node, eventName, callback) { node.addEventListener(eventName, callback, false); return { remove: function () { node.removeEventListener(eventName, callback, false); node = callback = null; this.remove = this.pause = this.resume = function () {}; }, pause: function () { node.removeEventListener(eventName, callback, false); }, resume: function () { node.addEventListener(eventName, callback, false); } }; }
javascript
{ "resource": "" }
q41459
rename
train
function rename(newName) { newName = newName.replace(/[\.\/]/g, ''); if (this.isRoot()) { this._name = newName; } else { var newPath = [this.parent.path(), newName].filter(function (e) { return e !== ''; }).join('.'); this.moveTo(newPath); } }
javascript
{ "resource": "" }
q41460
getHrefRec
train
function getHrefRec(element) { var href = element.getAttribute('href'); if (href) { return href.replace(location.origin, ''); } if (element.parentElement && element.parentElement !== document.body) { return getHrefRec(element.parentElement); } return null; }
javascript
{ "resource": "" }
q41461
_segment
train
function _segment(file) { console.log(); process.stdout.write(util.format('%s ', file)); }
javascript
{ "resource": "" }
q41462
_success
train
function _success(test, result) { process.stdout.write('.'.green); successes.push({ test: test, result: result }); }
javascript
{ "resource": "" }
q41463
_failure
train
function _failure(errors, test, result) { process.stdout.write('.'.red); failures.push({ errors: errors, test: test, result: result }); }
javascript
{ "resource": "" }
q41464
_end
train
function _end(debug) { const DEBUG_FIELDS = ['exitcode', 'output', 'stdout', 'stderr']; var summary = util.format( '%d test%s, %d success%s, %d failure%s', successes.length + failures.length, (successes.length + failures.length > 1) ? 's' : '', successes.length, (successes.length > 1) ? 'es' : '', failures.length, (failures.length > 1) ? 's' : '' ); console.log(''); if (failures.length === 0) { console.log(summary.green); } else { failures.forEach(function (failure) { console.error(util.format('' + '\n----------------' + '\n%s%s' + '\n%s', failure.test.description ? failure.test.description + '\n' : '', failure.test.file.cyan, failure.test.command)); failure.errors.forEach(function (error) { console.error(error.red); }); if (debug) { console.error('exec dir: %s\n'.grey, failure.test.dir); DEBUG_FIELDS.forEach(function (field) { if (failure.test[field]) { console.error('%s: %s\n'.grey, field, failure.result[field]); } }); } }); console.error(summary.red); } }
javascript
{ "resource": "" }
q41465
BindToEventDecorator
train
function BindToEventDecorator(_event, _target, _listenIn, _removeIn) { return function(propertyName, func) { const scope = this; const event = _event || propertyName; const target = !_target ? this.el : document.querySelector(_target); if (!target) { console.warn("Couldn't subscribe "+this.name+"."+propertyName+" to "+event+" on "+_target +" because querySelector returned undefined."); return; } const listenIn = _listenIn || "init"; const removeIn = _removeIn || "remove"; const listenFunc = this[listenIn]; const removeFunc = this[removeIn]; const boundFunc = func.bind(this); this[listenIn] = function() { if (listenFunc !== undefined) { listenFunc.apply(scope, arguments); } target.addEventListener(event, boundFunc); } this[removeIn] = function() { if (removeFunc !== undefined) { removeFunc.apply(scope, arguments); } target.removeEventListener(event, boundFunc); } return func; } }
javascript
{ "resource": "" }
q41466
checkStanza
train
function checkStanza(hubClient, stanza, fields, author, opt_sigValue) { var sig = opt_sigValue === undefined ? stanza.sig : opt_sigValue; if (!sig) { throw new errors.AuthenticationError('No `sig` field in stanza'); } if (!stanza.updatedAt || typeof(stanza.updatedAt) != 'number') { throw new errors.AuthenticationError('Invalid `updatedAt` field in stanza'); } return hubClient.getUserProfile(author, stanza.updatedAt) .then(function(userProfile) { var verifier = ursa.createVerifier('sha1'); updateWithFields(verifier, stanza, fields); var pubkeyStr = userProfile.pubkey; var pubkey = ursa.createPublicKey(pubkeyStr); var ok = verifier.verify(pubkey, stanza.sig, 'base64'); if (ok) { return true; } debug('First verification failed', author); // The signatures do not match. Refetch the author's profile directly // from the hub, then try again. if (Date.now() - userProfile.syncedAt < MIN_ENTITY_RESYNC_MS) { debug('Not refetching user profile', author); return false; } return hubClient.getUserProfileFromHub(author, stanza.updatedAt) .then(function(userProfile) { // The pubkeys are still the same, so don't bother re-checking. if (userProfile.pubkey == pubkeyStr) { debug('Pubkeys identical, not reverifying', author); return false; } // The pubkeys are different, so perhaps that's why the first check // failed. var pubkey = ursa.createPublicKey(userProfile.pubkey); return verifier.verify(userProfile.pubkey, sig, 'base64'); }) }) .catch(errors.NotFoundError, function(err) { throw new errors.AuthenticationError( 'No such user registered with the Hub: ' + author); }) .then(function(ok) { if (!ok) { throw new errors.AuthenticationError('Stanza signatures do not match for user ' + author); } return ok; }); }
javascript
{ "resource": "" }
q41467
signStanza
train
function signStanza(stanza, fields, privkey) { stanza.sig = generateStanzaSig(stanza, fields, privkey); return stanza; }
javascript
{ "resource": "" }
q41468
srcToMarkdown
train
function srcToMarkdown(src, level, threshold) { var blocks = srcToBlocks(src); return blocksToMarkdown(blocks, level, threshold); }
javascript
{ "resource": "" }
q41469
loadFile
train
function loadFile(filename, level, threshold) { var out = []; var file; out.push('<!-- BEGIN DOC-COMMENT H' + level + ' ' + filename + ' -->\n'); try { file = fs.readFileSync(filename, {encoding: 'utf-8'}); out.push(srcToMarkdown(file, level, threshold)); } catch (e) { // I don't see how we can relay this error safely } out.push('<!-- END DOC-COMMENT -->'); return out.join(''); }
javascript
{ "resource": "" }
q41470
filterDocument
train
function filterDocument(doc, threshold) { var sections = doc.split(re.mdSplit); var out = []; var i = 0; for (i = 0; i < sections.length; i++) { // 1. Raw input to preserve out.push(sections[i]); // Iterate i++; if (i >= sections.length) { break; } // 2. Header level let level = sections[i]; if (level === undefined) { level = 1; } // Iterate i++; if (i >= sections.length) { break; } // 3. File name out.push(loadFile(sections[i], level, threshold)); } return out.join(''); }
javascript
{ "resource": "" }
q41471
install
train
function install(Vue) { for (const name in components) { const component = components[name].component || components[name] Vue.component(name, component) } Vue.prototype.$actionSheet = $actionSheet Vue.prototype.$loading = $loading Vue.prototype.$toast = $toast Vue.prototype.$dialog = $dialog }
javascript
{ "resource": "" }
q41472
config
train
function config(name) { const args = [].slice.call(arguments, 1) const modules = { ActionSheet: $actionSheet, Loading: $loading, Toast: $toast, Dialog: $dialog } const module = components[name] || modules[name] if (typeof module.config === 'function') { module.config.apply(null, args) } else { console.warn(`${name}.config is not a function`) } }
javascript
{ "resource": "" }
q41473
fetchRow
train
async function fetchRow(connection, query, params){ // execute query const [result] = await _query(connection, query, params); // entry found ? if (result.length >= 1){ // extract data return result[0]; }else{ return null; } }
javascript
{ "resource": "" }
q41474
getStandardModule
train
function getStandardModule(url) { if (!(url in standardModuleCache)) { var symbol = new ModuleSymbol(null, null, null, url); var moduleInstance = traceur.runtime.modules[url]; Object.keys(moduleInstance).forEach((name) => { symbol.addExport(name, new ExportSymbol(null, name, null)); }); standardModuleCache[url] = symbol; } return standardModuleCache[url]; }
javascript
{ "resource": "" }
q41475
desc
train
function desc (array) { // Simply clone array = [].concat(array); // Ordered by version DESC array.sort(semver.rcompare); return array; }
javascript
{ "resource": "" }
q41476
scan
train
function scan(leveldb, options) { return new P(function(resolve, reject) { var datas = []; var resolved = false; function fin() { if (resolved) { return; } resolve(P.all(datas)); resolved = true; } leveldb.createReadStream(options) .on('data', function(data) { datas.push(data); }) .on('close', fin) .on('end', fin) .on('error', function(err) { reject(err); }) }); }
javascript
{ "resource": "" }
q41477
scanIndex
train
function scanIndex(leveldb, options) { return new P(function(resolve, reject) { var datas = []; var resolved = false; function fin() { if (resolved) { return; } resolve(P.all(datas)); resolved = true; } leveldb.createKeyStream(options) .on('data', function(key) { var i = key.lastIndexOf('\x00'); var key = key.substr(i + 1); datas.push(leveldb.getAsync(key)); }) .on('close', fin) .on('end', fin) .on('error', function(err) { reject(err); }) }); }
javascript
{ "resource": "" }
q41478
wafr
train
function wafr(options, callback) { const contractsPath = options.path; const optimizeCompiler = options.optimize; const sourcesExclude = options.exclude; const sourcesInclude = options.include; const focusContract = options.focus; const reportLogs = { contracts: {}, status: 'success', failure: 0, success: 0, logs: {}, }; // get allinput sources getInputSources(contractsPath, sourcesExclude, sourcesInclude, focusContract, (inputError, sources) => { if (inputError) { throwError(`while getting input sources: ${inputError}`); } // build contract sources input for compiler const compilerInput = { sources: Object.assign({ 'wafr/Test.sol': testContract }, sources), }; // compiling contracts log(`compiling contracts from ${Object.keys(sources).length} sources...`); // compile solc output (sync method) const output = solc.compile(compilerInput, optimizeCompiler); // output compiler warnings filterErrorErrors(output.errors).forEach((outputError) => { log(`while compiling contracts in path warning.. ${contractsPath}: ${outputError}`); }); // handle all compiling errors if (filterErrorWarnings(output.errors).length > 0) { output.errors.forEach((outputError) => { throwError(`while compiling contracts in path ${contractsPath}: ${outputError}`); }); } else { // compiling contracts log('contracts compiled!'); const outputContracts = contractNameProcessing(options.onlyContractName, output.contracts); // add output to report reportLogs.contracts = outputContracts; // find and build test contracts array const testContracts = buildTestContractsArray(outputContracts); const startIndex = 0; // done function const contractComplete = (contractReport) => { // if contract failed, then all tests fail if (contractReport !== false) { if (contractReport.status === 'failure') { reportLogs.status = 'failure'; reportLogs.failure += contractReport.failure; } else { reportLogs.success += contractReport.success; } } // if contract report is false, there is no more contracts to test if (contractReport === false) { // report done in log report(` ${reportLogs.failure && chalk.red(`${reportLogs.failure} not passing`) || ''} ${reportLogs.success && chalk.green(`${reportLogs.success} passing`) || ''} `); // report logs callback(null, reportLogs); } else { reportLogs.logs[contractReport.name] = contractReport; } }; // if no test contracts, end testing if (testContracts.length === 0) { contractComplete(false); } else { // test each contract sequentially testContractsSeq(startIndex, testContracts, contractComplete); } } }); }
javascript
{ "resource": "" }
q41479
parseError
train
function parseError(res, body) { // Res is optional. if (body == null) { body = res; } // Status code is required. const status = parseError.findErrorCode(sliced(arguments)); if (!status) { return false; } // Body can have an error-like object, in which case the attributes will be used. const obj = findErrorObj(body); if (obj) { body = Object.assign(body, obj); } return [status, body]; }
javascript
{ "resource": "" }
q41480
train
function (len) { _.isNumber(len) || (len = 1) while (len--) { readline.moveCursor(this.rl.output, -cliWidth(), 0) readline.clearLine(this.rl.output, 0) if (len) { readline.moveCursor(this.rl.output, 0, -1) } } return this }
javascript
{ "resource": "" }
q41481
train
function (x) { _.isNumber(x) || (x = 1) readline.moveCursor(this.rl.output, 0, -x) return this }
javascript
{ "resource": "" }
q41482
train
function () { if (!this.cursorPos) { return this } var line = this.rl._prompt + this.rl.line readline.moveCursor(this.rl.output, -line.length, 0) readline.moveCursor(this.rl.output, this.cursorPos.cols, 0) this.cursorPos = null return this }
javascript
{ "resource": "" }
q41483
random
train
function random(min, max) { var randomNumber = Math.random() * (max - min + 1) + min; if (!Number.isInteger(min) || !Number.isInteger(max)) { return randomNumber; } else { return Math.floor(randomNumber); } }
javascript
{ "resource": "" }
q41484
pidOf
train
function pidOf( procName, callback ){ if ( isString( procName )){ var pids = []; procStat( procName, function( err, processes ){ processes.object.forEach( function( proc ){ pids.push( proc.pid ) }); callback( err, pids ) }) } else callback( new Error( 'A non-string process name was supplied' ), null, null ) }
javascript
{ "resource": "" }
q41485
nameOf
train
function nameOf( pid, callback ){ if( isNumber( pid )){ procStat( pid, function( err, proc ){ callback( err, proc.object[ 0 ].name ); }) } else callback( new Error( 'A non-numeric PID was supplied' ), null ) }
javascript
{ "resource": "" }
q41486
procStat
train
function procStat( proc, callback ){ var type = isNumber( proc ) ? 'PID' : 'IMAGENAME', arg = '/fi \"' + type + ' eq ' + proc + '\" /fo CSV', row = null, processes = { array: [], object: [] }; taskList( arg, function( err, stdout ){ csv.parse( stdout, function( err, rows ){ if ( rows.length > 0 ){ for ( var i = 1; i < rows.length; i++ ){ row = rows[ i ]; processes.array.push( row ); processes.object.push({ name: row[ 0 ], pid: row[ 1 ], sessionName: row[ 2 ], sessionNumber: row[ 3 ], memUsage: row[ 4 ] }) } } else { var noun = isNumber( proc ) ? 'PIDs' : 'process names'; err = new Error( 'There were no ' + noun + ' found when searching for \"' + proc + '\"' ) } callback( err, processes ) }) }) }
javascript
{ "resource": "" }
q41487
kill
train
function kill( proc, callback ){ var arg = isNumber( proc ) ? '/F /PID ' + proc : '/F /IM ' + proc; if ( isNumber( proc ) || isString( proc )){ exec( taskKillPath + arg, function( err ){ if( callback ) callback( err ) }) } else { callback( new Error( 'The first kill() argument provided is neither a string nor an integer (not a valid process).' )) } }
javascript
{ "resource": "" }
q41488
escapeStringForJavascript
train
function escapeStringForJavascript(content) { return content.replace(/(['\\])/g, '\\$1') .replace(/[\f]/g, "\\f") .replace(/[\b]/g, "\\b") .replace(/[\n]/g, "\\n") .replace(/[\t]/g, "\\t") .replace(/[\r]/g, "\\r") .replace(/[\u2028]/g, "\\u2028") .replace(/[\u2029]/g, "\\u2029"); }
javascript
{ "resource": "" }
q41489
train
function(nga, options) { // create an admin application var app = ngAdmin.create(nga, options); // app.dashboard(nga.dashboard().template('<dashboard-page></dashboard-page>')); // create custom header if (options.auth) { app.header('<header-partial></header-partial>'); } // attach the admin application to the DOM and run it ngAdmin.attach(app); return app; }
javascript
{ "resource": "" }
q41490
Channel
train
function Channel(client, id){ EE.call(this); this.client = client; this.id = id; this.opened = false; this.confirmMode = false; var work = (id, method, err) => { this.opened = false; var error = new RabbitClientError(err); this.emit('close', error, this.id); if (error) { this.emit('error', error); this.client.channel['close-ok'](this.id, (err) => { if (err) this.emit('error', err); }); } }; var returning = (id, method, err) => { var error = new RabbitRouteError(err); this.emit('return', error, this.id); if (error) { this.emit('error', error); } }; this.client.once(this.id+':channel.close', work); this.once('close', ()=>{ this.client.removeListener(this.id+':channel.close', work); this.client.removeListener(this.id+':basic.return', returning); }); this.client.on(this.id+':basic.return', returning); }
javascript
{ "resource": "" }
q41491
train
function(uid, sid, group) { if(!uid || !sid || !group) { return false; } for(let i=0, l=group.length; i<l; i++) { if(group[i] === uid) { group.splice(i, 1); return true; } } return false; }
javascript
{ "resource": "" }
q41492
train
function(channelService, route, msg, groups, opts, cb) { let app = channelService.app; let namespace = 'sys'; let service = 'channelRemote'; let method = 'pushMessage'; let count = utils.size(groups); let successFlag = false; let failIds = []; logger.debug('[%s] channelService sendMessageByGroup route: %s, msg: %j, groups: %j, opts: %j', app.serverId, route, msg, groups, opts); if(count === 0) { // group is empty utils.invokeCallback(cb); return; } let latch = countDownLatch.createCountDownLatch(count, function() { if(!successFlag) { utils.invokeCallback(cb, new Error('all uids push message fail')); return; } utils.invokeCallback(cb, null, failIds); }); let rpcCB = function(serverId) { return function(err, fails) { if(err) { logger.error('[pushMessage] fail to dispatch msg to serverId: ' + serverId + ', err:' + err.stack); latch.done(); return; } if(fails) { failIds = failIds.concat(fails); } successFlag = true; latch.done(); }; }; opts = {type: 'push', userOptions: opts || {}}; // for compatiblity opts.isPush = true; let sendMessage = function(sid) { return (function() { if(sid === app.serverId) { channelService.channelRemote[method](route, msg, groups[sid], opts, rpcCB(sid)); } else { app.rpcInvoke(sid, {namespace: namespace, service: service, method: method, args: [route, msg, groups[sid], opts]}, rpcCB(sid)); } })(); }; let group; for(let sid in groups) { group = groups[sid]; if(group && group.length > 0) { sendMessage(sid); } else { // empty group process.nextTick(rpcCB(sid)); } } }
javascript
{ "resource": "" }
q41493
train
function () { process.stdin.resume(); process.stdin.setEncoding('utf8'); _execCtx = [self]; process.stdin.on('data', function (chunk) { var ctx = _execCtx[0], cmd = chunk.substr(0,chunk.length-1); if (cmd.substr(0,2) == '..') { cmd = 'if (_execCtx.length>1) _execCtx.shift(); undefined;' } else if (cmd.substr(0,1) == ':') { cmd = 'var newCtx = '+cmd.substr(1)+'; _execCtx.unshift(newCtx); undefined;'; } else if (cmd.substr(0,1) == '/') { cmd = ''; _execCtx = [self]; } self.exec(cmd,ctx?ctx:undefined); return false; }); }
javascript
{ "resource": "" }
q41494
train
function (serverPath) { if (!_.isString(serverPath)) return false; var _sourcePath = cwd+sourcePath, relativeSourcePath = path.relative(serverPath,_sourcePath)+'/', relativeServerPath = path.relative(cwd,serverPath); self.e.log("[*] Building new wnServer on `"+serverPath+"`"); if (!fs.existsSync(serverPath)) fs.mkdirSync(serverPath); self.e.log("[*] - Creating new `package.js` file."); var defaultPackage = fs.readFileSync(_sourcePath+'/default-package.json').toString('utf8'); defaultPackage = (defaultPackage+'').replace(/\{moduleName\}/g, 'server-'+serverPath.substr(0,serverPath.length-1).split('/').pop().replace(/\s/g,'-')); fs.writeFileSync(serverPath+'/package.json',defaultPackage); self.e.log("[*] - Creating new `config.json` file."); fs.writeFileSync(serverPath+'/config.json', fs.readFileSync(_sourcePath+'/default-config.json') ); self.e.log("[*] - Creating new `index.js` file."); var defaultIndex = fs.readFileSync(_sourcePath+'/default-index.js').toString('utf8'); defaultIndex = defaultIndex.replace(/\{sourcePath\}/g,'./'+relativeSourcePath.replace(/\\/g,'/')); defaultIndex = defaultIndex.replace(/\{serverPath\}/g,'./'+relativeServerPath.replace(/\\/g,'/')); fs.writeFileSync(serverPath+'/index.js',defaultIndex); self.e.log('[*] New wnServer created.'); return true; }
javascript
{ "resource": "" }
q41495
train
function (servers) { if (!_.isObject(servers)) return false; var modules = {}; for (s in servers) { var ref=servers[s], s = 'server-'+s; modules[s]=ref; modules[s].modulePath=(modules[s].serverPath || modules[s].modulePath); modules[s].class='wnServer'; modules[s].autoInit = false; } this.setModules(modules); }
javascript
{ "resource": "" }
q41496
train
function (id) { var m = this.getModule('server-'+id, function (server) { self.e.loadServer(server); }); _serverModules.push(m); return m; }
javascript
{ "resource": "" }
q41497
train
function (serverPath,relativeMainPath) { if (relativeMainPath) serverPath = path.relative(cwd,path.resolve(mainPath,serverPath)); var serverConfig = {}, consoleID = this.getServerModules().length+1; serverConfig[consoleID] = { 'modulePath': serverPath, 'serverID': consoleID }; this.e.log('[*] Building wnServer from `'+serverPath+'`'); if (!fs.existsSync(this.modulePath+serverPath)) { this.e.log('[*] Failed to load wnServer from path.'); return false; } this.setServers(serverConfig); var server = this.createServer(consoleID); this.selectServer(consoleID); return server; }
javascript
{ "resource": "" }
q41498
train
function (id) { if (this.hasServer(id)) { this.e.log('[*] Console active in SERVER#' + id); this.activeServer = id; } else { this.e.log('[*] Console active in NONE'); this.activeServer = -1; } }
javascript
{ "resource": "" }
q41499
train
function(app, opts) { opts = opts || {}; this.app = app; this.service = new SessionService(opts); let getFun = function(m) { return (function() { return function() { return self.service[m].apply(self.service, arguments); }; })(); }; // proxy the service methods except the lifecycle interfaces of component let method, self = this; for(let m in this.service) { if(m !== 'start' && m !== 'stop') { method = this.service[m]; if(typeof method === 'function') { this[m] = getFun(m); } } } }
javascript
{ "resource": "" }