_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q29400
train
function (key, preserveElems) { var subViews = (key && (typeof key === "string" || key.cid)) ? this.get(key) : key; var len; if (!subViews) { return this; } if (!isArray(subViews)) { subViews = [subViews]; } len = subViews ? subViews.length : 0; if (!preserveElems) { this.removeElems(subViews); } if (len) { this.trigger('remove', subViews); } while (subViews && subViews.length) { this._remove(subViews.shift()); } return this; }
javascript
{ "resource": "" }
q29401
train
function (keys, preserveElems) { var i = 0; var len = keys ? keys.length : 0; for (i; i < len; i++) { this.remove(keys[i], preserveElems); } return this; }
javascript
{ "resource": "" }
q29402
train
function (subViews) { subViews = subViews || this.subViews; var i = -1; var len = subViews.length; while (++i < len) { subViews[i].remove(); } return this; }
javascript
{ "resource": "" }
q29403
train
function (key) { if (key.cid) { return this._subViewsByCid[key.cid] || this._subViewsByModelCid[key.cid]; } if (key.indexOf('.') > -1 && this.dotNotation) { var segs = key.split('.'); var view = this.parent; while (segs.length && view) { view = view.subs.get(segs.shift()); } return view; } return this._subViewSingletons[key] || this._subViewsByCid[key] || this._subViewsByModelCid[key] || this._subViewsByType[key]; }
javascript
{ "resource": "" }
q29404
train
function (subview) { subview = (subview instanceof View === true) ? subview : this.get(subview); return subview._subviewtype; }
javascript
{ "resource": "" }
q29405
train
function (type) { var confs = type ? _.pick(this.config, type) : this.config; each(confs, function (config) { this.parent.$(config.location).html(''); }, this); return this; }
javascript
{ "resource": "" }
q29406
train
function () { var html = ''; var template = this.template; if (isFunction(template)) { html = template(result(this, 'templateVars')) || ''; } this.$el.html(html); this.subs.renderAppend(); return this; }
javascript
{ "resource": "" }
q29407
train
function (event) { var args = slice.call(arguments, 1); var stopPropogation; var anscestor; args.unshift(event); args.push(this); anscestor = this; while (anscestor) { anscestor.trigger.apply(anscestor, args); stopPropogation = anscestor._stopPropogation; if (stopPropogation && stopPropogation[event]) { stopPropogation[event] = false; return this; } anscestor = anscestor.parentView; } return this; }
javascript
{ "resource": "" }
q29408
train
function (event) { var args = slice.call(arguments, 1); var _trigger = function (subViews) { var i = -1; var len = subViews.length; var subSubs; var stopPropogation; var descend; while (++i < len) { descend = true; subViews[i].trigger.apply(subViews[i], args); stopPropogation = subViews[i]._stopPropogation; if (stopPropogation && stopPropogation[event]) { stopPropogation[event] = false; descend = false; } subSubs = subViews[i].subViews; if (descend && subSubs && subSubs.length) { _trigger(subSubs); } } }; args.unshift(event); args.push(this); _trigger([this]); return this; }
javascript
{ "resource": "" }
q29409
train
function (fnName, args) { var func; var ancestor = this; var isFunc = isFunction(fnName); while (ancestor.parentView) { ancestor = ancestor.parentView; if (ancestor) { func = isFunc ? fnName : ancestor[fnName]; func.apply(ancestor, args); } } return this; }
javascript
{ "resource": "" }
q29410
train
function (testFn) { var ancestor = this; while (ancestor.parentView) { ancestor = ancestor.parentView; if (ancestor && testFn(ancestor)) { return ancestor; } } return null; }
javascript
{ "resource": "" }
q29411
train
function (events) { events = events || result(this, 'viewEvents'); each(events, function (func, event) { var segs = event.split(' '); var listenTo = (segs.length > 1) ? this[segs[1]] : this; func = isFunction(func) ? func : this[func]; if (listenTo) { this.stopListening(listenTo, segs[0], func); this.listenTo(listenTo, segs[0], func); } }, this); return this; }
javascript
{ "resource": "" }
q29412
train
function (viewInstance) { console.assert(viewInstance instanceof Backbone.BaseView, 'viewInstance must be an instance of Backbone.BaseView'); var mixins = slice.call(arguments, 1); _marinate(viewInstance, mixins); }
javascript
{ "resource": "" }
q29413
train
function (View, name, eventsObj) { //eslint-disable-line no-shadow console.assert(View.prototype instanceof Backbone.BaseView, 'View must a Backbone.BaseView constructor'); _addEvents(View.prototype, name, eventsObj); }
javascript
{ "resource": "" }
q29414
train
function (viewInstance, name, eventsObj) { console.assert(viewInstance instanceof Backbone.BaseView, 'viewInstance must be an instance of Backbone.BaseView'); _addEvents(viewInstance, name, eventsObj); }
javascript
{ "resource": "" }
q29415
train
function(context, expression, onChange, callbackContext) { var observer = this.createObserver(expression, onChange, callbackContext || context); observer.bind(context); return observer; }
javascript
{ "resource": "" }
q29416
train
function(expression, options) { if (options && options.isSetter) { return expressions.parseSetter(expression, this.globals, this.formatters, options.extraArgs); } else if (options && options.extraArgs) { var allArgs = [expression, this.globals, this.formatters].concat(options.extraArgs); return expressions.parse.apply(expressions, allArgs); } else { return expressions.parse(expression, this.globals, this.formatters); } }
javascript
{ "resource": "" }
q29417
train
function(source, expression, value) { return this.getExpression(expression, { isSetter: true }).call(source, value); }
javascript
{ "resource": "" }
q29418
train
function(callback) { if (typeof callback === 'function') { this.afterSync(callback); } if (this.pendingSync) { return false; } var fallback = setTimeout(this.syncNow, 500); this.windows = this.windows.filter(this.removeClosed); this.pendingSync = this.windows.map(this.queueSync).concat(fallback); return true; }
javascript
{ "resource": "" }
q29419
train
function(callback) { if (typeof callback === 'function') { this.afterSync(callback); } if (this.pendingSync) { clearTimeout(this.pendingSync.pop()); this.pendingSync.forEach(this.cancelQueue); this.pendingSync = null; } if (this.syncing) { this.rerun = true; return false; } this.runSync(); return true; }
javascript
{ "resource": "" }
q29420
train
function(observer, skipUpdate) { this.observers.add(observer); if (!skipUpdate) { observer.forceUpdateNextSync = true; observer.sync(); } }
javascript
{ "resource": "" }
q29421
configure_logging
train
function configure_logging() { if ('log' in CONF) { if ('plugin' in CONF.log) { process.env.NODE_LOGGER_PLUGIN = CONF.log.plugin; } if ('level' in CONF.log) { process.env.NODE_LOGGER_LEVEL = CONF.log.level; } if ('customlevels' in CONF.log) { for (var key in CONF.log.customlevels) { process.env['NODE_LOGGER_LEVEL_' + key] = CONF.log.customlevels[key]; } } } }
javascript
{ "resource": "" }
q29422
errorMessage
train
function errorMessage(fileError) { var msg = ''; switch (fileError.code) { case FileError.NOT_FOUND_ERR: msg = 'File not found'; break; case FileError.SECURITY_ERR: // You may need the --allow-file-access-from-files flag // if you're debugging your app from file://. msg = 'Security error'; break; case FileError.ABORT_ERR: msg = 'Aborted'; break; case FileError.NOT_READABLE_ERR: msg = 'File not readable'; break; case FileError.ENCODING_ERR: msg = 'Encoding error'; break; case FileError.NO_MODIFICATION_ALLOWED_ERR: msg = 'File not modifiable'; break; case FileError.INVALID_STATE_ERR: msg = 'Invalid state'; break; case FileError.SYNTAX_ERR: msg = 'Syntax error'; break; case FileError.INVALID_MODIFICATION_ERR: msg = 'Invalid modification'; break; case FileError.QUOTA_EXCEEDED_ERR: // You may need the --allow-file-access-from-files flag // if you're debugging your app from file://. msg = 'Quota exceeded'; break; case FileError.TYPE_MISMATCH_ERR: msg = 'Type mismatch'; break; case FileError.PATH_EXISTS_ERR: msg = 'File already exists'; break; default: msg = 'Unknown FileError code (code= ' + fileError.code + ', type=' + typeof(fileError) + ')'; break; } return msg; }
javascript
{ "resource": "" }
q29423
train
function(template, delta) { assert.ok(Array.isArray(template), "'template' is not an array"); assert.ok(Array.isArray(delta), "'delta' is not an array"); /* * This merge step is inefficient O(n*m) but we are assuming small arrays * and 'delta' typically smaller than 'template'. * * A 'delta' operation could merge with another component in 'template' * with the same name, it could delete an existing entry if the 'module' * key is null, or it could insert a new entry in the array. * The insertion point of a new entry is just after the previous * operation target. If the first operation in 'delta' is a new entry it * becomes the first element. * * Note that 'delta' is not sorted and it could contain duplicates. This * allow us to change the order in the original list. For example, * if template is [A|B|...], and we want to swap B and A, we can add these * three operations in delta: * * Remove A (assign null to A's module) * Touch B (just have an entry with B's name that won't change B) * Add A with the original A's values (inserted after B) * */ var findEntry = function(result, name, lastOp) { return result.some(function(x, i) { if (x.name === name) { lastOp.index = i; return true; } else { return false; } }); }; var deleteEntry = function(result, name, lastOp) { if (findEntry(result, name, lastOp)) { result.splice(lastOp.index, 1); lastOp.index = lastOp.index -1; } }; var insertEntry = function(result, entry, lastOp) { // splice prepends, and we want after lastOp.index = lastOp.index + 1; result.splice(lastOp.index, 0, entry); }; var result = myUtils.deepClone(template); var lastOp = {index: -1}; delta.forEach(function(x) { if (x.module === null) { deleteEntry(result, x.name, lastOp); } else if (findEntry(result, x.name, lastOp)) { result[lastOp.index] = mergeObj(result[lastOp.index], x, false); } else { insertEntry(result, myUtils.deepClone(x), lastOp); } }); return result; }
javascript
{ "resource": "" }
q29424
train
function(template, delta) { assert.equal(typeof(template), 'object', "'template' is not an object"); assert.equal(typeof(delta), 'object', "'delta' is not an object"); var result = myUtils.deepClone(template); Object.keys(delta).forEach(function(x) { result[x] = myUtils.deepClone(delta[x]); }); return result; }
javascript
{ "resource": "" }
q29425
train
function(template, delta, overrideName) { if (template.name !== delta.name) { if (!overrideName) { var err = new Error('mergeObj: description names do not match'); err['template'] = template; err['delta'] = delta; throw err; } } /** @type specType*/ var result = { name: delta.name || template.name, module: (delta.module ? delta.module : template.module), description: (delta.description ? delta.description : template.description), env: mergeEnv(template.env, delta.env || {}) }; if (template.components || delta.components) { result.components = mergeComponents(template.components || [], delta.components || []); } return result; }
javascript
{ "resource": "" }
q29426
train
function(desc, f) { if (typeof desc === 'object') { f(desc.env); if (Array.isArray(desc.components)) { desc.components.forEach(function(x) { patchEnv(x, f);}); } } else { var err = new Error('patchEnv: not an object'); err['desc'] = desc; throw err; } }
javascript
{ "resource": "" }
q29427
train
function(prefix, f) { var retF = function(env) { Object.keys(env) .forEach(function(x) { var val = env[x]; if ((typeof val === 'string') && (val.indexOf(prefix) === 0)) { var propName = val.substring(prefix.length, val.length); env[x] = f(propName); } else if (Array.isArray(val)) { retF(val); } else if (val && (typeof val === 'object')) { retF(val); } }); }; return retF; }
javascript
{ "resource": "" }
q29428
getTransport
train
function getTransport(options = {}) { return new Promise((resolve, reject) => { try { const defaultTransport = { type: 'direct', transportOptions: { debug: true } }; const { transportObject = defaultTransport, } = options; const nodemailerTransporter = nodemailer.createTransport(transportMap[transportObject.type](transportObject.transportoptions)); if (transportObject.type === 'stub') { const originalSendmail = nodemailerTransporter.sendMail; nodemailerTransporter.sendMail = (data, callback) => { (function(maildata, mailcallback, fn) { return fn.call(nodemailerTransporter, maildata, function(err, email_status) { email_status.response = email_status.response.toString(); mailcallback(err, email_status); }); })(data, callback, originalSendmail); }; } nodemailerTransporter.use('compile', htmlToText()); resolve(nodemailerTransporter); } catch (e) { reject(e); } }); }
javascript
{ "resource": "" }
q29429
s_SAFE_COMPUTED_OPERANDS
train
function s_SAFE_COMPUTED_OPERANDS(node) { const operands = []; if (typeof node.computed === 'boolean' && node.computed) { // The following will pick up a single literal computed value (string). if (node.key.type === 'StringLiteral') { operands.push(TraitUtil.safeValue(node.key)); } else // Fully evaluate AST node and children for computed operands. { operands.push(...ASTGenerator.parse(node.key).operands); } } else // Parent is not computed and `parent.key` is an `Identifier` node. { operands.push(TraitUtil.safeName(node.key)); } return operands; }
javascript
{ "resource": "" }
q29430
train
function(_list){ var _result = 0; _u._$forEach( _list,function(_size){ if (!_size) return; if (!_result){ _result = _size; }else{ _result = Math.min(_result,_size); } } ); return _result; }
javascript
{ "resource": "" }
q29431
injectPaths
train
function injectPaths(paths) { u.each(paths, function(path) { if (path.inject) { // injected css and js sources are always rooted paths var src = mkSrc(path); if (/\.css$/i.test(src.path)) return opts.injectCss.push(src); if (/\.js$|\.es6$|\.jsx$/i.test(src.path)) return opts.injectJs.push(src); return opts.log('Don\'t know how to inject', path.path); } }); }
javascript
{ "resource": "" }
q29432
watchOpts
train
function watchOpts(src) { if ((src._pkg && !opts.watchPkgs) || ('watch' in src && !src.watch)) return false; return (typeof src.watch === 'object') ? src.watch : {}; }
javascript
{ "resource": "" }
q29433
normalizeOptsKey
train
function normalizeOptsKey(aval, basedir, pkg) { aval = aval || []; if (!u.isArray(aval)) { aval = [ aval ]; } return u.map(u.compact(aval), function(val) { return normalize(val, basedir, pkg); }); }
javascript
{ "resource": "" }
q29434
normalize
train
function normalize(val, basedir, pkg) { if (typeof val === 'string') { val = { path: val }; } var originalPath = val.path; // npm3 treatment of sub-package paths starting with ./node_modules/ var subPkgName = val.path.replace(/^\.\/node_modules\/([^/]+).*/,'$1'); if (subPkgName != originalPath) { var subPkg = resolvePkg({ path:subPkgName }, basedir, true); val.path = subPkg.dir + val.path.slice(15 + subPkgName.length); } // join with basedir if relative directory path else if (/^\.$|^\.\.$|^\.\/|^\.\.\//.test(val.path)) { val.path = fspath.join(basedir || opts.basedir, val.path); } // for brevity on console output val.inspect = function() { return (originalPath) + (pkg ? ' in ' + pkg : '') + (val.cache ? ' (cached)' : ''); }; if (pkg) { val._pkg = pkg; } return val; }
javascript
{ "resource": "" }
q29435
TimeoutError
train
function TimeoutError(message) { this.message = message; this.timeout = true; Error.captureStackTrace(this, arguments.callee); }
javascript
{ "resource": "" }
q29436
onFunction
train
function onFunction(data, op, iterStr, context) { var iter, data; // Check task if(!op || !data || !iterStr || !context) { throw Error('Worker received invalid task'); } // parse the serialized function // eval() may be evil but here we don't have much choice eval('var iter = ' + iterStr); switch(op) { case 'map': data = data.map(iter); break; case 'filter': data = data.filter(iter); break; default: data = null; break; } process.send({ result: data, context: context }); }
javascript
{ "resource": "" }
q29437
onExec
train
function onExec(funcStr, parStr, context) { var func, par, data, err = null; try { // Check task if(!funcStr || !context) { throw Error('Worker received invalid task'); } par = parStr ? JSON.parse(parStr) : null; // parse the serialized function // eval() may be evil but here we don't have much choice eval('var func = ' + funcStr); data = func(par); // console.log(' - '+data); } catch(e) { data = null; err = e; } process.send({ result: data, err: err, context: context }); }
javascript
{ "resource": "" }
q29438
getUserGroups
train
function getUserGroups(user) { var groups = {}; if (user && user.permissions) { user.permissions.forEach(function(permission) { var reg = new RegExp('^(get|update|delete)-group-(.+)$'); var permissionChunks = reg.exec(permission); if (permissionChunks) { var operation = permissionChunks[1]; var groupId = permissionChunks[2]; if (!groups[groupId]) groups[groupId] = []; groups[groupId].push(operation); } }); } return groups; }
javascript
{ "resource": "" }
q29439
getUserAuthorizedGroups
train
function getUserAuthorizedGroups(user, operation) { var userGroups = getUserGroups(user); var groups = []; for (var groupId in userGroups) { if (userGroups[groupId].indexOf(operation) >= 0) groups.push(groupId); } return groups; }
javascript
{ "resource": "" }
q29440
ObservableHash
train
function ObservableHash(observations) { var enabled = true; var _observers = []; _observers.enabled = true; Object.defineProperties(this, { _context: { writable: true, value: this }, _observations: { value: observations }, _namespaces: { value: [] }, _observers: { value: _observers }, computedObservers: { value: _observers } // alias to work with the computed system }); }
javascript
{ "resource": "" }
q29441
train
function() { this._observers.enabled = true; this._observers.forEach(this.observersBindHelper.bind(this), this); // Set namespaced hashes to the same value this._namespaces.forEach(this.observersStartHelper.bind(this), this); }
javascript
{ "resource": "" }
q29442
train
function(clearValues) { this._observers.enabled = false; this._observers.forEach(this.observersUnbindHelper.bind(this, clearValues)); // Set namespaced hashes to the same value this._namespaces.forEach(this.observersStopHelper.bind(this, clearValues), this); }
javascript
{ "resource": "" }
q29443
train
function(namespace, map) { if (typeof namespace === 'string' && typeof map === 'object') { if (!this[namespace]) { this[namespace] = new ObservableHash(this._observations); this[namespace].observersEnabled = this.observersEnabled; this._namespaces.push(namespace); } this._observations.computed.extend(this[namespace], map, { context: this[namespace]._context }); return this[namespace]; } else if (namespace && typeof namespace === 'object') { this._observations.computed.extend(this, namespace, { context: this._context }); return this; } else { throw new TypeError('addComputed must have a map object'); } }
javascript
{ "resource": "" }
q29444
train
function(expression, onChange, callbackContext) { var observer = this._observations.createObserver(expression, onChange, callbackContext || this); this._observers.push(observer); if (this.observersEnabled) observer.bind(this._context); return observer; }
javascript
{ "resource": "" }
q29445
resultsCallback
train
function resultsCallback() { var args = slice.call(arguments, 0); var err = args.shift(); if (err) { if (config.interrupt === true) { errors.push(err); results.push(null); callback.call(self, errors, results); return; } else { errored = true; args = null; } } else if (args.length === 0) { args = 'OK'; } else if (args.length == 1) { args = args[0]; } errors.push(err); results.push(args); self.emit('each', err, counter, args); if (config.parallel) { // Parallel if (++counter == stack.length) { self.promise.emit('finished'); } } else { // Sequential if (++counter == stack.length) { var preparedArgs = setInitialState(true); // Reset state, then return self.emit('post_exec'); callback.apply(self, preparedArgs); } else { var next = stack[counter]; context[next.caller].apply(context, next.args); } } }
javascript
{ "resource": "" }
q29446
queue
train
function queue(args) { args.push(resultsCallback); stack.push({caller: this.caller, args: args}); }
javascript
{ "resource": "" }
q29447
dummy
train
function dummy(caller) { return function() { queue.call({caller: caller}, slice.call(arguments, 0)); return self; } }
javascript
{ "resource": "" }
q29448
setInitialState
train
function setInitialState(ret) { var e, r; // Before resetting, keep a copy of args if (ret) { e = (errored ? errors : null); r = results; } // Reset runtime vars to their default state counter = 0; errored = false; errors = []; results = []; // Flush stack on first run or when config.flush is true if (stack == null || config.flush) stack = []; // Return prepared arguments if (ret) return [e, r]; }
javascript
{ "resource": "" }
q29449
train
function(_href){ // locked from history back if (!!_locked){ _locked = !1; return; } var _event = { oldValue:_location, newValue:_getLocation() }; // check ignore beforeurlchange event fire if (!!location.ignored){ location.ignored = !1; }else{ _v._$dispatchEvent( location,'beforeurlchange',_event ); if (_event.stopped){ if (!!_location){ _locked = !0; _setLocation(_location.href,!0); } return; }; } // fire urlchange _url = _ctxt.location.href; _location = _event.newValue; _v._$dispatchEvent( location,'urlchange',_location ); _h.__pushHistory(_location.href); }
javascript
{ "resource": "" }
q29450
train
function(){ var _knl = _m._$KERNEL; _ie7 = _knl.engine=='trident'&&_knl.release<='3.0'; return _isHack()&&('onhashchange' in window)&&!_ie7; }
javascript
{ "resource": "" }
q29451
tokenString
train
function tokenString(quote, f) { return function(stream, state) { var ch; if(isInString(state) && stream.current() == quote) { popStateStack(state); if(f) state.tokenize = f; return ret("string", "string"); } pushStateStack(state, { type: "string", name: quote, tokenize: tokenString(quote, f) }); // if we're in a string and in an XML block, allow an embedded code block if(stream.match("{", false) && isInXmlAttributeBlock(state)) { state.tokenize = tokenBase; return ret("string", "string"); } while (ch = stream.next()) { if (ch == quote) { popStateStack(state); if(f) state.tokenize = f; break; } else { // if we're in a string and in an XML block, allow an embedded code block in an attribute if(stream.match("{", false) && isInXmlAttributeBlock(state)) { state.tokenize = tokenBase; return ret("string", "string"); } } } return ret("string", "string"); }; }
javascript
{ "resource": "" }
q29452
tokenVariable
train
function tokenVariable(stream, state) { var isVariableChar = /[\w\$_-]/; // a variable may start with a quoted EQName so if the next character is quote, consume to the next quote if(stream.eat("\"")) { while(stream.next() !== '\"'){}; stream.eat(":"); } else { stream.eatWhile(isVariableChar); if(!stream.match(":=", false)) stream.eat(":"); } stream.eatWhile(isVariableChar); state.tokenize = tokenBase; return ret("variable", "variable"); }
javascript
{ "resource": "" }
q29453
tokenAttribute
train
function tokenAttribute(stream, state) { var ch = stream.next(); if(ch == "/" && stream.eat(">")) { if(isInXmlAttributeBlock(state)) popStateStack(state); if(isInXmlBlock(state)) popStateStack(state); return ret("tag", "tag"); } if(ch == ">") { if(isInXmlAttributeBlock(state)) popStateStack(state); return ret("tag", "tag"); } if(ch == "=") return ret("", ""); // quoted string if (ch == '"' || ch == "'") return chain(stream, state, tokenString(ch, tokenAttribute)); if(!isInXmlAttributeBlock(state)) pushStateStack(state, { type: "attribute", name: name, tokenize: tokenAttribute}); stream.eat(/[a-zA-Z_:]/); stream.eatWhile(/[-a-zA-Z0-9_:.]/); stream.eatSpace(); // the case where the attribute has not value and the tag was closed if(stream.match(">", false) || stream.match("/", false)) { popStateStack(state); state.tokenize = tokenBase; } return ret("attribute", "attribute"); }
javascript
{ "resource": "" }
q29454
train
function(tasksPerProcess) { this.ttl = tasksPerProcess; this.available = true; this.process = fork(__dirname + '/child-process.js', {silent: true}); this.reset = function() { this.process.kill('SIGKILL'); this.process = fork(__dirname + '/child-process.js', {silent: true}); this.ttl = tasksPerProcess; this.available = true; }; this.clean = function() { this.process.removeAllListeners(); this.process.stdout.removeAllListeners(); this.process.stderr.removeAllListeners(); }; this.terminate = function() { this.process.kill('SIGTERM'); }; }
javascript
{ "resource": "" }
q29455
train
function(concurrency, tasksPerProcess) { this.childs = []; for(var i = 0; i < concurrency; i += 1) { this.childs[i] = new Child(tasksPerProcess); } }
javascript
{ "resource": "" }
q29456
SQLiteHelper
train
function SQLiteHelper (schemaPath, dbPath) { let dbFilePath = dbPath, dbDirPath = path.dirname(dbFilePath), sql; /** * Saves a sql database to the disk. * * @param sql {Database} */ function saveDB (sql) { let data = sql.export(); let buffer = new Buffer(data); mkdirp.sync(dbDirPath, '0755'); fs.writeFileSync(dbFilePath, buffer); } /** * Prefixes object params with ':'. * If something other than an object is given the will be returned without being changed. * * @param params {[]|{}|string} * @returns {*} returns the updated params object */ function normalizeParams(params) { if (params && params.constructor !== Array && typeof params === 'object') { params = _.mapKeys(params, function (value, key) { return ':' + _.trimStart(key, ':'); }); } return params; } /** * Executes a command returning the results. * * @param query {string} the query string * @param params {[]|{}} the parameters to be bound to the query * @returns {[]} an array of rows */ function query (query, params) { let rows = []; let stmt = sql.prepare(query); params = normalizeParams(params); stmt.bind(params); while(stmt.step()) { rows.push(stmt.getAsObject()); } stmt.free(); return rows; } /** * Executes a command ignoring the results. * * @param query {string} the run string * @param params {[]|{}} the parameters to be bound to the query */ function run(query, params) { let stmt = sql.prepare(query); params = normalizeParams(params); stmt.run(params); stmt.free(); } if (!fs.existsSync(dbFilePath)) { let schema = fs.readFileSync(schemaPath); sql = new SQL.Database(); sql.run(schema); saveDB(sql); } else { let buffer = fs.readFileSync(dbFilePath); sql = new SQL.Database(buffer); } return {query: query, save: saveDB.bind(null, sql), run: run}; }
javascript
{ "resource": "" }
q29457
saveDB
train
function saveDB (sql) { let data = sql.export(); let buffer = new Buffer(data); mkdirp.sync(dbDirPath, '0755'); fs.writeFileSync(dbFilePath, buffer); }
javascript
{ "resource": "" }
q29458
query
train
function query (query, params) { let rows = []; let stmt = sql.prepare(query); params = normalizeParams(params); stmt.bind(params); while(stmt.step()) { rows.push(stmt.getAsObject()); } stmt.free(); return rows; }
javascript
{ "resource": "" }
q29459
run
train
function run(query, params) { let stmt = sql.prepare(query); params = normalizeParams(params); stmt.run(params); stmt.free(); }
javascript
{ "resource": "" }
q29460
validateAndCbBackend
train
function validateAndCbBackend (instance, urlPort, cb) { var backendUrl = instance.dockerUrlForPort(urlPort); var err = validateContainer(instance.attrs.container); if (err) { return cb(err); } if (!backendUrl) { err = Boom.create(400, 'port not exposed', urlPort); return cb(err); } cb(null, backendUrl); }
javascript
{ "resource": "" }
q29461
train
function () { if (!self.connections.length) { self.removeListener('remove', remove); self.closing = false; return callback(); } }
javascript
{ "resource": "" }
q29462
identifySchema
train
function identifySchema(obj) { if (obj) { const code = obj.code; const action = obj.action; const category = Dialect[action]; if (category) { if (action === 'msg' || action == 'invalid-request') { // First handle the schemas which are a category unto themselves. return category; } else if (code) { // Then handle codes. Fall through if there is a code, // but it doesn't exist for the identified category. const categoryCode = category[code]; if (categoryCode) { return categoryCode; } } else { // If there is no code, attempted to fetch the request sub-object. return category.request; } } if (code) { // If there is a code, but it wasn't associated with the identified // category (if any), then attempt to locate it in the general responses. let category = Dialect.general; if (category) { return category[code]; } } } }
javascript
{ "resource": "" }
q29463
validate
train
function validate(object, validator, callback) { if (typeof callback === 'function') { return Joi.validate(object, validator, callback); } else { return Joi.validate(object, validator); } }
javascript
{ "resource": "" }
q29464
autoValidate
train
function autoValidate(object) { const seq = (object) ? object.seq : undefined; const action = (object) ? object.action : undefined; const schema = identifySchema(object) if (schema) { const {error, value} = validate(object, schema); if (error) { return { isValid: false, seq, action, error }; } else { return { isValid: true, seq, action, value }; } } else { return { isValid: false, seq, action, error: new Error('No matching schema found.') }; } }
javascript
{ "resource": "" }
q29465
parseAndAutoValidate
train
function parseAndAutoValidate(json) { try { const obj = JSON.parse(json); return autoValidate(obj); } catch (error) { return { isValid: false, error: error }; } }
javascript
{ "resource": "" }
q29466
getDirection
train
function getDirection(position1, position2) { var _getDistanceVector2 = getDistanceVector(position1, position2), x = _getDistanceVector2.x, y = _getDistanceVector2.y; return atan2(y, x); }
javascript
{ "resource": "" }
q29467
findWord
train
function findWord(cm, lineNum, pos, dir, regexps) { var line = cm.getLine(lineNum); while (true) { var stop = (dir > 0) ? line.length : -1; var wordStart = stop, wordEnd = stop; // Find bounds of next word. for (; pos != stop; pos += dir) { for (var i = 0; i < regexps.length; ++i) { if (regexps[i].test(line.charAt(pos))) { wordStart = pos; // Advance to end of word. for (; pos != stop && regexps[i].test(line.charAt(pos)); pos += dir) {} wordEnd = (dir > 0) ? pos : pos + 1; return { from: Math.min(wordStart, wordEnd), to: Math.max(wordStart, wordEnd), line: lineNum}; } } } // Advance to next/prev line. lineNum += dir; if (!isLine(cm, lineNum)) return null; line = cm.getLine(lineNum); pos = (dir > 0) ? 0 : line.length; } }
javascript
{ "resource": "" }
q29468
textObjectManipulation
train
function textObjectManipulation(cm, object, remove, insert, inclusive) { // Object is the text object, delete object if remove is true, enter insert // mode if insert is true, inclusive is the difference between a and i var tmp = textObjects[object](cm, inclusive); var start = tmp.start; var end = tmp.end; if ((start.line > end.line) || (start.line == end.line && start.ch > end.ch)) var swap = true ; pushInBuffer(cm.getRange(swap ? end : start, swap ? start : end)); if (remove) cm.replaceRange("", swap ? end : start, swap ? start : end); if (insert) cm.setOption('keyMap', 'vim-insert'); }
javascript
{ "resource": "" }
q29469
train
function(_key,_event){ if (_event.state==0){ _doClearAction(_key); } _doStateChangeCallback(_key,_event.state); }
javascript
{ "resource": "" }
q29470
train
function() { this.handlers.push(topology.on('bindings-completed', () => { this.handle('bindings-completed'); })); this.handlers.push(connection.on('reconnected', () => { this.transition('reconnecting'); })); this.handlers.push(this.on('failed', (err) => { _.each(this.deferred, function(x) { x(err); }); this.deferred = []; })); }
javascript
{ "resource": "" }
q29471
train
function(reject) { let index = _.indexOf(this.deferred, reject); if (index >= 0) { this.deferred.splice(index, 1); } }
javascript
{ "resource": "" }
q29472
train
function() { let deferred = DeferredPromise(); logger.debug(`Destroy called on exchange ${this.name} - ${connection.name} (${this.published.count()} messages pending)`); this.handle('destroy', deferred); return deferred.promise; }
javascript
{ "resource": "" }
q29473
train
function(message) { let publishTimeout = message.timeout || options.publishTimeout || message.connectionPublishTimeout || 0; logger.silly(`Publish called in state ${this.state}`); return new Promise((resolve, reject) => { let timeout; let timedOut; if(publishTimeout > 0) { timeout = setTimeout(() => { timedOut = true; reject(new Error('Publish took longer than configured timeout')); this.removeDeferred(reject); }, publishTimeout); } const onPublished = () => { resolve(); this.removeDeferred(reject); }; const onRejected = (err) => { reject(err); this.removeDeferred(reject); }; let op = () => { if(timeout) { clearTimeout(timeout); timeout = null; } if(!timedOut) { return this.channel.publish(message) .then(onPublished, onRejected); } return Promise.resolve(); }; this.deferred.push(reject); this.handle('publish', op); }); }
javascript
{ "resource": "" }
q29474
writeProgress
train
function writeProgress(id, total, completed) { var percent = Math.round(10 * (100 * completed) / total) / 10; if(id == lastProgressId) { readline.cursorTo(process.stdout, 0); readline.clearLine(process.stdout, 0); } else { lastProgressId = id; process.stdout.write('\n'); } var progressTitles = { projects: 'Indexing Projects', chunks: 'Indexing Chunks', ta: 'Indexing translationAcademy', resources: 'Indexing Resources', container: 'Downloading Containers', catalog: 'Indexing Catalogs', langnames: 'Indexing Target Languages', 'temp-langnames': 'Indexing Temporary Target Languages', 'approved-temp-langnames': 'Indexing Approved Temporary Target Languages', 'new-language-questions': 'Indexing Questionnaire' }; process.stdout.write((progressTitles[id] || id) + ' [' + total + '] ' + percent + '%'); }
javascript
{ "resource": "" }
q29475
condition
train
function condition(file){ var suffix = file.path.substr(file.base.length); var re = new RegExp(specialChars); var flag = service === "hosting" && re.test(suffix); var warning = "Warning: Cannot sync files with characters: " + specialChars + " in the file name: "; if (flag){ var message = warning + suffix; console.log(message.red); } return flag; }
javascript
{ "resource": "" }
q29476
PersonCommunications
train
function PersonCommunications (f1, personID) { if (!personID) { throw new Error('PersonCommunications requires a person ID!') } Communications.call(this, f1, { path: '/People/' + personID + '/Communications' }) }
javascript
{ "resource": "" }
q29477
init
train
function init (router) { router.use((err, req, res, next) => { console.error(err.stack || err.message) res.statusCode = err.statusCode || 500 res.end() }) }
javascript
{ "resource": "" }
q29478
train
function(table, params, unique) { unique = unique || []; let columns = _.keys(params); let whereStatements = _.map(unique, function(c) { return c + '=:' + c}); let updatedColumns = _.map(_.filter(columns, function(c) { return unique.indexOf(c) }), function(c) { return c + '=:' + c }); let insertHolders = _.map(columns, function(k) { return ':' + k; }); run('insert or ignore into ' + table + ' (' + columns.join(', ') + ') values (' + insertHolders.join(', ') + ')', params); run('update or fail ' + table + ' set ' + updatedColumns.join(', ') + ' where ' + whereStatements.join(' and '), params); save(); // TRICKY: in this module we are strictly dealing with inserts or *full* updates. // Therefore we can rely on the existence of the unique columns to retrieve the id let result = query('select id from ' + table + ' where ' + whereStatements.join(' and ') + ' order by id asc limit 1', params); return firstId(result); }
javascript
{ "resource": "" }
q29479
train
function(obj, required_props) { if(typeof obj === 'object') { required_props = required_props || Object.keys(obj); for (let prop of required_props) { if (obj[prop] === undefined || obj[prop] === null || obj[prop] === '') { throw new Error('Missing required property "' + prop + '"'); } } } else if(required_props && required_props.length > 0) { throw new Error('Missing required property "' + required_props + '"'); } else if(obj === undefined || obj === null || obj === '') { throw new Error('The value cannot be empty'); } }
javascript
{ "resource": "" }
q29480
train
function() { let resultLangCount = query('select count(*) as count from target_language'); let resultResLvl3Count = query('select count(*) as count from resource where checking_level >= 3'); let resultResCount = query('select count(*) as count from resource'); let resultProjCount = query('select count(*) as count from (select id from project group by slug)'); return { resource_count_level3:resultResLvl3Count[0]['count'], resource_count:resultResCount[0]['count'], target_language_count:resultLangCount[0]['count'], project_count:resultProjCount[0]['count'] }; }
javascript
{ "resource": "" }
q29481
train
function(temp_target_language_slug) { let result = query('select tl.* from target_language as tl' + ' left join temp_target_language as ttl on ttl.approved_target_language_slug=tl.slug' + ' where ttl.slug=?', [temp_target_language_slug]); if(result.length > 0) { delete result[0].id; return result[0]; } return null; }
javascript
{ "resource": "" }
q29482
train
function(languageSlug, projectSlug) { // support passing args as an object if(languageSlug != null && typeof languageSlug == 'object') { projectSlug = languageSlug.projectSlug; languageSlug = languageSlug.languageSlug; } let result = query('select p.*, c.slug as category_slug from project as p' + ' left join category as c on c.id=p.category_id' + ' where p.slug=? and p.source_language_id in (' + ' select id from source_language where slug=?)' + ' limit 1', [projectSlug, languageSlug]); if(result.length > 0) { // store the language slug for convenience result[0].source_language_slug = languageSlug; return result[0]; } return null; }
javascript
{ "resource": "" }
q29483
train
function(languageSlug) { let result; if(languageSlug) { result = query('select p.*, c.slug as category_slug from project as p' + ' left join category as c on c.id=p.category_id' + ' where p.source_language_id in (select id from source_language where slug=?)' + ' order by p.sort asc', [languageSlug]); } else { result = query('select * from project' + ' group by slug order by sort asc'); } for(let project of result) { // store the language slug for convenience project.source_language_slug = languageSlug; } return result; }
javascript
{ "resource": "" }
q29484
train
function(parentCategoryId, languageSlug, translateMode) { let preferredSlug = [languageSlug, 'en', '%']; let categories = []; if(translateMode) { categories = query('select \'category\' as type, c.slug as name, \'\' as source_language_slug,' + ' c.id, c.slug, c.parent_id, count(p.id) as num from category as c' + ' left join (' + ' select p.id, p.category_id, count(r.id) as num from project as p' + ' left join resource as r on r.project_id=p.id and r.translate_mode like(?)' + ' group by p.slug' + ' ) p on p.category_id=c.id and p.num > 0' + ' where parent_id=? and num > 0 group by c.slug', [translateMode, parentCategoryId]); } else { categories = query('select \'category\' as type, category.slug as name, \'\' as source_language_slug, * from category where parent_id=?', [parentCategoryId]); } // find best name let catNameQuery = 'select sl.slug as source_language_slug, cn.name as name' + ' from category_name as cn' + ' left join source_language as sl on sl.id=cn.source_language_id' + ' where sl.slug like(?) and cn.category_id=?'; for(let cat of categories) { for(let slug of preferredSlug) { let result = query(catNameQuery, [slug, cat.id]); if(result.length > 0) { cat.name = result[0]['name']; cat.source_language_slug = result[0]['source_language_slug']; break; } } } let projects = query('select * from (' + ' select \'project\' as type, \'\' as source_language_slug,' + ' p.id, p.slug, p.sort, p.name, count(r.id) as num from project as p' + ' left join resource as r on r.project_id=p.id and r.translate_mode like (?)' + ' where p.category_id=? group by p.slug' + ')' + (translateMode ? ' where num > 0' : ''), [translateMode || '%', parentCategoryId]); // find best name let projNameQuery = 'select sl.slug as source_language_slug, p.name as name' + ' from project as p' + ' left join source_language as sl on sl.id=p.source_language_id' + ' where sl.slug like(?) and p.slug=? order by sl.slug asc'; for(let proj of projects) { for(let slug of preferredSlug) { let result = query(projNameQuery, [slug, proj.slug]); if(result.length > 0) { proj.name = result[0]['name']; proj.source_language_slug = result[0]['source_language_slug']; break; } } } return categories.concat(projects); }
javascript
{ "resource": "" }
q29485
train
function(languageSlug, projectSlug, resourceSlug) { let result = query('select r.*, lri.translation_words_assignments_url from resource as r' + ' left join legacy_resource_info as lri on lri.resource_id=r.id' + ' where r.slug=? and r.project_id in (' + ' select id from project where slug=? and source_language_id in (' + ' select id from source_language where slug=?)' + ' )' + ' limit 1', [resourceSlug, projectSlug, languageSlug]); if(result.length > 0) { let res = result[0]; // organize the status res.status = { translate_mode: res.translate_mode, checking_level: res.checking_level, comments: res.comments, pub_date: res.pub_date, license: res.license, version: res.version }; delete res.translate_mode; delete res.checking_level; delete res.comments; delete res.pub_date; delete res.license; delete res.version; // store language and project slug for convenience res.source_language_slug = languageSlug; res.project_slug = projectSlug; // get formats res.formats = []; let formatResults = query('select * from resource_format' + ' where resource_id=?', [res.id]); res.imported = false; for(let format of formatResults) { delete format.id; delete format.resource_id; format.imported = !!format.imported; res.formats.push(format); // TRICKY: this is not technically correct, but for convenience we attach the import status to the resource directly if(format.imported) res.imported = true; } return res; } return null; }
javascript
{ "resource": "" }
q29486
train
function(languageSlug, versificationSlug) { let result = query('' + 'select vn.name, v.slug, v.id from versification_name as vn' + ' left join versification as v on v.id=vn.versification_id' + ' left join source_language as sl on sl.id=vn.source_language_id' + ' where sl.slug=? and v.slug=?', [languageSlug, versificationSlug]); if(result.length > 0) { return result[0]; } return null; }
javascript
{ "resource": "" }
q29487
train
function(tdId) { let result = query('select * from questionnaire where td_id=?', [tdId]); if(result.length > 0) { let questionnaire = result[0]; questionnaire.language_data = {}; // load data fields let dataResults = query('select field, question_td_id from questionnaire_data_field where questionnaire_id=?', [questionnaire.id]); for(let data of dataResults) { questionnaire.language_data[data.field] = data.question_td_id; } return questionnaire; } return null; }
javascript
{ "resource": "" }
q29488
train
function() { let results = query('select * from questionnaire'); for(let questionnaire of results) { // load data fields questionnaire.language_data = {}; let dataResults = query('select field, question_td_id from questionnaire_data_field where questionnaire_id=?', [questionnaire.id]); for(let data of dataResults) { questionnaire.language_data[data.field] = data.question_td_id; } } return results; }
javascript
{ "resource": "" }
q29489
train
function(language_slug, project_slug, resource_slug, resource_type, translate_mode, min_checking_level, max_checking_level) { let condition_max_checking = ''; language_slug = language_slug || '%'; project_slug = project_slug || '%'; resource_slug = resource_slug || '%'; resource_type = resource_type || '%'; translate_mode = translate_mode || '%'; min_checking_level = min_checking_level || 0; max_checking_level = max_checking_level || -1; if(max_checking_level >= 0) condition_max_checking = ' and r.checking_level <= ' + max_checking_level; let translations = []; let results = query("select l.slug as language_slug, l.name as language_name, l.direction," + " p.slug as project_slug, p.category_id, p.name as project_name, p.desc, p.icon, p.sort, p.chunks_url," + " r.id as resource_id, r.slug as resource_slug, r.name as resource_name, r.type, r.translate_mode, r.checking_level, r.comments, r.pub_date, r.license, r.version," + " lri.translation_words_assignments_url," + " c.slug as category_slug " + " from source_language as l" + " left join project as p on p.source_language_id=l.id" + " left join resource as r on r.project_id=p.id" + " left join legacy_resource_info as lri on lri.resource_id=r.id" + " left join category as c on c.id=p.category_id" + " where l.slug like(?) and p.slug like(?) and r.slug like(?)" + " and r.checking_level >= ?" + condition_max_checking + " and r.type like(?) and r.translate_mode like(?)", [language_slug, project_slug, resource_slug, min_checking_level, resource_type, translate_mode]); for(let r of results) { let trans = { language: { slug: r.language_slug, name: r.language_name, direction: r.direction }, project: { slug: r.project_slug, name: r.project_name, desc: r.desc, sort: r.sort, icon: r.icon, chunks_url: r.chunks_url, source_language_slug: r.language_slug, category_id: r.category_id, category_slug: r.category_slug }, resource: { slug: r.resource_slug, name: r.resource_name, type: r.type, status: { translate_mode: r.translate_mode, checking_level: r.checking_level, comments: r.comments, pub_date: r.pub_date, license: r.license, version: r.version }, project_slug: r.project_slug, source_language_slug: r.language_slug } }; // load formats and add to resource let formats = []; let formatResults = query('select * from resource_format' + ' where resource_id=?', [r.resource_id]); let imported = false; for(let f of formatResults) { delete f.id; delete f.resource_id; f.imported = !!f.imported; formats.push(f); // TRICKY: this is not technically correct, but for convenience we attach the import status to the resource directly if(f.imported) imported = true; } trans.resource.formats = formats; trans.resource.imported = imported; translations.push(trans); } return translations; }
javascript
{ "resource": "" }
q29490
equal
train
function equal(a, b) { if (a === b) return true; if (a === undefined || b === undefined) return false; if (a === null || b === null) return false; if (a.constructor === String) return a.localeCompare(b) === 0; if (b.constructor === String) return b.localeCompare(a) === 0; return false; }
javascript
{ "resource": "" }
q29491
installFilteredMouseMove
train
function installFilteredMouseMove(element) { element.bind("mousemove", function (e) { var lastpos = $.data(document, "select2-lastpos"); if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) { $(e.target).trigger("mousemove-filtered", e); } }); }
javascript
{ "resource": "" }
q29492
ajax
train
function ajax(options) { var timeout, // current scheduled but not yet executed request requestSequence = 0, // sequence used to drop out-of-order responses handler = null, quietMillis = options.quietMillis || 100; return function (query) { window.clearTimeout(timeout); timeout = window.setTimeout(function () { requestSequence += 1; // increment the sequence var requestNumber = requestSequence, // this request's sequence number data = options.data, // ajax data function transport = options.transport || $.ajax, traditional = options.traditional || false, type = options.type || 'GET'; // set type of request (GET or POST) data = data.call(this, query.term, query.page, query.context); if( null !== handler) { handler.abort(); } handler = transport.call(null, { url: options.url, dataType: options.dataType, data: data, type: type, traditional: traditional, success: function (data) { if (requestNumber < requestSequence) { return; } // TODO 3.0 - replace query.page with query so users have access to term, page, etc. var results = options.results(data, query.page); query.callback(results); } }); }, quietMillis); }; }
javascript
{ "resource": "" }
q29493
local
train
function local(options) { var data = options, // data elements dataText, text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search if (!$.isArray(data)) { text = data.text; // if text is not a function we assume it to be a key name if (!$.isFunction(text)) { dataText = data.text; // we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available text = function (item) { return item[dataText]; }; } data = data.results; } return function (query) { var t = query.term, filtered = { results: [] }, process; if (t === "") { query.callback({results: data}); return; } process = function(datum, collection) { var group, attr; datum = datum[0]; if (datum.children) { group = {}; for (attr in datum) { if (datum.hasOwnProperty(attr)) group[attr]=datum[attr]; } group.children=[]; $(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); }); if (group.children.length) { collection.push(group); } } else { if (query.matcher(t, text(datum))) { collection.push(datum); } } }; $(data).each2(function(i, datum) { process(datum, filtered.results); }); query.callback(filtered); }; }
javascript
{ "resource": "" }
q29494
train
function () { function resolveContainerWidth() { var style, attrs, matches, i, l; if (this.opts.width === "off") { return null; } else if (this.opts.width === "element"){ return this.opts.element.outerWidth() === 0 ? 'auto' : this.opts.element.outerWidth() + 'px'; } else if (this.opts.width === "copy" || this.opts.width === "resolve") { // check if there is inline style on the element that contains width style = this.opts.element.attr('style'); if (style !== undefined) { attrs = style.split(';'); for (i = 0, l = attrs.length; i < l; i = i + 1) { matches = attrs[i].replace(/\s/g, '') .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/); if (matches !== null && matches.length >= 1) return matches[1]; } } if (this.opts.width === "resolve") { // next check if css('width') can resolve a width that is percent based, this is sometimes possible // when attached to input type=hidden or elements hidden via css style = this.opts.element.css('width'); if (style.indexOf("%") > 0) return style; // finally, fallback on the calculated width of the element return (this.opts.element.outerWidth() === 0 ? 'auto' : this.opts.element.outerWidth() + 'px'); } return null; } else if ($.isFunction(this.opts.width)) { return this.opts.width(); } else { return this.opts.width; } }; var width = resolveContainerWidth.call(this); if (width !== null) { this.container.attr("style", "width: "+width); } }
javascript
{ "resource": "" }
q29495
IntervalMonitor
train
function IntervalMonitor(monitor, prefix, interval) { this.monitor = monitor; this.prefix = prefix || this.monitor.prefix; this.interval = interval || this.monitor.interval; }
javascript
{ "resource": "" }
q29496
each
train
function each(key, interface, fn) { var stack = interface.stack; for (var i = 0, len = stack.length; i < len; i++) { stack[i][key].forEach(fn); } }
javascript
{ "resource": "" }
q29497
buildOpeningElementAttributes
train
function buildOpeningElementAttributes (attribs, state) { var _props = [] while (attribs.length) { var prop = attribs.shift() if (t.isJSXSpreadAttribute(prop)) { prop.argument._isSpread = true _props.push(t.spreadProperty(prop.argument)) } else { _props.push(convertAttribute(prop, state)) } } attribs = t.objectExpression(_props) return attribs }
javascript
{ "resource": "" }
q29498
train
function(_form){ var _result = []; _u._$reverseEach( _form.getElementsByTagName('input'), function(_input){ if (_input.type!='file'){ return; } // remove file without name if (!_input.name){ _input.parentNode.removeChild(_input); return; } // for multiple file per-input if (_input.files.length>1){ _u._$forEach(_input.files,function(_file){ _result.push({name:_input.name,file:_file}); }); _input.parentNode.removeChild(_input); } } ); return _result.length>0?_result:null; }
javascript
{ "resource": "" }
q29499
train
function(_element){ var _id = _element.id; if (!!_dataset[_id]) return; var _map = {}; _u._$forEach( _element.attributes, function(_node){ var _key = _node.nodeName; if (_key.indexOf(_tag)!=0) return; _key = _key.replace(_tag,'') .replace(_reg,function($1,$2){ return $2.toUpperCase(); }); _map[_key] = _node.nodeValue||''; } ); _dataset[_id] = _map; }
javascript
{ "resource": "" }