_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q39200
parseArguments
train
function parseArguments(options, callback) { if (_.isUndefined(options) && _.isUndefined(callback)) { // No params return [{}, undefined]; } if (!_.isUndefined(options) && _.isFunction(options)) { // Only callback param callback = options; options = {}; } return [options, callback]; // Both params }
javascript
{ "resource": "" }
q39201
http
train
function http(tick, args) { let url = 'https://www.tickspot.com/' + tick.subscriptionID + '/api/v2/'; url += args.paths.join('/') + '.json'; if (args.query) { url += '?'; url += _.pairs(args.query).map(p => p.join('=')).join('&'); } return url; }
javascript
{ "resource": "" }
q39202
extractPage
train
function extractPage(options) { let page = 1; if (options && options.page) { page = options.page; delete options.page; } return page; }
javascript
{ "resource": "" }
q39203
parseCookie
train
function parseCookie(str) { var obj = {}, pairs = str.split(/[;,] */); for (var pair,eqlIndex,key,val,i=0; i < pairs.length; i++) { pair = pairs[i]; eqlIndex = pair.indexOf('='); key = pair.substr(0, eqlIndex).trim().toLowerCase(); val = pair.substr(++eqlIndex, pair.length).trim(); if ('"' === val[0]) val = val.slice(1, -1); if (obj[key] === undefined) { val = val.replace(/\+/g, ' '); try { obj[key] = decodeURIComponent(val); } catch (err) { if (err instanceof URIError) { obj[key] = val; } else { throw err; } } } } return obj; }
javascript
{ "resource": "" }
q39204
getRequestCookies
train
function getRequestCookies(req) { if (req.headers.cookie != null) { try { return parseCookie(req.headers.cookie); } catch (e) { this.log(req.urlData.pathname, "Error parsing cookie header: " + e.toString()); return {}; } } else { return {}; } }
javascript
{ "resource": "" }
q39205
train
function(a,b){ if(b[0]=="my-id") { var fakeResult = []; return fakeResult; }else return document.getElementById.apply(document,b); }
javascript
{ "resource": "" }
q39206
gitPorcelainStatus
train
function gitPorcelainStatus() { return git('status --porcelain -b', stdout => { const status = gitUtil.extractStatus(stdout); let parsedStatus = Object.values(status.index).concat(Object.values(status.workingTree)); // Flattened parsedStatus = parsedStatus.reduce((a, b) => a.concat(b), []); return { status, currentBranch: status.branch.split('...')[0], clean: parsedStatus.length === 0 }; }); }
javascript
{ "resource": "" }
q39207
train
function(args, fn, type) { this.args = args; this.fn = fn; this.type = type; this.id = prefix + _code_node_id_count++; }
javascript
{ "resource": "" }
q39208
train
function() { HelpDocument.apply(this, arguments); this.useCustom = false; this.sections = [ HelpDocument.SYNOPSIS, HelpDocument.DESCRIPTION, HelpDocument.COMMANDS, HelpDocument.OPTIONS, HelpDocument.BUGS ] }
javascript
{ "resource": "" }
q39209
clean
train
function clean (callback) { if (this._clobber) { rimraf(path.join(destination, this._clobberGlob), callback); } else { callback(null); } }
javascript
{ "resource": "" }
q39210
discover
train
function discover (callback) { glob(path.join(this._source, '/**/*.*'), function (err, filepaths) { if (err) callback(err); callback(null, filepaths); }); }
javascript
{ "resource": "" }
q39211
run
train
function run (files, callback) { let self = this, i = 0; function next(err, files) { let mw = self.middleware[i++]; if (mw) { mw(files, self, next); } else { callback(null, files); } }; next(null, files); }
javascript
{ "resource": "" }
q39212
writeFile
train
function writeFile (file, callback) { fs.outputFile(path.resolve(this._destination, path.join(file.path.dir, file.path.name + file.path.ext)), file.content, function (err) { if (err) callback(err); callback(null); }); }
javascript
{ "resource": "" }
q39213
getRootChildren
train
function getRootChildren( root, libs, com ) { var src = ( root.attribs.src || "" ).trim( ); if ( src.length > 0 ) { if (!libs.fileExists( src )) { libs.fatal( "File not found: \"" + src + "\"!" ); } // Add a compilation dependency on the include file. libs.addInclude( src ); var content = libs.readFileContent( src ); root.children = libs.parseHTML( content ); } }
javascript
{ "resource": "" }
q39214
getPropertiesAndBindings
train
function getPropertiesAndBindings( root, libs, com, indent ) { // Attributes can have post initialization, especially for data bindings. var postInit = {}; var hasPostInit = false; var key, val, values; var bindings; var slots; for ( key in root.attribs ) { if ( key.charAt( 0 ) == '$' ) { // All the attributes that start with a '$' are used as args attributes. val = root.attribs[key]; com.prop[key.substr( 1 )] = JSON.stringify( val ); } else if ( key.substr( 0, 5 ) == 'intl:' ) { // Internationalization. val = root.attribs[key]; com.prop[key.substr( 5 )] = "APP._(" + JSON.stringify( val ) + ")"; } else if ( key.substr( 0, 5 ) == 'bind:' ) { // Syntaxe : // <bind> := <bind-item> <bind-next>* // <bind-next> := "," <bind-item> // <bind-item> := <widget-name> <attribute>? <value>? // <widget-name> := /[$a-zA-Z_-][$0-9a-zA-Z_-]+/ // <attribute> := ":" <attrib-name> // <attrib-name> := /[$a-zA-Z_-][$0-9a-zA-Z_-]+/ // <value> := "=" <data> // <data> := "true" | "false" | "null" | <number> | <string> // // @example // <wdg:checkbox bind:value="btn1:action" /> // <wdg:checkbox bind:value="btn1:action, btn2, action=false" /> if ( typeof postInit[key.substr( 5 )] === 'undefined' ) { postInit[key.substr( 5 )] = {}; } postInit[key.substr( 5 )].B = parseBinding(root.attribs[key]); hasPostInit = true; } else if ( key.substr( 0, 5 ) == 'slot:' ) { // @example // <wdg:button slot:action="removeOrder" /> // <wdg:button slot:action="removeOrder, changePage" /> // <wdg:button slot:action="my-module:my-function" /> values = root.attribs[key].split( "," ); key = key.substr( 5 ); if ( typeof postInit[key] === 'undefined' ) { postInit[key] = {}; } slots = [ ]; values.forEach( function( val ) { // Before the colon (:) there is the module name. After, there // is the function name. If there is no colon, `APP` is used // as module. val = val.split( ':' ); if ( val.length < 2 ) { slots.push(val[0].trim( )); } else { slots.push(val.map( String.trim )); libs.require(val[0]); } }); postInit[key].S = slots; hasPostInit = true; } else { com.attr[key] = root.attribs[key]; } } if ( hasPostInit ) { libs.addPostInitJS( " W.bind('" + com.attr.id + "'," + JSON.stringify( postInit ) + ");" ); } }
javascript
{ "resource": "" }
q39215
Resource
train
function Resource(attributes) { this.engine = engine; this.name = !this.name ? this.name : this.name.toLowerCase(); this.queryParams = {}; this.attributes = {}; this.load(attributes || {}); }
javascript
{ "resource": "" }
q39216
daemonize
train
function daemonize(file, conf, args) { /* istanbul ignore next: never parse argv in test env */ args = args || process.argv.slice(2); args.unshift(file); var logfile = conf.get(ConfigKey.LOGFILE) || '/dev/null' //var logfile = conf.get(ConfigKey.LOGFILE) || 'daemon.log' , out = fs.openSync(logfile, 'a') , err = fs.openSync(logfile, 'a') , opts = { detached: true, stdio: ['ignore', out, err], cwd: process.cwd(), env: process.env }; //console.dir(logfile); //console.dir(args); var ps = spawn(cmd, args, opts); /* istanbul ignore next: always in test env */ if(process.env.NODE_ENV !== Constants.TEST) { process.exit(0); } return ps.pid; }
javascript
{ "resource": "" }
q39217
write
train
function write(conf) { var contents = process.pid + EOL , file = conf.get(ConfigKey.PIDFILE); // can be the empty string if(file) { try { fs.writeFileSync(file, contents); log.notice('wrote pid %s to %s', process.pid, file); }catch(e) { log.warning('failed to write pid file (%s): %s', file, e.message); } } }
javascript
{ "resource": "" }
q39218
remove
train
function remove(conf) { var file = conf.get(ConfigKey.PIDFILE); // can be the empty string if(file) { log.notice('removing pid file %s', file); try { fs.unlinkSync(file); }catch(e) { log.warning('failed to remove pid file (%s): %s', file, e.message); } } }
javascript
{ "resource": "" }
q39219
train
function(node, root) { var pn = node.parentNode; while (pn) { if (pn == root) { break; } pn = pn.parentNode; } return !!pn; }
javascript
{ "resource": "" }
q39220
train
function(node, bag) { if (!bag) { return 1; } var id = _nodeUID(node); if (!bag[id]) { return bag[id] = 1; } return 0; }
javascript
{ "resource": "" }
q39221
train
function(query, root) { // NOTE: elementsById is not currently supported // NOTE: ignores xpath-ish queries for now //Set list constructor to desired value. This can change //between calls, so always re-assign here. if (!query) { return []; } if (query.constructor == Array) { return /** @type {!Array} */ (query); } if (!goog.isString(query)) { return [query]; } if (goog.isString(root)) { root = goog.dom.getElement(root); if (!root) { return []; } } root = root || goog.dom.getDocument(); var od = root.ownerDocument || root.documentElement; // throw the big case sensitivity switch // NOTE: // Opera in XHTML mode doesn't detect case-sensitivity correctly // and it's not clear that there's any way to test for it caseSensitive = root.contentType && root.contentType == 'application/xml' || goog.userAgent.OPERA && (root.doctype || od.toString() == '[object XMLDocument]') || !!od && (goog.userAgent.IE ? od.xml : (root.xmlVersion || od.xmlVersion)); // NOTE: // adding 'true' as the 2nd argument to getQueryFunc is useful for // testing the DOM branch without worrying about the // behavior/performance of the QSA branch. var r = getQueryFunc(query)(root); // FIXME(slightlyoff): // need to investigate this branch WRT dojo:#8074 and dojo:#8075 if (r && r.nozip) { return r; } return _zip(r); }
javascript
{ "resource": "" }
q39222
Propagator
train
function Propagator( constructor, transforms, cancellable, signalCancelled) { this._constructor = constructor || promise.Promise; this._transforms = transforms; this._cancellable = cancellable === true; this._signalCancelled = signalCancelled; this._state = INITIALIZED; this._resolved = false; this._cancelled = false; this._delegatedResolve = null; this._delegatedReject = null; this._result = null; this._resultThen = null; this._handledRejection = null; this._promise = null; }
javascript
{ "resource": "" }
q39223
nodeIsRenderedByOtherInstance
train
function nodeIsRenderedByOtherInstance(container) { var rootEl = getReactRootElementInContainer(container); return !!(rootEl && isReactNode(rootEl) && !ReactDOMComponentTree.getInstanceFromNode(rootEl)); }
javascript
{ "resource": "" }
q39224
isReactNode
train
function isReactNode(node) { return isValidContainer(node) && (node.hasAttribute(ROOT_ATTR_NAME) || node.hasAttribute(ATTR_NAME)); }
javascript
{ "resource": "" }
q39225
train
function (root, className) { var all = ReactTestUtils.scryRenderedDOMComponentsWithClass(root, className); if (all.length !== 1) { throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for class:' + className); } return all[0]; }
javascript
{ "resource": "" }
q39226
train
function (root, tagName) { return ReactTestUtils.findAllInRenderedTree(root, function (inst) { return ReactTestUtils.isDOMComponent(inst) && inst.tagName.toUpperCase() === tagName.toUpperCase(); }); }
javascript
{ "resource": "" }
q39227
train
function (root, tagName) { var all = ReactTestUtils.scryRenderedDOMComponentsWithTag(root, tagName); if (all.length !== 1) { throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for tag:' + tagName); } return all[0]; }
javascript
{ "resource": "" }
q39228
train
function (root, componentType) { return ReactTestUtils.findAllInRenderedTree(root, function (inst) { return ReactTestUtils.isCompositeComponentWithType(inst, componentType); }); }
javascript
{ "resource": "" }
q39229
train
function (root, componentType) { var all = ReactTestUtils.scryRenderedComponentsWithType(root, componentType); if (all.length !== 1) { throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for componentType:' + componentType); } return all[0]; }
javascript
{ "resource": "" }
q39230
train
function (topLevelType, node, fakeNativeEvent) { fakeNativeEvent.target = node; ReactBrowserEventEmitter.ReactEventListener.dispatchEvent(topLevelType, fakeNativeEvent); }
javascript
{ "resource": "" }
q39231
matchesSelector
train
function matchesSelector(element, selector) { var matchesImpl = element.matches || element.webkitMatchesSelector || element.mozMatchesSelector || element.msMatchesSelector || function (s) { return matchesSelector_SLOW(element, s); }; return matchesImpl.call(element, selector); }
javascript
{ "resource": "" }
q39232
registerApp
train
function registerApp(name, description, permissions) { const CONNECTION = new Connection(); return new Promise((resolve, reject) => { CONNECTION.register(name, description, permissions) .then(() => resolve(new ConnectionHandler(CONNECTION))) .catch((error) => reject(error)); }); }
javascript
{ "resource": "" }
q39233
connectApp
train
function connectApp(token) { const CONNECTION = new Connection(); return new Promise((resolve, reject) => { CONNECTION.connect(token) .then(() => resolve(new ConnectionHandler(CONNECTION))) .catch((error) => reject(error)); }); }
javascript
{ "resource": "" }
q39234
train
function(options) { 'use strict'; var client = this, log = options.log, socketHost = options.socketHost, hubName = options.hubName, hub; /** * open the public/private channels to begin exchanges */ this.subscribe = function(channelName, handler, callback) { client.createHub(); if (typeof handler !== 'function') { throw new Error('must subscribe with a handler, using default...'); } log.info('open the access channel: ', channelName); hub.subscribe( channelName, handler ).then(function() { log.info('channel ', channelName, ' now alive...'); if (callback) { callback( channelName ); } }); }; /** * wrap the request message and publish to the specified channel * * @param channel - the channel name * @param id - the ssid * @param request - the message body */ this.publish = function(channel, id, request) { var message = client.wrapMessage(id, request); if (log.isDebug()) { log.debug('publish to ', channel, ', message: ', JSON.stringify( message )); } hub.publish( channel, message ); }; /** * create the message hub from socket host * * @returns the message hub */ this.createHub = function() { if (!hub) { hub = new Faye.Client( socketHost + hubName, { timeout:45 }); } return hub; }; /** * create the standard wrapper * * @param request a request object * @returns the wrapped message request */ this.wrapMessage = function(id, request) { var message = { ts:Date.now(), message:request }; if (id) { message.id = id; } return message; }; // constructor validations if (!log) throw new Error('access client must be constructed with a log'); }
javascript
{ "resource": "" }
q39235
validateCache
train
function validateCache(path, cache) { const {mtime} = fs.statSync(path); return { mtime, fromCache: Boolean(cache[path] && Sugar.Date.is(mtime, cache[path].mtime)) }; }
javascript
{ "resource": "" }
q39236
getFile
train
function getFile(path) { const cache = validateCache(path, filesCache); if (!cache.fromCache) { filesCache[path] = { mtime: cache.mtime, content: fs.readFileSync(path, 'utf-8') }; } return filesCache[path].content; }
javascript
{ "resource": "" }
q39237
BulkChange
train
function BulkChange(model) { this.model = model; this.bulk = model.collection.initializeUnorderedBulkOp(); this.isChange = false; }
javascript
{ "resource": "" }
q39238
getMediaByBuffer
train
function getMediaByBuffer (uri, cert, mode, user, safe, bufferURI) { var bufferPath = root if (bufferURI) { bufferPath += '/../' + url.parse(bufferURI).path } return new Promise(function (resolve, reject) { // var bufferPath = __dirname + '/../data/buffer/image/' debug('bufferPath', bufferPath) var files = fs.readdirSync(bufferPath) files.sort(function (a, b) { return fs.statSync(bufferPath + b).mtime.getTime() - fs.statSync(bufferPath + a).mtime.getTime() }) var file = getNextFile(files) debug('nextFile', file) if (file) { var nextFile = bufferPath + file var ret = { 'uri': nextFile, 'cacheURI': urlencode.decode(file) } // var lastFile = bufferPath + files[files.length - 1] resolve(ret) } else { reject(new Error('nothing in buffer')) } balance(user).then((ret) => { return ret }).then(function (ret) { if (ret >= algos.getRandomUnseenImage.cost) { addMediaToBuffer(uri, cert, mode, user, safe, bufferURI) } else { reject(new Error('not enough funds')) } }) }) }
javascript
{ "resource": "" }
q39239
addMediaToBuffer
train
function addMediaToBuffer (uri, cert, mode, user, safe, bufferURI) { // var bufferPath = root // if (bufferURI) { // bufferPath += '/../' + url.parse(bufferURI).path // } setTimeout(() => { try { // fs.unlinkSync(lastFile) } catch (e) { console.error(e) } var params = {} params.reviewer = user if (safe && safe === 'off') { params.safe = 0 } else { params.safe = 1 } algos.getRandomUnseenImage.function(params).then(function (row) { debug('unseen', row.ret) var cacheURI = row.ret[0][0].cacheURI var filePath = cacheURI.substr('file://'.length) debug('copying', filePath) // copyMedia(filePath, bufferPath + urlencode(cacheURI), function (err) { copyMedia(filePath, bufferURI + urlencode(cacheURI), cert, function (err) { if (err) { debug(err) } else { console.log('success!') // pay var credit = {} credit['https://w3id.org/cc#source'] = user credit['https://w3id.org/cc#amount'] = algos.getRandomUnseenImage.cost credit['https://w3id.org/cc#currency'] = 'https://w3id.org/cc#bit' credit['https://w3id.org/cc#destination'] = algos.getRandomUnseenImage.counterparty debug(credit) pay(credit) if (row && row.conn) { row.conn.close() } } }) }) }, 500) }
javascript
{ "resource": "" }
q39240
copyMedia
train
function copyMedia (path, to, cert, callback) { var hookPath = __dirname + '/../data/buffer/hook.sh' debug('copyMedia', path, to, cert) if (/^http/.test(to)) { debug('using http') var parsed = url.parse(to) debug('parsed', parsed) var domain = url.parse(to).domain var file = url.parse(to).path debug(domain, file) var a = parsed.pathname.split('/') var uri = parsed.protocol + '//' + parsed.host for (var i = 0; i < a.length - 1; i++) { uri += a[i] + '/' } uri += urlencode(a[i]) debug('uri', uri) // uri = 'https://phone.servehttp.com:8000/data/buffer/image/' + urlencode('file%3A%2F%2F%2Fmedia%2Fmelvin%2FElements%2Fpichunter.com%2F2443342_15_o.jpg') var options = { method: 'PUT', url: uri, key: fs.readFileSync(cert), cert: fs.readFileSync(cert), headers: { // We can define headers too 'Content-Type': 'image/jpg' } } debug(options) fs.createReadStream(path).pipe(request.put(options, function (err, response, body) { if (err) { debug(err) callback(err) } else { debug('success') callback(null) setTimeout(function () { exec(hookPath) }, 0) } })) } else { fs.copy(path, to, function (err) { if (err) { callback(err) } else { callback(null, null) setTimeout(function () { exec(hookPath) }, 0) } }) } }
javascript
{ "resource": "" }
q39241
getMediaByAPI
train
function getMediaByAPI (uri, cert, mode, user, safe, bufferURI) { return new Promise(function (resolve, reject) { balance(user).then((ret) => { return ret }).then(function (ret) { if (ret >= algos.getRandomUnseenImage.cost) { qpm_media.getRandomUnseenImage().then(function (row) { row.conn.close() resolve(row.ret[0][0]) // pay var credit = {} credit['https://w3id.org/cc#source'] = user credit['https://w3id.org/cc#amount'] = algos.getRandomUnseenImage.cost credit['https://w3id.org/cc#currency'] = 'https://w3id.org/cc#bit' credit['https://w3id.org/cc#destination'] = algos.getRandomUnseenImage.counterparty pay(credit) }).catch(function (err) { row.conn.close() reject(err) }) } else { reject(new Error('not enough funds')) } }) }) }
javascript
{ "resource": "" }
q39242
getMediaByHTTP
train
function getMediaByHTTP (uri, cert, mode, user, safe, bufferURI) { return new Promise(function (resolve, reject) { var cookiePath = __dirname + '/../data/cookie.json' var cookies = readCookie(cookiePath) if (cookies) { options.headers['Set-Cookie'] = 'connect.sid=' + sid + '; Path=/; HttpOnly; Secure' } var options = { url: uri, key: fs.readFileSync(cert), cert: fs.readFileSync(cert), headers: { // We can define headers too 'Accept': 'application/json' } } request.get(options, function (error, response, body) { writeCookie(response, cookiePath) if (!error && response.statusCode === 200) { json = JSON.parse(body) resolve(json) } else { reject(error) } }) }) }
javascript
{ "resource": "" }
q39243
getNextFile
train
function getNextFile (files, type) { for (var i = 0; i < files.length; i++) { var file = files[i] if (/.ttl$/.test(file)) { continue } return file } }
javascript
{ "resource": "" }
q39244
f_todo_secildi
train
function f_todo_secildi(_uyari) { l.info("f_todo_secildi"); //bu uyarı için atanmış kullanıcı id lerini çek var kullanici_idleri = f_uye_id_array(_uyari); return _uyari.RENDER.Sonuc.Data.map(function (_elm) { var detay = f_detay_olustur(schema.SABIT.UYARI.TODO, _uyari, _elm); return f_uyari_sonucu_ekle(detay) .then(function (_id) { var db_gorev = require('./db_gorev'); //eklenen uyarı sonucunu görevlere ekliyoruz return kullanici_idleri.mapX(null, db_gorev.f_db_gorev_ekle, _id).allX(); }); }) .allX(); }
javascript
{ "resource": "" }
q39245
getProp
train
function getProp (obj, path, isArray) { var next; path = _.isString(path) ? path.split('.') : path; // We have more traversing to do if (path.length > 1) { next = path.shift(); if (_.isArray(obj[next])) { isArray = true; var arr = _.compact(_.flatten(obj[next].map(function (el, i) { return getProp(el, _.clone(path), isArray); }))); return arr.length ? arr : undefined; } else { if (!obj[next]) { return; } return getProp(obj[next], path, isArray); } // No more traversing. We can now target the final node with path[0] } else { next = path[0]; // if we are at the end of the path and `obj` is an array if (_.isArray(obj)) { return _.pluck(obj, next); } else { if (!obj[next]) { return; } return isArray ? [obj[next]] : obj[next]; } } }
javascript
{ "resource": "" }
q39246
train
function () { var dest = path.join(options.dest, themes[count]); // deletes theme is already exists. if (fs.exists(dest)) { fs.rmdir(dest); } mv(path.join(options.themes, themes[count], 'dist'), dest, {mkdirp: true}, function() { buildNextTheme(); }); }
javascript
{ "resource": "" }
q39247
search
train
function search(root, expression, maxDepth) { var length = root.children.length; var depth = null; var lookingForToc = expression !== null; var map = []; var headingIndex; var closingIndex; if (!lookingForToc) { headingIndex = -1; } slugs.reset(); /* * Visit all headings in `root`. * We `slug` all headings (to account for duplicates), * but only create a TOC from top-level headings. */ visit(root, HEADING, function(child, index, parent) { var value = toString(child); var id = child.data && child.data.hProperties && child.data.hProperties.id; id = slugs.slug(id || value); if (parent !== root) { return; } if (lookingForToc) { if (isClosingHeading(child, depth)) { closingIndex = index; lookingForToc = false; } if (isOpeningHeading(child, depth, expression)) { headingIndex = index + 1; depth = child.depth; } } if (!lookingForToc && value && child.depth <= maxDepth) { child.__id__ = id; map.push({ depth: child.depth, value: value, id: id }); } }); if (headingIndex && !closingIndex) { closingIndex = length + 1; } if (headingIndex === undefined) { headingIndex = -1; closingIndex = -1; map = []; } return { index: headingIndex, endIndex: closingIndex, map: map }; }
javascript
{ "resource": "" }
q39248
colorErrors
train
function colorErrors(stdLine) { // lazy load chalk if (chalk === undefined) { chalk = require("chalk"); } return colorErrorPatterns.reduce((op, pattern) => { const matches = pattern.exec(op); if (matches !== null && matches.length > 0) { op = op.replace(pattern, chalk.red(matches[0])); } return op; }, stdLine); }
javascript
{ "resource": "" }
q39249
writeError
train
function writeError(chunk) { // in production give the output as-is if (NODE_ENV === "production") { return this.queue(chunk); } clearTimeout(errorTimer); errorChunks.push(chunk.toString()); errorTimer = setTimeout(() => { this.queue(formatErrors(errorChunks.join(""))); }, 10); }
javascript
{ "resource": "" }
q39250
respawn
train
function respawn() { if (isNil(proc) === false) { proc.stderr.removeAllListeners(); proc.stderr.end(); proc.stderr.unpipe(); proc.stdout.removeAllListeners(); proc.stdout.end(); proc.stdout.unpipe(); proc.removeAllListeners(); proc.kill(); } const { env } = process; const opts = { env }; const args = []; let cmd; // run opti-node // e.g. opti-node script.js if (exec === "") { args.push(script); } // execute something else if (exec !== "") { const [execCmd, ...execArgs] = exec .trim() .replace(leadingQuotesPattern, "") .replace(trailingQuotesPattern) .split(" "); cmd = execCmd; execArgs.forEach(item => args.push(item)); } if (isNil(cmd) === false) { // not running opti-node proc = spawn(cmd, args, opts); } else { // running with opti-node const optiNodeOpts = { args, opts }; optiNodeOpts.cmd = cmd; proc = createProcess(optiNodeOpts); } proc.addListener("close", () => watcher.emit("proc-close")); proc.addListener("disconnect", () => watcher.emit("proc-disconnect")); proc.addListener("error", err => watcher.emit("proc-error", err)); proc.addListener("exit", () => watcher.emit("proc-exit")); proc.stdout.pipe(watcher.stdout); proc.stderr.pipe(watcher.stderr); }
javascript
{ "resource": "" }
q39251
promisify
train
function promisify(data, prevent = false) { let promisified; if (typeof data === 'function') { promisified = (...args) => new Promise((resolve, reject) => { data.call(data, ...args.concat((error, ...args) => { error ? reject(error) : resolve.call(data, ...args); })); }); } else if (typeof data === 'object' && false === prevent) { promisified = new Proxy({}, { get: (target, property) => promisify(data[property], true), }); } else if (typeof data === 'string' && false === prevent) { promisified = promisify(require(data)); } else { promisified = data; } return promisified; }
javascript
{ "resource": "" }
q39252
Decoder
train
function Decoder(conf, options, file) { Transform.call(this); this._writableState.objectMode = true; this._readableState.objectMode = true; this.eol = options.eol; this.conf = conf; this.file = file; this.lineNumber = 0; }
javascript
{ "resource": "" }
q39253
_transform
train
function _transform(chunk, encoding, cb) { this.emit('lines', chunk); try { this.parse(chunk); }catch(e) { this.emit('error', e); } cb(); }
javascript
{ "resource": "" }
q39254
parse
train
function parse(lines) { var i, line, key, parts, values; for(i = 0;i < lines.length;i++) { line = lines[i]; this.lineNumber++; // ignore comments and whitespace lines if(COMMENT.test(line) || WHITESPACE.test(line)) { continue; // got something to parse }else{ // strip empty entires, leading whitespace is allowed parts = line.split(/\s+/).filter(function(p) { return p; }) // get the config key key = parts[0]; // remaining parts to parse as values values = parts.slice(1); try { this.conf.add(key, values, this.lineNumber); }catch(e) { throw new ConfigError(this.lineNumber, line, this.file, e); } } } }
javascript
{ "resource": "" }
q39255
BaseMiddleware
train
function BaseMiddleware (Model, key) { // constructor var instance = function (req, res, next) { return instance.exec()(req, res, next); }; instance.Model = Model; instance.methodChain = []; instance.__proto__ = this.__proto__; instance.setKey = function (key) { key = key || Model.modelName.toLowerCase(); instance.modelKey = inflect.singularize(key); instance.collectionKey = inflect.pluralize(key); }; instance.setKey(key); return instance; }
javascript
{ "resource": "" }
q39256
train
function (url, site, ctx, loadFunc) { return $.Deferred(function (dfd) { ctx = ctx || SP.ClientContext.get_current(); site = site || ctx.get_site(); var web = (url) ? (typeof url == "string") ? site.openWeb(url) : url : ctx.get_web(); var res = loadFunc && loadFunc(web) || ctx.load(web); ctx.executeQueryAsync( function (sender, args) { dfd.resolve(web, res, sender, args); }, function onError(sender, args) { dfd.reject({ sender: sender, args: args }); //dfd.reject('Request failed ' + args.get_message() + '\n' + args.get_stackTrace()); }); }).promise(); }
javascript
{ "resource": "" }
q39257
execute
train
function execute(req, res) { req.conn.watch(req.args, req.db); res.send(null, Constants.OK); }
javascript
{ "resource": "" }
q39258
getPlatformDetailsFromDir
train
function getPlatformDetailsFromDir(dir, platformIfKnown){ var libDir = path.resolve(dir); var platform; var version; try { var pkg = require(path.join(libDir, 'package')); platform = platformFromName(pkg.name); version = pkg.version; } catch(e) { // Older platforms didn't have package.json. platform = platformIfKnown || platformFromName(path.basename(dir)); var verFile = fs.existsSync(path.join(libDir, 'VERSION')) ? path.join(libDir, 'VERSION') : fs.existsSync(path.join(libDir, 'CordovaLib', 'VERSION')) ? path.join(libDir, 'CordovaLib', 'VERSION') : null; if (verFile) { version = fs.readFileSync(verFile, 'UTF-8').trim(); } } // if (!version || !platform || !platforms[platform]) { // return Q.reject(new CordovaError('The provided path does not seem to contain a ' + // 'Cordova platform: ' + libDir)); // } return Q({ libDir: libDir, platform: platform || platformIfKnown, version: version || '0.0.1' }); }
javascript
{ "resource": "" }
q39259
hostSupports
train
function hostSupports(platform) { var p = platforms[platform] || {}, hostos = p.hostos || null; if (!hostos) return true; if (hostos.indexOf('*') >= 0) return true; if (hostos.indexOf(process.platform) >= 0) return true; return false; }
javascript
{ "resource": "" }
q39260
mixSpecIntoComponent
train
function mixSpecIntoComponent(Constructor, spec) { if (!spec) { if (false) { var typeofSpec = typeof spec; var isMixinValid = typeofSpec === 'object' && spec !== null; process.env.NODE_ENV !== 'production' ? warning(isMixinValid, '%s: You\'re attempting to include a mixin that is either null ' + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec) : void 0; } return; } !(typeof spec !== 'function') ? false ? invariant(false, 'ReactClass: You\'re attempting to use a component class or function as a mixin. Instead, just use a regular object.') : _prodInvariant('75') : void 0; !!ReactElement.isValidElement(spec) ? false ? invariant(false, 'ReactClass: You\'re attempting to use a component as a mixin. Instead, just use a regular object.') : _prodInvariant('76') : void 0; var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. !(isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY')) ? false ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.', specPolicy, name) : _prodInvariant('77', specPolicy, name) : void 0; // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === 'DEFINE_MANY_MERGED') { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === 'DEFINE_MANY') { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if (false) { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } }
javascript
{ "resource": "" }
q39261
train
function (event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null; } if (dispatchConfig.phasedRegistrationNames !== undefined) { // pulling phasedRegistrationNames out of dispatchConfig helps Flow see // that it is not undefined. var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; for (var phase in phasedRegistrationNames) { if (!phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var pluginModule = EventPluginRegistry.registrationNameModules[phasedRegistrationNames[phase]]; if (pluginModule) { return pluginModule; } } } return null; }
javascript
{ "resource": "" }
q39262
train
function () { eventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } if (false) { var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames; for (var lowerCasedName in possibleRegistrationNames) { if (possibleRegistrationNames.hasOwnProperty(lowerCasedName)) { delete possibleRegistrationNames[lowerCasedName]; } } } }
javascript
{ "resource": "" }
q39263
asap
train
function asap(callback, context) { !batchingStrategy.isBatchingUpdates ? false ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context whereupdates are not being batched.') : _prodInvariant('125') : void 0; asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; }
javascript
{ "resource": "" }
q39264
unmountComponentFromNode
train
function unmountComponentFromNode(instance, container, safely) { if (false) { ReactInstrumentation.debugTool.onBeginFlush(); } ReactReconciler.unmountComponent(instance, safely); if (false) { ReactInstrumentation.debugTool.onEndFlush(); } if (container.nodeType === DOC_NODE_TYPE) { container = container.documentElement; } // http://jsperf.com/emptying-a-node while (container.lastChild) { container.removeChild(container.lastChild); } }
javascript
{ "resource": "" }
q39265
train
function (nextElement, container, shouldReuseMarkup, context) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. false ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !isValidContainer(container) ? false ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : _prodInvariant('37') : void 0; ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var componentInstance = instantiateReactComponent(nextElement, false); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context); var wrapperID = componentInstance._instance.rootID; instancesByReactRootID[wrapperID] = componentInstance; return componentInstance; }
javascript
{ "resource": "" }
q39266
dispatch
train
function dispatch(action) { if (!(0, _isPlainObject2['default'])(action)) { throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); } if (typeof action.type === 'undefined') { throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); } if (isDispatching) { throw new Error('Reducers may not dispatch actions.'); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) { listeners[i](); } return action; }
javascript
{ "resource": "" }
q39267
Configuration
train
function Configuration(options, parent) { options = options || {}; this.options = options; // delimiter used to split and join lines this.options.eol = options.eol || EOL; // parent reference - used by includes this._parent = parent; // file path to primary configuration file loaded this._file = null; // encapsulates the decoded data this._data = {}; // keep track of modified keys this._modified = {}; // keep track of keys that were added that were // not present when the configuration file was parsed // this will be appended on rewrite this._added = {}; // map of files that were included this._includes = {}; // current include file being processed this._include = null; // store all lines for REWRITE this._lines = []; // only the root needs defaults if(!parent) { this.set(Types.PORT, DEFAULTS.port, null, true); } }
javascript
{ "resource": "" }
q39268
get
train
function get(key, stringify) { var val = this._data[key] ? this._data[key].value : (DEFAULTS[key] !== undefined ? DEFAULTS[key] : undefined); if(val === undefined) return null; if(stringify) { val = this.encode(key, val, true); } return val; }
javascript
{ "resource": "" }
q39269
validate
train
function validate(key, values) { var typedef, value; if(!~Keys.indexOf(key)) { throw new Error('unknown configuration key: ' + key); } // retrieve the type definition typedef = Types[key]; // validate on the typedef try { value = typedef.validate(key, values); }catch(e) { // got a more specific error message to throw if(typeof validator[key] === 'object' && validator[key].error) { throw validator[key].error; } throw e; } return value; }
javascript
{ "resource": "" }
q39270
onLoad
train
function onLoad() { var k, o, v; for(k in this._data) { o = this._data[k]; v = o.value; try { this.verify(k, v); if(k === Types.SLAVEOF) { if(this.get(Types.CLUSTER_ENABLED) && v) { throw new Error('slaveof directive not allowed in cluster mode'); } } }catch(e) { //console.dir('got include error'); this.emit('error', new ConfigError( o.lineno, this._lines[o.lineno - 1] || null, this.getFile(), e)); } } }
javascript
{ "resource": "" }
q39271
set
train
function set(key, value, lineno, child) { // keys can be passed as buffers // we need a string key = '' + key; //console.error('%s=%s', key, value); var typedef = Types[key] , exists = this._data[key] , val = exists || {value: null, lineno: !child ? lineno : undefined} , changed = false; if(!lineno && !child) { changed = !exists || exists && exists.value !== value; } if(typedef && typedef.repeats) { // repeatable values always trigger a change // as they are created or appended if(!lineno && !child) changed = true; if(!exists) { val.value = [value]; this._data[key] = val; }else{ exists.value.push(value); } }else{ val.value = value; this._data[key] = val; } if(lineno === undefined && !child) { // keep track of new keys, repeatable keys that are arrays // are always appended to the end of the file if(typedef.repeats || !exists) { if(!Object.keys(this._added).length) { this._lines.push(GENERATED); } this._added[key] = value; // add a line with the encoded value this._lines.push(this.encode(key, value)); } // keep track of modified data for config rewrite (must come after added) if(exists && !this._added[key]) { this._modified[exists.lineno] = key; // line numbers are one-based but the array is zero this._lines[exists.lineno - 1] = this.encode(key, value); } } if(changed) { // emit change event with key, newval, oldval, newentry, oldentry this.emit('change', key, value, (exists ? exists.value : undefined), val, exists); // emit by key also, easier to consume this.emit(key, key, value, (exists ? exists.value : undefined), val, exists); } // merge include files synchronously // as we encounter them if(key === Types.INCLUDE && value) { this.emit('include', value, this._file, lineno); } }
javascript
{ "resource": "" }
q39272
directives
train
function directives(def) { // mock line number for error messages var lineno = 1 , k , v // inline directive, not from a file , file = 'directive override (argv)'; function addDirective(k, v) { // must be strings split into an array // they are parsed and validated v = ('' + v).split(/\s+/); // mimic behaving as a child so source file // line numbers are not overwritten try { this.add(k, v, lineno, true); }catch(e) { return this.emit('error', new ConfigError(lineno, k + ' ' + v, file, e)); } lineno++; } addDirective = addDirective.bind(this); for(k in def) { v = def[k]; if(!Array.isArray(v)) { addDirective(k, v); }else{ v.forEach(function(item) { addDirective(k, item); }) } } }
javascript
{ "resource": "" }
q39273
load
train
function load(opts, cb) { if(typeof opts === 'function') { cb = opts; opts = undefined; } if(typeof opts === 'string') { file = opts; }else if(typeof opts === 'object') { file = opts.file; } if(file === undefined) file = DEFAULT_FILE; var sync = typeof cb !== 'function' , stream , file , reader , decoder = new Decoder(this, this.options, file); if(!file || typeof file !== 'string' && !(file instanceof Readable)){ return this.emit('error', new Error('cannot load configuration, path or stream expected')); } // need absolute path to be able to // correctly find circular references if(typeof file === 'string') { file = resolve(file); } this._file = file; if(sync && file && typeof file === 'string') { this._lines = (fs.readFileSync(file) + '').split(this.options.eol); decoder.parse(this._lines); if(opts && opts.directives) { this.directives(opts.directives); } return decoder; } if(file instanceof Readable) { stream = file; }else{ /* istanbul ignore next: cannot mock stdin, readable only */ stream = opts && opts.stdin ? process.stdin : fs.createReadStream(file, this.options.read) } reader = new LineReader(this.options); this.once('load', cb); function onEnd() { if(opts && opts.directives) { this.directives(opts.directives); } decoder.removeAllListeners('error'); reader.removeAllListeners('error'); stream.removeAllListeners('error'); //console.dir(opts); // this.onLoad(); this.emit('load', this); } function onLines(lines) { this._lines = this._lines.concat(lines); } var onError = this.onError.bind(this); decoder.on('error', onError); stream.on('error', onError); reader.on('error', onError); // listen for includes this.on('include', this.onInclude.bind(this)) // listen for lines on the primary configuration. decoder.on('lines', onLines.bind(this)); stream.on('end', onEnd.bind(this)); stream.pipe(reader).pipe(decoder); return reader; }
javascript
{ "resource": "" }
q39274
write
train
function write(file, cb) { if(file === undefined) file = this._file; if(file === DEFAULT_FILE) { return this.emit( 'error', new Error('cannot write to default configuration')); } var sync = typeof cb !== 'function' , stream , save , encoder = new Encoder(this.options) , lines = this._lines , size = 32 , i = 0 , len = (lines.length / size); if(!file || typeof file !== 'string' && !(file instanceof Writable)){ return this.emit('error', new Error('cannot write configuration, path or stream expected')); } if(typeof file === 'string') { file = resolve(file); save = file + Constants.SAVE; } if(sync && file && typeof file === 'string') { try { fs.writeFileSync(save, encoder.parse(this._lines)); fs.renameSync(save, file); }catch(e) { /* istanbul ignore next: hard to mock a rename(2) error */ return this.emit('error', e); } return encoder; } if(file instanceof Writable) { stream = file; }else{ stream = fs.createWriteStream(save, this.options.read) } this.once('write', cb); function onFinish() { function onRename(err) { encoder.removeAllListeners('error'); stream.removeAllListeners('error'); /* istanbul ignore next: hard to mock a rename(2) error */ if(err) return this.emit('error', err); this.emit('write', this); } onRename = onRename.bind(this); if(save) { fs.rename(save, file, onRename); }else{ onRename(); } } var onError = this.onError.bind(this); encoder.on('error', onError); stream.on('error', onError); stream.on('finish', onFinish.bind(this)); encoder.pipe(stream); if((lines.length % size) !== 0) len++; // not a very large config if(lines.length < size) { encoder.end(lines); return encoder; } // split the work for larger config files function writeLines() { var chunk = lines.slice(i * size, (i * size) + size); // all done if(!chunk.length) { return encoder.end(); } // ensure we get correct line break between // line chunks, the encoder joins lines on EOL // this means that the last line in the chunk array // does not have an EOL, we need to ensure it does if(i > 0) { chunk.unshift(''); } // write out the line chunk encoder.write(chunk); setImmediate(writeLines); i++; } writeLines(); return encoder; }
javascript
{ "resource": "" }
q39275
writeLines
train
function writeLines() { var chunk = lines.slice(i * size, (i * size) + size); // all done if(!chunk.length) { return encoder.end(); } // ensure we get correct line break between // line chunks, the encoder joins lines on EOL // this means that the last line in the chunk array // does not have an EOL, we need to ensure it does if(i > 0) { chunk.unshift(''); } // write out the line chunk encoder.write(chunk); setImmediate(writeLines); i++; }
javascript
{ "resource": "" }
q39276
handleFailure
train
function handleFailure(err) { // Respond back to SWF failing the workflow winston.log('error', 'An problem occured in the execution of workflow: %s, failing due to: ', self.name, err.stack); decisionTask.response.fail('Workflow failed', err, function (err) { if (err) { winston.log('error', 'Unable to mark workflow: %s as failed due to: %s', self.name, JSON.stringify(err)); return; } }); }
javascript
{ "resource": "" }
q39277
handleSuccess
train
function handleSuccess() { // If any activities failed, we need to fail the workflow if (context.failed()) { winston.log('warn', 'One of more activities failed in workflow: %s, marking workflow as failed', self.name); // Respond back to SWF failing the workflow decisionTask.response.fail('Activities failed', { failures: context.errorMessages }, function (err) { if (err) { winston.log('error', 'Unable to mark workflow: %s as failed due to: %s', self.name, JSON.stringify(err)); return; } }); } else { // Check to see if we are done with the workflow if (context.done()) { winston.log('info', 'Workflow: %s has completed successfuly', self.name); // Stop the workflow decisionTask.response.stop({ result: JSON.stringify(context.results) }); } // If no decisions made this round, skip if (!decisionTask.response.decisions) { winston.log('debug', 'No decision can be made this round for workflow: %s', self.name); // Record our state when we can't make a decision to help in debugging // decisionTask.response.add_marker('current-state', JSON.stringify(context.currentStatus())); decisionTask.response.wait(); } // Respond back to SWF with all decisions decisionTask.response.respondCompleted(decisionTask.response.decisions, function (err) { if (err) { winston.log('error', 'Unable to respond to workflow: %s with decisions due to: %s', self.name, JSON.stringify(err)); return; } }); } }
javascript
{ "resource": "" }
q39278
train
function (opts) { opts = opts || {} opts = defaults(opts, { nodeModulesDir: path.resolve(process.cwd(), 'node_modules'), package: rpkg.gen(opts.package) }) fs.mkdirpSync(path.resolve(opts.nodeModulesDir, opts.package.name)) fs.writeFileSync( path.resolve(opts.nodeModulesDir, opts.package.name, 'package.json'), JSON.stringify(opts.package, null, 2) ) if (opts.targetPackage) { var key = opts.isDev ? 'devDependencies' : 'dependencies' var targetPackage = JSON.parse(fs.readFileSync(opts.targetPackage)) targetPackage[key] = targetPackage[key] || {} targetPackage[key][opts.package.name] = opts.package.version fs.writeFileSync(opts.targetPackage, JSON.stringify(targetPackage, null, 2)) } return opts.package }
javascript
{ "resource": "" }
q39279
train
function (opts) { var name if (opts && opts.name) name = opts.name if (opts && opts.package && opts.package.name) name = opts.package.name if (!name) throw new TypeError('package name missing') opts = defaults(opts, { nodeModulesDir: path.resolve(process.cwd(), 'node_modules') }) fs.removeSync(path.resolve(opts.nodeModulesDir, name)) if (opts.targetPackage) { var key = opts.isDev ? 'devDependencies' : 'dependencies' var targetPackage = JSON.parse(fs.readFileSync(opts.targetPackage)) delete targetPackage[key][name] fs.writeFileSync(opts.targetPackage, JSON.stringify(targetPackage, null, 2)) } }
javascript
{ "resource": "" }
q39280
SortedSet
train
function SortedSet(source) { HashMap.call(this); this._rtype = TYPE_NAMES.ZSET; if(source) { for(var k in source) { this.setKey(k, source[k]); } } }
javascript
{ "resource": "" }
q39281
zadd
train
function zadd(members) { var i , c = 0 , score , member; for(i = 0;i < members.length;i+=2) { score = members[i]; if(INFINITY[score] !== undefined) { score = INFINITY[score]; } member = members[i + 1]; if(this.zrank(member) === null) { c++; } // this will add or update the score this.setKey(member, score); } return c; }
javascript
{ "resource": "" }
q39282
zrem
train
function zrem(members) { var i , c = 0; for(i = 0;i < members.length;i++) { c += this.delKey(members[i]); } return c; }
javascript
{ "resource": "" }
q39283
zrank
train
function zrank(member) { if(this._data[member] === undefined) return null; for(var i = 0;i < this._keys.length;i++) { if(this.memberEqual(member, this._keys[i].m)) { return i; } } return null; }
javascript
{ "resource": "" }
q39284
zincrby
train
function zincrby(increment, member) { var score = parseFloat(this._data[member]) || 0; score += parseFloat(increment); this.setKey(member, score); return score; }
javascript
{ "resource": "" }
q39285
set
train
function set(req, res) { var key = '' + req.args[0] , value = req.args[1]; // already validated the config key/value so should be ok // to update the in-memory config, some config verification // methods perform side-effects, eg: dir this.conf.set(key, value); res.send(null, Constants.OK); if(key === ConfigKey.DIR) { this.log.notice('cwd: %s', process.cwd()); } }
javascript
{ "resource": "" }
q39286
rewrite
train
function rewrite(req, res) { /* istanbul ignore next: tough to mock fs write error */ function onError(err) { this.conf.removeAllListeners('error'); this.conf.removeAllListeners('write'); res.send(err); } function onWrite() { this.conf.removeAllListeners('error'); this.conf.removeAllListeners('write'); res.send(null, Constants.OK); } this.conf.once('error', onError.bind(this)); this.conf.write(this.conf.getFile(), onWrite.bind(this)); }
javascript
{ "resource": "" }
q39287
resetstat
train
function resetstat(req, res) { this.stats.reset(); res.send(null, Constants.OK); }
javascript
{ "resource": "" }
q39288
validate
train
function validate(cmd, args, info) { AbstractCommand.prototype.validate.apply(this, arguments); var sub = info.command.sub , cmd = '' + sub.cmd , args = sub.args , key , val , verified; if(cmd === Constants.SUBCOMMAND.config.set.name) { key = '' + args[0]; val = '' + args[1]; // test config key is allowed to be set at runtime if(!~Runtime.indexOf(key)) { throw new ConfigParameter(key); } // validate input value and coerce to native type try { val = this.conf.validate(key, [val]); // additional validation after type coercion and // basic checks, some methods modify the value (hz) // although most just throw an error verified = this.conf.verify(key, val); if(verified !== undefined) { val = verified; } args[1] = val; }catch(e) { throw new ConfigValue(key, val); } }else if(cmd === Constants.SUBCOMMAND.config.rewrite.name) { if(this.conf.isDefault()) { throw ConfigRewrite; } } }
javascript
{ "resource": "" }
q39289
registerSchema
train
function registerSchema(schema) { var typename = getTypenameFromSchemaID(schema.id); var registered_schema = tv4.getSchema(schema.id); if (registered_schema == null) { var is_draft_schema = (schema.id === exports.DRAFT_SCHEMA_ID); if (!is_draft_schema) { if (typename == null) { // error typename not available from id return false; } } else { typename = exports.DRAFT_SCHEMA_TYPENAME; } var result = tv4_validateSchema(schema); if (result.errors.length === 0) { // some docs indicate addSchema() returns boolean, but the source code returns nothing tv4.addSchema(schema); schemas[typename] = schema; return true; } else { return false; } } else { // schema is already registered, don't re-register return true; } }
javascript
{ "resource": "" }
q39290
tv4_validate
train
function tv4_validate(typename, query) { var id = getSchemaIDFromTypename(typename); var schema = tv4.getSchema(id); if (schema == null) { var error = { code: 0, message: 'Schema not found', dataPath: '', schemaPath: id }; return { valid: false, missing: [], errors: [error] }; } var report = tv4.validateMultiple(query, schema); return report; }
javascript
{ "resource": "" }
q39291
tv4_validateSchema
train
function tv4_validateSchema(schema) { var is_draft_schema = (schema.id === exports.DRAFT_SCHEMA_ID); var draft_schema = (is_draft_schema) ? schema : tv4.getSchema(exports.DRAFT_SCHEMA_ID); var report = tv4.validateMultiple(schema, draft_schema); return report; }
javascript
{ "resource": "" }
q39292
mutateJsonFile
train
function mutateJsonFile(targetPath, source, mutator) { if (!mutator) { mutator = source; source = null; } let sourceConfig = source; try { // console.log('targetPath', targetPath); let targetConfig = readJson(targetPath); // console.log('source', source); if (typeof source === 'string') { sourceConfig = readJson(source); } // console.log('sourceConfig', targetPath, sourceConfig) sourceConfig = sourceConfig ? sourceConfig : targetConfig; let newConfig = mutator(targetConfig, sourceConfig); writeJson(targetPath, newConfig, {spaces: 2}); } catch (e) { log.error('Error: operating on aurelia.json. Reverting to previous version ;{}', e); writeJson(targetPath, sourceConfig, {spaces: 2}); } }
javascript
{ "resource": "" }
q39293
detree
train
function detree(items, children, parent_id) { var item, i; for (i = 0; i < children.length; i++) { item = children[i]; if (parent_id) { item.parent = parent_id; } items.push(item); if (item.children) { detree(items, item.children, item.id); } delete item.children; } }
javascript
{ "resource": "" }
q39294
_getTags
train
function _getTags(pelem, tag, platform, transform) { var platformTag = pelem.find('./platform[@name="' + platform + '"]'); var tagsInRoot = pelem.findall(tag); tagsInRoot = tagsInRoot || []; var tagsInPlatform = platformTag ? platformTag.findall(tag) : []; var tags = tagsInRoot.concat(tagsInPlatform); if ( typeof transform === 'function' ) { tags = tags.map(transform); } return tags; }
javascript
{ "resource": "" }
q39295
hasOwnValue
train
function hasOwnValue(object, value) { assertType(object, 'object', false, 'Invalid object specified'); for (let k in object) { if (object.hasOwnProperty(k) && (object[k] === value)) return true; } return false; }
javascript
{ "resource": "" }
q39296
render
train
function render() { var framework = this._bigpipe._framework , bootstrap = this , data; data = this.keys.reduce(function reduce(memo, key) { memo[key] = bootstrap[key]; return memo; }, {}); // // Adds initial HTML headers to the queue. The first flush will // push out these headers immediately. If the render mode is sync // the headers will be injected with the other content. Since each // front-end framework might require custom bootstrapping, data is // passed to fittings, which will return valid bootstrap content. // this.debug('Queueing initial headers'); this._queue.push({ name: this.name, view: framework.get('bootstrap', { name: this.name, template: '', id: this.id, data: data, state: {} }) }); return this; }
javascript
{ "resource": "" }
q39297
contentTypeHeader
train
function contentTypeHeader(type) { if (this._res.headersSent) return this.debug( 'Headers already sent, ignoring content type change: %s', contentTypes[type] ); this.contentType = contentTypes[type]; this._res.setHeader('Content-Type', this.contentType); }
javascript
{ "resource": "" }
q39298
queue
train
function queue(name, parent, data) { this.length--; // // Object was queued, transform the response type to application/json. // if ('object' === typeof data && this._contentType !== contentTypes.json) { this.emit('contentType', 'json'); } this._queue.push({ parent: parent, name: name, view: data }); return this; }
javascript
{ "resource": "" }
q39299
join
train
function join() { var pagelet = this , result = this._queue.map(function flatten(fragment) { if (!fragment.name || !fragment.view) return ''; return fragment.view; }); try { result = this._contentType === contentTypes.json ? JSON.stringify(result.shift()) : result.join(''); } catch (error) { this.emit('done', error); return this.debug('Captured error while stringifying JSON data %s', error); } this._queue.length = 0; return result; }
javascript
{ "resource": "" }