_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q31700
addStaticRoute
train
function addStaticRoute(routePath, targets) { if (!Object.isArray(targets)) { targets = [targets]; } targets.forEach(function(target) { if (target) app.use(routePath, app.middleware.static(path.resolve(config.rootDir, target))); }); }
javascript
{ "resource": "" }
q31701
parseRoute
train
function parseRoute(route, target) { var verbs, routePath, routeParts; routeParts = route.split(' '); if (routeParts.length === 1) { verbs = ['all']; routePath = routeParts[0]; } else { verbs = routeParts[0].split(','); verbs.map(function (verb) { return verb.trim().toLowerCase(); }); routePath = routeParts[1]; } return {verbs: verbs, path: routePath, target: target}; }
javascript
{ "resource": "" }
q31702
parseParameter
train
function parseParameter(spec, ctx, params) { if (!spec || !isObject(spec)) return spec; for (var i=0, n=PARSERS.length, p; i<n; ++i) { p = PARSERS[i]; if (spec.hasOwnProperty(p.key)) { return p.parse(spec, ctx, params); } } return spec; }
javascript
{ "resource": "" }
q31703
getExpression
train
function getExpression(_, ctx, params) { if (_.$params) { // parse expression parameters parseParameters(_.$params, ctx, params); } var k = 'e:' + _.$expr + '_' + _.$name; return ctx.fn[k] || (ctx.fn[k] = accessor(parameterExpression(_.$expr, ctx), _.$fields, _.$name)); }
javascript
{ "resource": "" }
q31704
getKey
train
function getKey(_, ctx) { var k = 'k:' + _.$key + '_' + (!!_.$flat); return ctx.fn[k] || (ctx.fn[k] = key(_.$key, _.$flat)); }
javascript
{ "resource": "" }
q31705
getField
train
function getField(_, ctx) { if (!_.$field) return null; var k = 'f:' + _.$field + '_' + _.$name; return ctx.fn[k] || (ctx.fn[k] = field(_.$field, _.$name)); }
javascript
{ "resource": "" }
q31706
getCompare
train
function getCompare(_, ctx) { var k = 'c:' + _.$compare + '_' + _.$order, c = array(_.$compare).map(function(_) { return (_ && _.$tupleid) ? tupleid : _; }); return ctx.fn[k] || (ctx.fn[k] = compare(c, _.$order)); }
javascript
{ "resource": "" }
q31707
getEncode
train
function getEncode(_, ctx) { var spec = _.$encode, encode = {}, name, enc; for (name in spec) { enc = spec[name]; encode[name] = accessor(encodeExpression(enc.$expr, ctx), enc.$fields); encode[name].output = enc.$output; } return encode; }
javascript
{ "resource": "" }
q31708
getSubflow
train
function getSubflow(_, ctx) { var spec = _.$subflow; return function(dataflow, key, parent) { var subctx = parseDataflow(spec, ctx.fork()), op = subctx.get(spec.operators[0].id), p = subctx.signals.parent; if (p) p.set(parent); return op; }; }
javascript
{ "resource": "" }
q31709
start
train
function start() { // Listen to the port app.listen(hrsConfigs.port, function (err) { if (err) { info(err); } info('Running on http://%s:%s', hrsConfigs.address, hrsConfigs.port); }); }
javascript
{ "resource": "" }
q31710
train
function(args,next) { // do nothing now but in 1 sec setTimeout(function() { // if i'm job id 10 or 20, let's add // another job dynamicaly in the queue. // It can be usefull for network operation (retry on timeout) if (args._jobId==10||args._jobId==20) { myQueueJobs.add(myjob,[999,'bla '+args._jobId]); } next(); },Math.random(1000)*2000); }
javascript
{ "resource": "" }
q31711
isVoidElement
train
function isVoidElement(elName) { var result = false; if (elName && elName.toLowerCase) { result = VOID_HTML_ELEMENTS.hasOwnProperty(elName.toLowerCase()); } return result; }
javascript
{ "resource": "" }
q31712
train
function (blockList) { this.errors = []; this.tree = new Node("file", null); this.tree.content = []; this._advance(blockList, 0, this.tree.content); this._postProcessTree(); }
javascript
{ "resource": "" }
q31713
train
function (description, errdesc) { //TODO: errdesc is a bit vague var desc = { description : description }; if (errdesc) { if (errdesc.line) { // Integers desc.line = errdesc.line; desc.column = errdesc.column; } if (errdesc.code) { // String desc.code = errdesc.code; } if (errdesc.suberrors) { // Array of String desc.suberrors = errdesc.suberrors; } } this.errors.push(desc); }
javascript
{ "resource": "" }
q31714
train
function(expAst, attribute) { //verify that an event handler is a function call if (expAst && isEventHandlerAttr(attribute.name) && expAst.v !== '(') { this._logError("Event handler attribute only support function expressions", attribute.value[0]); } }
javascript
{ "resource": "" }
q31715
train
function (blocks, startIndex, out, optEndFn) { var block, type; if (blocks) { for (var i = startIndex; i < blocks.length; i++) { block = blocks[i]; type = block.type; if (optEndFn && optEndFn(type, block.name)) { // we stop here return i; } //by convention, a block of type xyz is managed by a __xyz function in the class if (this["__" + type]) { i = this["__" + type](i, blocks, out); } else { this._logError("Invalid statement: " + type, block); } } return blocks.length; } }
javascript
{ "resource": "" }
q31716
train
function() { var nodes = this.tree.content; for (var i = 0; i < nodes.length; i++) { if (nodes[i].type === "template") { this._processNodeContent(nodes[i].content,nodes[i]); } } }
javascript
{ "resource": "" }
q31717
train
function(nodeList, parent) { // Ensure that {let} nodes are always at the beginning of a containter element var node, contentFound = false; // true when a node different from let is found for (var i = 0; i < nodeList.length; i++) { node = nodeList[i]; //console.log(i+":"+node.type) if (node.type === "comment") { continue; } if (node.type==="text") { // tolerate static white space text if (node.value.match(/^\s*$/)) { continue; } } if (node.type === "let") { if (contentFound) { // error: let must be defined before any piece of content this._logError("Let statements must be defined at the beginning of a block", node); } else { parent.needSubScope = true; } } else { contentFound = true; if (node.content) { this._processNodeContent(node.content, node); } if (node.content1) { this._processNodeContent(node.content1, node); } if (node.content2) { this._processNodeContent(node.content2, node); } } } }
javascript
{ "resource": "" }
q31718
train
function (index, blocks, out) { var node = new Node("template"); var block = blocks[index]; var validationResults = this._processTemplateStart(block.attributes, block.closingBrace); if (validationResults.errors.length > 0) { this._logError("Invalid template declaration", { line: block.line, column : block.column, code: validationResults.code, suberrors: validationResults.errors }); } node.name = block.name; if (block.controller) { node.controller = block.controller; node.controller.ref = block.controllerRef; } else if (block.args) { node.args = block.args; // check args for (var i=0; i < node.args.length; i++) { if (reservedKeywords[node.args[i]]) { this._logError("Reserved keywords cannot be used as template argument: "+node.args[i], block); } } } node.isExport = (block.modifier !== null && block.modifier.type === "export"); node.isExportModule = (block.modifier !== null && block.modifier.type === "export-module"); node.startLine = block.line; node.endLine = block.endLine; node.content = []; out.push(node); if (!block.closed) { this._logError("Missing end template statement", block); } // parse sub-list of blocks this._advance(block.content, 0, node.content); return index; }
javascript
{ "resource": "" }
q31719
train
function (index, blocks, out) { var node = new Node("plaintext"), block = blocks[index]; node.value = block.value; out.push(node); return index; }
javascript
{ "resource": "" }
q31720
train
function (index, blocks, out) { var node = new Node("log"), block = blocks[index]; node.line = block.line; node.column = block.column; node.exprs = block.exprs; out.push(node); return index; }
javascript
{ "resource": "" }
q31721
train
function (index, blocks, out) { //creates the if node var node = new Node("if"), block = blocks[index], lastValidIndex = index; node.condition = { "category": block.condition.category, "value": block.condition.value, "line": block.condition.line, "column": block.condition.column }; node.condition.bound = true; //TODO: what does it mean? node.content1 = []; out.push(node); var endFound = false, out2 = node.content1; //process the content of the if block, until one of the if end is found (i.e. endif, else or elseif), if any while (!endFound) { //fills node.content1 with the next blocks index = this._advance(blocks, index + 1, out2, this._ifEndTypes); if (index < 0 || !blocks[index]) { this._logError("Missing end if statement", blocks[lastValidIndex]); endFound = true; } else { var type = blocks[index].type; if (type === "endif") { endFound = true; } else if (type === "else") { //loop will restrat, filling node.content2 with the next blocks node.content2 = []; out2 = node.content2; lastValidIndex = index; } else if (type === "elseif") { // consider as a standard else statement node.content2 = []; out2 = node.content2; lastValidIndex = index; endFound = true; // process as if it were an if node index = this.__if(index, blocks, out2); } } } return index; }
javascript
{ "resource": "" }
q31722
train
function (index, blocks, out) { //creates the foreach node var node = new Node("foreach"), block = blocks[index]; node.item = block.item; node.key = block.key; node.collection = block.colref; node.content = []; out.push(node); //fills node.content with the next blocks, until an endforeach is found, if any var nextIndex = this._advance(blocks, index + 1, node.content, this._foreachEndTypes); if (nextIndex < 0 || !blocks[nextIndex]) { this._logError("Missing end foreach statement", blocks[index]); } return nextIndex; }
javascript
{ "resource": "" }
q31723
train
function (index, blocks, out) { var block = blocks[index]; if (isVoidElement(block.name)) { block.closed=true; } return this._elementOrComponent("element", index, blocks, out); }
javascript
{ "resource": "" }
q31724
train
function (blockType, index, blocks, out) { var node = new Node(blockType), block = blocks[index], blockValue, expAst; node.name = block.name; node.closed = block.closed; if (block.ref) { // only for components node.ref = block.ref; } // Handle attributes var attributes = block.attributes, attribute, outAttribute; node.attributes = []; for (var i = 0; i < attributes.length; i++) { attribute = attributes[i]; //invalid attribute if (attribute.type === "invalidattribute") { for (var j = 0; j < attribute.errors.length; j++) { var error = attribute.errors[j]; var msg = "Invalid attribute"; if (error.errorType === "name") { msg = "Invalid attribute name: \\\"" + error.value + "\\\""; } else if (error.errorType === "value" || error.errorType === "tail") { var valueAsString = ""; for (var k = 0; k < error.value.length; k++) { var errorBlock = error.value[k]; if (k === 0) { error.line = errorBlock.line; error.column = errorBlock.column; } if (errorBlock.type === "expression") { valueAsString += "{" + errorBlock.value + "}"; var expAst = this._validateExpressionBlock(errorBlock); this._validateEventHandlerAttr(expAst, attribute); } else { valueAsString += errorBlock.value; } } if (typeof error.tail === "undefined") { msg = "Invalid attribute value: \\\"" + valueAsString + "\\\""; } else { msg = "Attribute value \\\"" + valueAsString + "\\\" has trailing chars: " + error.tail; } } else if (error.errorType === "invalidquotes") { msg = "Missing quote(s) around attribute value: " + error.value.replace("\"", "\\\""); } this._logError(msg, error); } continue; } //valid attribute var length = attribute.value.length; if (length === 0) { // this case arises when the attribute is empty - so let's create an empty text node if (attribute.value === "") { // attribute has no value - e.g. autocomplete in an input element outAttribute = { name : attribute.name, type : "name", line : attribute.line, column : attribute.column }; node.attributes.push(outAttribute); continue; } else { attribute.value.push({ type : "text", value : "" }); } length = 1; } if (length === 1) { // literal or expression var type = attribute.value[0].type; if (type === "text" || type === "expression") { outAttribute = attribute.value[0]; outAttribute.name = attribute.name; if (type === "expression") { expAst = this._validateExpressionBlock(outAttribute); this._validateEventHandlerAttr(expAst, attribute); } } else { this._logError("Invalid attribute type: " + type, attribute); continue; } } else { // length > 1 so attribute is a text block // if attribute is an event handler, raise an error if (isEventHandlerAttr(attribute.name)) { this._logError("Event handler attributes don't support text and expression mix", attribute); } //check expression attributes for syntax errors for (var j=0; j<length; j++) { blockValue = attribute.value[j]; if (blockValue.type === "expression") { expAst = this._validateExpressionBlock(blockValue); this._validateEventHandlerAttr(expAst, attribute); } } outAttribute = { name : attribute.name, type : "textblock", content : attribute.value }; } node.attributes.push(outAttribute); } //fills node.content with the next blocks, until an matching end element is found, if any node.content = []; out.push(node); if (!block.closed) { var endFound = false, blockName = block.name; while (!endFound) { index = this._advance(blocks, index + 1, node.content, function (type, name) { return (type === "end" + blockType); // && name===blockName }); if (index < 0 || !blocks[index]) { if (blockType==="component") { blockName="#"+this._getComponentPathAsString(block.ref); } // we didn't find any endelement or endcomponent this._logError("Missing end " + blockType + " </" + blockName + ">", block); endFound = true; } else { // check if the end name is correct var endBlock = blocks[index]; if (endBlock.type === "endelement" || endBlock.type === "endcptattribute") { if (endBlock.name !== blockName) { this._logError("Missing end " + blockType + " </" + blockName + ">", block); index -= 1; // the current end element/component may be caught by a container element } } else { // endcomponent var beginPath = this._getComponentPathAsString(block.ref), endPath = this._getComponentPathAsString(endBlock.ref); if (beginPath !== endPath) { this._logError("Missing end component </#" + beginPath + ">", block); index -= 1; // the current end element/component may be caught by a container element } } endFound = true; } } } return index; }
javascript
{ "resource": "" }
q31725
train
function(ref) { if (ref.category !== "objectref" || !ref.path || !ref.path.length || !ref.path.join) { return null; } return ref.path.join("."); }
javascript
{ "resource": "" }
q31726
train
function (index, blocks, out) { // only called in case of error var block = blocks[index]; var msg = "Invalid HTML element syntax"; if (block.code && block.code.match(/^<\/?@/)) { //when it starts with <@ or </@ msg = "Invalid component attribute syntax"; } this._logError(msg, block); return index; }
javascript
{ "resource": "" }
q31727
train
function (index, blocks, out) { // only called in case of error, i.e not digested by _elementOrComponent var block = blocks[index], name = block.name; if (isVoidElement(name)) { this._logError("The end element </" + name + "> was rejected as <" + name + "> is a void HTML element and can't have a closing element", block); } else { this._logError("End element </" + name + "> does not match any <" + name + "> element", block); } return index; }
javascript
{ "resource": "" }
q31728
train
function (index, blocks, out) { // only called in case of error, i.e not digested by _elementOrComponent var block = blocks[index], path = this._getComponentPathAsString(block.ref) ; this._logError("End component </#" + path + "> does not match any <#" + path + "> component", block); return index; }
javascript
{ "resource": "" }
q31729
Connector
train
function Connector(settings) { this.mailgun = Mailgun({apiKey: settings.apikey, domain: settings.domain}); }
javascript
{ "resource": "" }
q31730
callObservers
train
function callObservers(object, chgeset) { var ln = object[OBSERVER_PROPERTY]; if (ln) { var elt; for (var i = 0, sz = ln.length; sz > i; i++) { elt = ln[i]; if (elt.constructor === Function) { elt(chgeset); } } } }
javascript
{ "resource": "" }
q31731
train
function (object, property, value) { if (object[OBSERVER_PROPERTY]) { var existed = ownProperty.call(object, property), oldVal = object[property]; delete object[property]; if (existed) { var chgset=[changeDesc(object, property, object[property], oldVal, "deleted")]; callObservers(object, chgset); } } else { delete object[property]; } }
javascript
{ "resource": "" }
q31732
train
function (tplctxt, scopevars, ctlWrapper, ctlInitArgs, rootscope) { var vs = rootscope ? Object.create(rootscope) : {}, nm, argNames = []; // array of argument names if (scopevars) { for (var i = 0, sz = scopevars.length; sz > i; i += 2) { nm = scopevars[i]; vs[nm] = scopevars[i + 1]; // feed the vscope argNames.push(nm); } } vs["$scope"] = vs; // self reference (used for variables - cf. expression handler) var root = null; if (tplctxt.$constructor && tplctxt.$constructor === $CptNode) { // we use the component node as root node root = tplctxt; root.init(vs, this.nodedefs, argNames, ctlWrapper, ctlInitArgs); } else { root = new $RootNode(vs, this.nodedefs, argNames, ctlWrapper, ctlInitArgs); } return root; }
javascript
{ "resource": "" }
q31733
getGlobalRef
train
function getGlobalRef(name) { var r=global[name]; if (r===undefined) { r=null; } return r; }
javascript
{ "resource": "" }
q31734
_validate
train
function _validate (code, lineMap) { var validationResult = jsv.validate(code); var result = {isValid: validationResult.isValid}; if (!validationResult.isValid) { // translate error line numbers var error, lineNumber; for (var i = 0; i < validationResult.errors.length; i++) { error = validationResult.errors[i]; lineNumber = error.line; error.line = -1; // to avoid sending a wrong line in case of pb for (var j = 0; j < lineMap.length; j++) { if (lineMap[j] === lineNumber) { error.line = j; // original line nbr break; } } } result.errors = validationResult.errors; } return result; }
javascript
{ "resource": "" }
q31735
_getErrorScript
train
function _getErrorScript (errors, fileName) { var result = ''; if (errors && errors.length) { var err=errors[0]; var ctxt={ type:"error", file:fileName, code:err.code, line:err.line, column:err.column }; var suberrors = err.suberrors; var suberrorsJsStr = ""; // varargs, should end up as sth like '"a", "b", "c"' if (suberrors && suberrors.length > 0) { var out = []; for (var k = 0; k < suberrors.length; k++) { out[k] = _toDoubleQuotedJsString(suberrors[k], '==> '); } suberrorsJsStr = out.join(', ') + ', '; } var descriptionJsStr = _toDoubleQuotedJsString(err.description); var metadata = JSON.stringify(ctxt, null); result = ['\r\nrequire("hsp/rt/log").error(', descriptionJsStr, ',', suberrorsJsStr, metadata ,');\r\n'].join(""); } return result; }
javascript
{ "resource": "" }
q31736
_generateLineMap
train
function _generateLineMap (res, file) { if (res.errors && res.errors.length) { return; } var syntaxTree = res.syntaxTree, templates = []; // identify the templates in the syntax tree for (var i = 0; i < syntaxTree.length; i++) { if (syntaxTree[i].type === 'template') { templates.push(syntaxTree[i]); } } var nbrOfLinesInCompiledTemplate = 5; //all generated templates got fixed no of LOC var lineMap = [], pos = HEADER_SZ, template; var pos1 = -1; // position of the next template start var pos2 = -1; // position of the next template end var tplIdx = -1; // position of the current template for (var i = 0; i < (file.split(/\n/g).length + 1); i++) { if (i === 0 || i === pos2) { // end of current template: let's determine next pos1 and pos2 tplIdx = (i === 0) ? 0 : tplIdx + 1; if (tplIdx < templates.length) { // there is another template template = templates[tplIdx]; pos1 = template.startLine; pos2 = Math.max(template.endLine, pos1); } else { // last template has been found tplIdx = pos1 = pos2 = -1; } if (i === 0) { lineMap[0] = 0; } i++; } if (i === pos1) { for (var j = pos1; j < (pos2 + 1); j++) { // all lines are set to the template start lineMap[i] = pos; i++; } pos += nbrOfLinesInCompiledTemplate; i -= 2; // to enter the i===pos2 clause at next step } else { lineMap[i] = pos; pos++; } } return lineMap; }
javascript
{ "resource": "" }
q31737
train
function () { json.unobserve(this.target, this.callback); this.props=null; this.callback=null; this.target=null; }
javascript
{ "resource": "" }
q31738
train
function (observer, property) { if (!property) property = ALL; var arr = this.props[property]; if (!arr) { // property is not observed yet arr = []; this.props[property] = arr; } arr.push(observer); }
javascript
{ "resource": "" }
q31739
PropObserver_notifyChanges
train
function PropObserver_notifyChanges (chglist) { var c; for (var i = 0, sz = chglist.length; sz > i; i++) { c = chglist[i]; if (!c) continue; // check if we listen to this property if (this.props[c.name]) { PropObserver_notifyChange(this, c, c.name); } } if (this.props[ALL]) { PropObserver_notifyChange(this, c, ALL); } }
javascript
{ "resource": "" }
q31740
Naivebayes
train
function Naivebayes(options) { // set options object this.options = {}; if (typeof options !== 'undefined') { if (!options || typeof options !== 'object' || Array.isArray(options)) { throw TypeError( `NaiveBayes got invalid 'options': ${options}'. Pass in an object.` ); } this.options = options; } this.tokenizer = this.options.tokenizer || defaultTokenizer; this.alpha = this.options.alpha || DEFAULT_ALPHA; this.fitPrior = this.options.fitPrior === undefined ? DEFAULT_FIT_PRIOR : this.options.fitPrior; // initialize our vocabulary and its size this.vocabulary = {}; this.vocabularySize = 0; // number of documents we have learned from this.totalDocuments = 0; // document frequency table for each of our categories //= > for each category, how often were documents mapped to it this.docCount = {}; // for each category, how many words total were mapped to it this.wordCount = {}; // word frequency table for each category //= > for each category, how frequent was a given word mapped to it this.wordFrequencyCount = {}; // hashmap of our category names this.categories = {}; }
javascript
{ "resource": "" }
q31741
train
function (listItemContainers, node) { var isOrdered = node.nodeName === 'OL'; var startIndex = parseInt(node.getAttribute('start'), 10) || 1; // only applicable to ordered lists var blocks = (listItemContainers || []).map((listItemContainer, listItemIndex) => { var listItemElems = unwrap(listItemContainer); var firstListItemElem = listItemElems[0]; if (firstListItemElem && isTextBlock(firstListItemElem)) { let firstListItemPrefix = isOrdered ? `${startIndex + listItemIndex}. ` : `- `; firstListItemElem.text = firstListItemPrefix + firstListItemElem.text; } return listItemElems; }).reduce((prevBlocks, listItemBlocks) => { return prevBlocks.concat(listItemBlocks); }, []); return wrap(blocks); }
javascript
{ "resource": "" }
q31742
train
function(name, eve){ // Bi-directional binding of value m.addBinding(name, function(prop) { if (typeof prop == "function") { this.value = prop(); this[eve] = m.withAttr("value", prop); } else { this.value = prop; } }, true); }
javascript
{ "resource": "" }
q31743
getTag
train
function getTag(el) { return (el.firstChild === null) ? {'UL':'LI','DL':'DT','TR':'TD'}[el.tagName] || el.tagName : el.firstChild.tagName; }
javascript
{ "resource": "" }
q31744
wrap
train
function wrap(xhtml, tag) { var e = document.createElement('div'); e.innerHTML = xhtml; return e; }
javascript
{ "resource": "" }
q31745
train
function(o) { var options = {}; "duration after easing".split(' ').forEach( function(p) { if (props[p]) { options[p] = props[p]; delete props[p]; } }); return options; }
javascript
{ "resource": "" }
q31746
train
function(props) { var serialisedProps = [], key; if (typeof props != string) { for (key in props) { serialisedProps.push(cssstyle(key) + ':' + props[key]); } serialisedProps = serialisedProps.join(';'); } else { serialisedProps = props; } return serialisedProps; }
javascript
{ "resource": "" }
q31747
checkMax
train
function checkMax(value, max) { if (max) { if (max.charAt(0) === '-') { if (value.charAt(0) !== '-') return false; return checkMax(max.substr(1), value.substr(1)); } else { if (value.charAt(0) === '-') return true; } var len = Math.max(value.length, max.length); max = left0pad(max, len); value = left0pad(value, len); return value <= max; } return true; }
javascript
{ "resource": "" }
q31748
writeTopicConfig
train
function writeTopicConfig(client, topic, configs, callback) { debug('writeTopicConfig: "%s", %j', topic, configs); updateEntityConfig(client, getTopicConfigPath(topic), configs, callback); }
javascript
{ "resource": "" }
q31749
writeClientConfig
train
function writeClientConfig(client, clientId, configs, callback) { debug('writeClientConfig: "%s", %j', clientId, configs); updateEntityConfig(client, getClientConfigPath(clientId), configs, callback); }
javascript
{ "resource": "" }
q31750
createParentPath
train
function createParentPath(client, path, callback) { var parentDir = path.substring(0, path.lastIndexOf('/')); debug('createParentPath: "%s"', parentDir); if (parentDir.length != 0) { client.create(parentDir, function(err) { if (err) { if (err.code === NO_NODE) { return createParentPath(client, parentDir, function(err) { if (err) return callback(err); createParentPath(client, path, callback); }); } else if (err.code !== NODE_EXISTS) return callback(err); } callback(null, path); }); } else callback(null, path); }
javascript
{ "resource": "" }
q31751
createPersistentPath
train
function createPersistentPath(client, path, data, callback) { debug('createPersistentPath: "%s" "%s"', path, data); data = ensureBuffer(data); client.create(path, data, function(err) { if (err) { if (err.code !== NO_NODE) return callback(err); createParentPath(client, path, function(err) { if (err) return callback(err); client.create(path, data, callback); }); } else callback(null, path); }) }
javascript
{ "resource": "" }
q31752
updatePersistentPath
train
function updatePersistentPath(client, path, data, callback) { debug('updatePersistentPath: "%s" "%s"', path, data); data = ensureBuffer(data); client.setData(path, data, function (err) { if (err) { if (err.code !== NO_NODE) return callback(err); createParentPath(client, path, function(err) { if (err) return callback(err); client.create(path, data, function(err) { if (err) { if (err.code !== NODE_EXISTS) return callback(err); client.setData(path, data, callback); } else callback(null); }); }); } else callback(null); }); }
javascript
{ "resource": "" }
q31753
train
function( id, callback ){ var ID = id; // If the callback is the first parameter if( typeof id == 'function' ){ ID = 'ID_' + this._ID; callback = id; } this._callbacks[ID] = callback; this._ID++; return ID; }
javascript
{ "resource": "" }
q31754
train
function( id, xStore ){ Object.defineProperty(xStore, '_dispatcher', { value: this }); return this.register( id, xStore.callback ); }
javascript
{ "resource": "" }
q31755
train
function( ids ) { var promises = [], i = 0 ; if( !Array.isArray( ids ) ) ids = [ ids ]; for(; i<ids.length; i++ ){ if( this._promises[ ids[i] ] ) promises.push( this._promises[ ids[i] ] ); } if( !promises.length ) return this._Promise.resolve(); return this._Promise.all( promises ); }
javascript
{ "resource": "" }
q31756
train
function(){ var me = this, dispatchArguments = arguments, promises = [] ; this._promises = []; // A closure is needed for the callback id Object.keys( this._callbacks ).forEach( function( id ){ // All the promises must be set in me._promises before trying to resolve // in order to make waitFor work ok me._promises[ id ] = me._Promise.resolve() .then( function(){ return me._callbacks[ id ].apply( me, dispatchArguments ); }) .catch( function( err ){ console.error( err.stack || err ); }) ; promises.push( me._promises[ id ] ); }); // var dequeue = function(){ me._dispatchQueue.shift(); if( !me._dispatchQueue.length ) me._currentDispatch = false; }; return this._Promise.all( promises ) .then( dequeue, dequeue ) ; }
javascript
{ "resource": "" }
q31757
commonEventHandler
train
function commonEventHandler(event, arg) { // NOTE: send from renderer process always. var successEventName = getSuccessEventName(arg.eventName, arg.id); var failureEventName = getFailureEventName(arg.eventName, arg.id); var onSuccess = function(result) { // send success to ipc for renderer process. event.sender.send(COMMON_SUCCESS_EVENT_NAME, { data: result, eventName: arg.eventName, id: arg.id }); cee.removeListener(successEventName, onSuccess); cee.removeListener(failureEventName, onFailure); }; var onFailure = function(result) { // send failure to ipc for renderer process. event.sender.send(COMMON_FAILURE_EVENT_NAME, { data: result, eventName: arg.eventName, id: arg.id }); cee.removeListener(successEventName, onSuccess); cee.removeListener(failureEventName, onFailure); }; // add listener to common event emitter for main process. cee.on(successEventName, onSuccess); cee.on(failureEventName, onFailure); // emit to common event emitter for main process. cee.emit(arg.eventName, arg.id, arg.data, event); }
javascript
{ "resource": "" }
q31758
on
train
function on(event, listener) { // call from main process always. // add listener to common event emitter for main process. cee.on(event, function(id, data, ipcEvent) { listener(data, ipcEvent) .then(function(result) { cee.emit(getSuccessEventName(event, id), result); }) .catch(function(result) { cee.emit(getFailureEventName(event, id), result); }); }); }
javascript
{ "resource": "" }
q31759
installPeerDependencies
train
async function installPeerDependencies(cwd, installDir, options) { const { data: pkg } = await joycon.load({ files: ['package.json'], cwd }) const peers = pkg.peerDependencies || {} const packages = [] for (const peer in peers) { if (!options.peerFilter || options.peerFilter(peer, peers[peer])) { packages.push(`${peer}@${peers[peer]}`) } } if (packages.length > 0) { await install( Object.assign({}, options, { packages, cwd: installDir, installPeers: false }) ) } }
javascript
{ "resource": "" }
q31760
Robot
train
function Robot(opts) { if (!(this instanceof Robot)) { return new Robot(opts); } this.chains = opts.chains; this.offset = opts.offset || [0, 0, 0]; if (!opts.orientation) { opts.orientation = {}; } this.orientation = { pitch: opts.orientation.pitch || 0, yaw: opts.orientation.yaw || 0, roll: opts.orientation.roll || 0 }; }
javascript
{ "resource": "" }
q31761
Chain
train
function Chain(opts) { if (!(this instanceof Chain)) { return new Chain(opts); } if (opts.constructor) { this.devices = new opts.constructor(opts.actuators); } else { this.devices = opts.actuators; } this.chainType = opts.chainType; this.links = opts.links; this.origin = opts.origin || [0, 0, 0]; this.position = opts.startAt || [0, 0, 0]; this.require = opts.require || true; }
javascript
{ "resource": "" }
q31762
splitOnFirst
train
function splitOnFirst(str, splitter, callback) { var parts = str.split(splitter); var first = parts.shift(); return callback(first, parts.join(splitter)); }
javascript
{ "resource": "" }
q31763
liteURL
train
function liteURL(str) { // We first check if we have parsed this URL before, to avoid running the // monster regex over and over (which is expensive!) var uri = memo[str]; if (typeof uri !== 'undefined') { return uri; } //parsed url uri = uriParser(str); uri.params = queryParser(uri); // Stored parsed values memo[str] = uri; return uri; }
javascript
{ "resource": "" }
q31764
dateGetter
train
function dateGetter(name, size, offset, trim, negWrap) { if (offset === void 0) { offset = 0; } if (trim === void 0) { trim = false; } if (negWrap === void 0) { negWrap = false; } return function (date, locale) { var /** @type {?} */ part = getDatePart(name, date, size); if (offset > 0 || part > -offset) { part += offset; } if (name === DateType.Hours && part === 0 && offset === -12) { part = 12; } return padNumber(part, size, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign), trim, negWrap); }; }
javascript
{ "resource": "" }
q31765
getDateTranslation
train
function getDateTranslation(date, locale, name, width, form, extended) { switch (name) { case TranslationType.Months: return getLocaleMonthNames(locale, form, width)[date.getMonth()]; case TranslationType.Days: return getLocaleDayNames(locale, form, width)[date.getDay()]; case TranslationType.DayPeriods: var /** @type {?} */ currentHours_1 = date.getHours(); var /** @type {?} */ currentMinutes_1 = date.getMinutes(); if (extended) { var /** @type {?} */ rules = getLocaleExtraDayPeriodRules(locale); var /** @type {?} */ dayPeriods_1 = getLocaleExtraDayPeriods(locale, form, width); var /** @type {?} */ result_1; rules.forEach(function (rule, index) { if (Array.isArray(rule)) { // morning, afternoon, evening, night var _a = rule[0], hoursFrom = _a.hours, minutesFrom = _a.minutes; var _b = rule[1], hoursTo = _b.hours, minutesTo = _b.minutes; if (currentHours_1 >= hoursFrom && currentMinutes_1 >= minutesFrom && (currentHours_1 < hoursTo || (currentHours_1 === hoursTo && currentMinutes_1 < minutesTo))) { result_1 = dayPeriods_1[index]; } } else { // noon or midnight var hours = rule.hours, minutes = rule.minutes; if (hours === currentHours_1 && minutes === currentMinutes_1) { result_1 = dayPeriods_1[index]; } } }); if (result_1) { return result_1; } } // if no rules for the day periods, we use am/pm by default return getLocaleDayPeriods(locale, form, /** @type {?} */ (width))[currentHours_1 < 12 ? 0 : 1]; case TranslationType.Eras: return getLocaleEraNames(locale, /** @type {?} */ (width))[date.getFullYear() <= 0 ? 0 : 1]; } }
javascript
{ "resource": "" }
q31766
getRandomColors
train
function getRandomColors() { var letters = '0123456789ABCDEF'.split(''); var _color = '#'; for (var i = 0; i < 6; i++) { _color += letters[Math.floor(Math.random() * 16)]; } return _color; }
javascript
{ "resource": "" }
q31767
getFirstAndLastName
train
function getFirstAndLastName(data) { var names = data.split(" "); if (names && names.length >= 2) { var firstName = names[0]; var lastName = names[1]; if (firstName && lastName) { var text = firstName.substr(0, 1) + lastName.substr(0, 1); return text; } else { return data.substr(0, 2); } } }
javascript
{ "resource": "" }
q31768
wrap
train
function wrap(elements, options) { elements = toArray(elements); /* Don't wrap only a container in a container */ if (elements.length === 1 && isContainer(elements[0])) { return elements[0]; } var container = { type: cardTypes.container, items: elements }; setOptions(container, options); return container; }
javascript
{ "resource": "" }
q31769
turndown
train
function turndown(input) { if (!canConvert(input)) { throw new TypeError(input + ' is not a string, or an element/document/fragment node.'); } var cardElems = process.call(this, new RootNode(input)); return createCard(cardElems); }
javascript
{ "resource": "" }
q31770
replacementForNode
train
function replacementForNode(node) { var rule = this.rules.forNode(node); var content = process.call(this, node); // get's internal content of node return rule.replacement(content, node); }
javascript
{ "resource": "" }
q31771
canConvert
train
function canConvert(input) { return input != null && (typeof input === 'string' || input.nodeType && (input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11)); }
javascript
{ "resource": "" }
q31772
prange
train
function prange(s) { const set = new Set() const subs = s // correct things like AJs -A9s to AJs-A9s .replace( /([A,K,Q,J,T,2-9]{2}[o,s]?)\s*-\s*([A,K,Q,J,T,2-9]{2}[o,s]?)/g , '$1-$2' ) // correct AK + to AK+ .replace( /([A,K,Q,J,T,2-9]{2}[o,s]?)\s\+/g , '$1+' ) // split at any white space or comma (any errornous space was removed via replace) .split(/[,\s]+/).map(x => x.trim()) for (let i = 0; i < subs.length; i++) { const res = subrange(subs[i]) res.forEach(x => set.add(x)) } return Array.from(set).sort(byCodeRankDescending) }
javascript
{ "resource": "" }
q31773
organizer
train
function organizer(flat, tags, treeDescriptor, leafDescriptor) { var tree = {}; flat.forEach(function (song) { var treePtr = tree; var depth = 1; // strPossibleKeys can be like "albumArtist|artist", or just "album" for instance treeDescriptor.forEach(function (strPossibleKeys) { var possibleKeys = strPossibleKeys.split("|"); var valueForKey = undefined; for (var key in possibleKeys) { valueForKey = song[possibleKeys[key]]; if (valueForKey !== undefined && valueForKey !== "") { break; } } if (valueForKey === undefined) { valueForKey = ""; } if (!treePtr[valueForKey]) { if (depth === treeDescriptor.length) { treePtr[valueForKey] = { tags: {}, mpd: [] }; } else { treePtr[valueForKey] = { tags: {}, mpd: {} }; } var mostCommonKey = possibleKeys[possibleKeys.length - 1]; if (tags[mostCommonKey] && tags[mostCommonKey][valueForKey]) { treePtr[valueForKey].tags = tags[mostCommonKey][valueForKey]; } } treePtr = treePtr[valueForKey].mpd; depth++; }); var leaf = {}; if (leafDescriptor) { leafDescriptor.forEach(function (key) { leaf[key] = song[key]; }); } else { leaf = song; } if (tags["song"] && tags["song"][song.file]) { leaf.tags = tags["song"][song.file]; } treePtr.push(leaf); }); return { root: tree }; }
javascript
{ "resource": "" }
q31774
load
train
function load() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; params = (0, _lodash.defaults)({}, params, { locale: 'en_US' }); return new Promise(function (resolve, reject) { if (window.FB) { return resolve(window.FB); } var src = '//connect.facebook.net/' + params.locale + '/sdk.js'; var script = document.createElement('script'); script.id = 'facebook-jssdk'; script.src = src; script.async = true; script.addEventListener('load', function () { return resolve(window.FB); }, false); script.addEventListener('error', function () { return reject('Error loading Facebook JS SDK from ' + src); }, false); var sibling = document.getElementsByTagName('script')[0]; sibling.parentNode.insertBefore(script, sibling); }); }
javascript
{ "resource": "" }
q31775
reverse
train
function reverse(combos) { const { offsuit, suited, pairs } = sortOut(combos) const ps = reversePairs(pairs) const os = reverseNonPairs(offsuit, 'o') const su = reverseNonPairs(suited, 's') const nonpairs = unsuitWhenPossible(new Set(os), new Set(su)) return ps.concat(nonpairs).join(', ') }
javascript
{ "resource": "" }
q31776
showInvisibles
train
function showInvisibles(str) { let ret = ''; for (let i = 0; i < str.length; i++) { switch (str[i]) { case ' ': ret += '·'; // Middle Dot, \u00B7 break; case '\n': ret += '⏎'; // Return Symbol, \u23ce break; case '\t': ret += '↹'; // Left Arrow To Bar Over Right Arrow To Bar, \u21b9 break; case '\r': ret += '␍'; // Carriage Return Symbol, \u240D break; default: ret += str[i]; break; } } return ret; }
javascript
{ "resource": "" }
q31777
generateDifferences
train
function generateDifferences(source, prettierSource) { // fast-diff returns the differences between two texts as a series of // INSERT, DELETE or EQUAL operations. The results occur only in these // sequences: // /-> INSERT -> EQUAL // EQUAL | /-> EQUAL // \-> DELETE | // \-> INSERT -> EQUAL // Instead of reporting issues at each INSERT or DELETE, certain sequences // are batched together and are reported as a friendlier "replace" operation: // - A DELETE immediately followed by an INSERT. // - Any number of INSERTs and DELETEs where the joining EQUAL of one's end // and another's beginning does not have line endings (i.e. issues that occur // on contiguous lines). const results = diff(source, prettierSource); const differences = []; const batch = []; let offset = 0; // NOTE: INSERT never advances the offset. while (results.length) { const result = results.shift(); const op = result[0]; const text = result[1]; switch (op) { case diff.INSERT: case diff.DELETE: batch.push(result); break; case diff.EQUAL: if (results.length) { if (batch.length) { if (LINE_ENDING_RE.test(text)) { flush(); offset += text.length; } else { batch.push(result); } } else { offset += text.length; } } break; default: throw new Error(`Unexpected fast-diff operation "${op}"`); } if (batch.length && !results.length) { flush(); } } return differences; function flush() { let aheadDeleteText = ''; let aheadInsertText = ''; while (batch.length) { const next = batch.shift(); const op = next[0]; const text = next[1]; switch (op) { case diff.INSERT: aheadInsertText += text; break; case diff.DELETE: aheadDeleteText += text; break; case diff.EQUAL: aheadDeleteText += text; aheadInsertText += text; break; } } if (aheadDeleteText && aheadInsertText) { differences.push({ offset, operation: generateDifferences.REPLACE, insertText: aheadInsertText, deleteText: aheadDeleteText, }); } else if (!aheadDeleteText && aheadInsertText) { differences.push({ offset, operation: generateDifferences.INSERT, insertText: aheadInsertText, }); } else if (aheadDeleteText && !aheadInsertText) { differences.push({ offset, operation: generateDifferences.DELETE, deleteText: aheadDeleteText, }); } offset += aheadDeleteText.length; } }
javascript
{ "resource": "" }
q31778
cast
train
function cast(value){ if(value === undefined) return undefined; /* * Integers: 344i */ if(value.match(/^\d+i$/m)){ value = value.slice(0, -1); return parseInt(value); } /* boolean true * t, T, true, True, or TRUE */ if(value.match(/^t$|^true$/im)){ return true; } /* boolean false * f, F, false, False, or FALSE */ if(value.match(/^f$|^false$/im)){ return false; } /* * match strings */ if(value.match(/^"(.*)"$/)){ value = value.match(/^"(.*)"$/); if(value.length === 2){ return value[1]; } } if(!isNaN(value)) return parseFloat(value); return undefined; }
javascript
{ "resource": "" }
q31779
loadEnforcer
train
function loadEnforcer(method) { return function () { for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) { rest[_key] = arguments[_key]; } var FB = (0, _getGlobalFB2.default)(); if (!FB) { throw new Error('FB SDK Wrapper cannot call method ' + method.name + '; the ' + 'SDK is not loaded yet. Call load() first and wait for its promise ' + 'to resolve.'); } else { return method.apply(undefined, [FB].concat(rest)); } }; }
javascript
{ "resource": "" }
q31780
rule
train
function rule() { var ret = this.seq(rulename, defined_as, elements, c_nl); var da = ret[2]; if (da === "=") { return this.rules.addRule(ret[1], ret[3]); } if (da === "=/") { return this.rules.addAlternate(ret[1], ret[3]); } return this.fail(); }
javascript
{ "resource": "" }
q31781
train
function(bindingsString, bindingContext) { try { var viewModel = bindingContext['$data'], scopes = (typeof viewModel == 'object' && viewModel != null) ? [viewModel, bindingContext] : [bindingContext], bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, scopes.length, this.bindingCache); return bindingFunction(scopes); } catch (ex) { throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString); } }
javascript
{ "resource": "" }
q31782
calculateEditDistanceMatrix
train
function calculateEditDistanceMatrix(oldArray, newArray, maxAllowedDistance) { var distances = []; for (var i = 0; i <= newArray.length; i++) distances[i] = []; // Top row - transform old array into empty array via deletions for (var i = 0, j = Math.min(oldArray.length, maxAllowedDistance); i <= j; i++) distances[0][i] = i; // Left row - transform empty array into new array via additions for (var i = 1, j = Math.min(newArray.length, maxAllowedDistance); i <= j; i++) { distances[i][0] = i; } // Fill out the body of the array var oldIndex, oldIndexMax = oldArray.length, newIndex, newIndexMax = newArray.length; var distanceViaAddition, distanceViaDeletion; for (oldIndex = 1; oldIndex <= oldIndexMax; oldIndex++) { var newIndexMinForRow = Math.max(1, oldIndex - maxAllowedDistance); var newIndexMaxForRow = Math.min(newIndexMax, oldIndex + maxAllowedDistance); for (newIndex = newIndexMinForRow; newIndex <= newIndexMaxForRow; newIndex++) { if (oldArray[oldIndex - 1] === newArray[newIndex - 1]) distances[newIndex][oldIndex] = distances[newIndex - 1][oldIndex - 1]; else { var northDistance = distances[newIndex - 1][oldIndex] === undefined ? Number.MAX_VALUE : distances[newIndex - 1][oldIndex] + 1; var westDistance = distances[newIndex][oldIndex - 1] === undefined ? Number.MAX_VALUE : distances[newIndex][oldIndex - 1] + 1; distances[newIndex][oldIndex] = Math.min(northDistance, westDistance); } } } return distances; }
javascript
{ "resource": "" }
q31783
log
train
function log(type, args, color){ pad(); var msg = format.apply(format, args); if (color) msg = chalk[color](msg); var pre = prefix(); console[type](pre, msg); }
javascript
{ "resource": "" }
q31784
decode
train
function decode (imageDataView, width, height, format) { var result; format = format ? format.toLowerCase() : 'dxt1'; if (format === decode.dxt1) { result = decodeBC1(imageDataView, width, height); } else if(format === decode.dxt2) { result = decodeBC2(imageDataView, width, height, true); } else if(format === decode.dxt3) { result = decodeBC2(imageDataView, width, height, false); } else if(format === decode.dxt4) { result = decodeBC3(imageDataView, width, height, true); } else if(format === decode.dxt5) { result = decodeBC3(imageDataView, width, height, false); } else { throw new Error('Unknown DXT format : \'' + format + '\''); } return result; }
javascript
{ "resource": "" }
q31785
lower
train
function lower(str, options, cb) { // handle Handlebars or Lodash templates if (typeof options === 'function') { cb = options; options = {}; } cb(null, str.toLowerCase()); }
javascript
{ "resource": "" }
q31786
extractParts
train
function extractParts (str, indexA, indexB) { let part = str.substr(indexA, indexB); part = part.replace(/</g, '&lt;').replace(/>/g, '&gt;'); part = part.replace(/\n/g, '<span class="invisible"> \u21A9</span>\n'); part = part.replace(/\t/g, '<span class="invisible tab">\u2192</span>'); return part; }
javascript
{ "resource": "" }
q31787
handleStream
train
function handleStream(remotePeerId, stream) { if (opened[remotePeerId] !== true) { stream.write("hello!") stream.on("data", log) } function log(data) { console.log("[PEER2]", remotePeerId, data) } }
javascript
{ "resource": "" }
q31788
Logger
train
function Logger (options) { if (!(this instanceof Logger)) return new Logger(options); options = options || {}; debug('new logger v%s', pkg.version); var router = Router(); router.on(function (sock, args, cb) { debug('logger args.length %s', arguments.length); try { // "this" is the "socket" logger.stream().write(logger.format(sock, args) + "\n"); cb(); } catch (e) { debug('caught an error %s', e); console.trace(e); cb(e); } }); function logger (sock, cb) { debug('logger sock', sock, cb.toString()); router(sock, cb); } logger.__proto__ = Logger.prototype; if (options.stream) { logger.stream(options.stream); } if (options.format) { logger.format(options.format); } return logger; }
javascript
{ "resource": "" }
q31789
unlock
train
function unlock(isVerbose) { if (isVerbose) { console.log('Start unlocking ...'); } // Load bower.json and make sure it is a locked bower.json file var bowerConfigStr = fs.readFileSync('bower.json', {encoding: 'utf8'}); var bowerConfig = JSON.parse(bowerConfigStr); if (!bowerConfig.bowerLocker) { console.warn('The bower.json is already unlocked.\n' + "Run 'bower-locker lock' to create a locked file."); process.exit(1); } // Load original bower file var originalBowerConfigStr = fs.readFileSync('bower-locker.bower.json', {encoding: 'utf8'}); // Write it back as bower.json fs.writeFileSync('bower.json', originalBowerConfigStr, {encoding: 'utf8'}); console.log('Unlocking completed.'); }
javascript
{ "resource": "" }
q31790
Route
train
function Route(props) { props = props ? merge({}, props) : {}; var path = props.path; if (typeof path === 'string') { path = path.replace(slashes, ''); } delete props.path; var view = props.view; delete props.view; var viewPromise = props.viewPromise; delete props.viewPromise; var name = props.name; delete props.name; var __scope = props.__scope; delete props.__scope; var args = Array.prototype.slice.call(arguments, 1); var children = []; // so we support passing routes as arguments and arrays for (var i = 0, len = args.length; i < len; i++) { if (Array.isArray(args[i])) { children = children.concat(args[i]); } else { children.push(args[i]); } } var route = {path, name, view, viewPromise, props, children, __scope}; buildNameIndex(route); return route; }
javascript
{ "resource": "" }
q31791
postProcess
train
function postProcess(state) { var i, foundStart = false, foundEnd = false, delim, token, delimiters = state.delimiters, max = state.delimiters.length; for (i = 0; i < max; i++) { delim = delimiters[i]; if (delim.marker === '->') { foundStart = true; } else if (delim.marker === '<-') { foundEnd = true; } } if (foundStart && foundEnd) { for (i = 0; i < max; i++) { delim = delimiters[i]; if (delim.marker === '->') { foundStart = true; token = state.tokens[delim.token]; token.type = 'centertext_open'; token.tag = 'div'; token.nesting = 1; token.markup = '->'; token.content = ''; token.attrs = [ [ 'class', 'text-align-center' ] ]; } else if (delim.marker === '<-') { if (foundStart) { token = state.tokens[delim.token]; token.type = 'centertext_close'; token.tag = 'div'; token.nesting = -1; token.markup = '<-'; token.content = ''; } } } } }
javascript
{ "resource": "" }
q31792
procesArray
train
function procesArray(array) { if (!array || !Array.isArray(array)) { return array; } return array.map((item, index) => { if (typeof item === "string") { return localizeString(item); } return item; }); }
javascript
{ "resource": "" }
q31793
renderText
train
function renderText(args, that) { if (isNewTextVersion) { args[0] = { ...args[0], children: pseudoText(args[0].children) }; return defaultTextRender.apply(that, args); } else { const element = defaultTextRender.apply(that, args); return React.cloneElement(element, { children: pseudoText(element.props.children) }); } }
javascript
{ "resource": "" }
q31794
render
train
function render() { return function(...args) { return ( <PseudoContext.Consumer> {value => { if (!value) { return defaultTextRender.apply(this, args); } return renderText(args, this); }} </PseudoContext.Consumer> ); }; }
javascript
{ "resource": "" }
q31795
clean
train
function clean(post) { return reject({ title: post.title, contentFormat: post.contentFormat, content: post.content, tags: post.tags, canonicalUrl: post.canonicalUrl, publishStatus: post.publishStatus, license: post.license }); }
javascript
{ "resource": "" }
q31796
fetchViews
train
function fetchViews(match) { var activeTrace = match.activeTrace.map(fetchViewsStep); return activeTrace.some(Promise.is) ? Promise.all(activeTrace).then((activeTrace) => merge(match, {activeTrace})) : Promise.resolve(merge(match, {activeTrace})); }
javascript
{ "resource": "" }
q31797
train
function (node) { var key = node.property || node.key; if (!node.computed && key.type === 'JSXIdentifier') { return key.name; } // Delegate to original method. return infer.propName.apply(infer, arguments); }
javascript
{ "resource": "" }
q31798
train
function (node, scope) { var finder = infer.typeFinder[node.type]; return finder ? finder(node, scope) : infer.ANull; }
javascript
{ "resource": "" }
q31799
status
train
function status(isVerbose) { // Load bower.json and make sure it is a locked bower.json file var bowerConfigStr = fs.readFileSync('bower.json', {encoding: 'utf8'}); var bowerConfig = JSON.parse(bowerConfigStr); var locked = bowerConfig.bowerLocker; if (locked) { var timeDiff = (new Date()).getTime() - (new Date(locked.lastUpdated)).getTime(); console.log('bower.json was locked as of %s (%s)', locked.lastUpdated, formatTimeDiff(timeDiff)); if (isVerbose) { console.log('Currently locked dependencies:'); Object.keys(locked.lockedVersions).forEach(function(key) { console.log(' %s (%s): %s', key, locked.lockedVersions[key], bowerConfig.resolutions[key]); }); } } else { console.log('The bower.json is currently unlocked.\n'); } }
javascript
{ "resource": "" }