_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q31600
train
function (text, value) { var valueLength = value.length; if (text.length < valueLength) { return false; } return text.substring(0, valueLength) === value; }
javascript
{ "resource": "" }
q31601
train
function (array, c, depth) { var start = array.length - (array.length / Math.pow(2, depth)); for (var i = start, len = array.length; i < len; i += 1) { array[i] += c; } }
javascript
{ "resource": "" }
q31602
train
function (array) { var set = {}; var result = []; for (var i = 0, len = array.length; i < len; i += 1) { var item = array[i]; if (!Object.prototype.hasOwnProperty.call(set, item)) { set[item] = true; result.push(item); } } return result; }
javascript
{ "resource": "" }
q31603
train
function (routes) { if (!Array.isArray(routes)) { routes = [routes]; } var result = []; routes.forEach(function (route) { if (route.indexOf('[') === -1) { result.push(route); return; } var immediateResult = ['']; var depth = 0; var inLiteral = 0; for (var i = 0, len = route.length; i < len; i += 1) { var c = route[i]; if (!inLiteral) { if (c === '[') { depth += 1; for (var j = 0, lenJ = immediateResult.length; j < lenJ; j += 1) { immediateResult.push(immediateResult[j]); } } else if (c === ']') { depth -= 1; } else { if (c === '{') { inLiteral += 1; } else if (c === '}') { throw new Error("Found unexpected } in route: " + route); } addCharToArray(immediateResult, c, depth); } } else { if (c === '{') { inLiteral += 1; } else if (c === '}') { inLiteral -= 1; } addCharToArray(immediateResult, c, depth); } } for (i = 0, len = immediateResult.length; i < len; i += 1) { result.push(immediateResult[i]); } }); return distinct(result); }
javascript
{ "resource": "" }
q31604
train
function (bind, prefix) { return function (path, callback) { var prefixedPath = prefix + path; validatePath(prefixedPath); var innerMethods = spawn(escort.prototype, { bind: function (routeName, route, descriptor) { if (arguments.length === 2) { descriptor = route; route = routeName; if (Array.isArray(route)) { routeName = guessRouteName(prefixedPath + route[0]); } else { routeName = guessRouteName(prefixedPath + route); } } return bind(routeName, route, descriptor, prefixedPath); }, submount: makeSubmountFunction(bind, prefixedPath) }); callback.call(innerMethods, innerMethods); }; }
javascript
{ "resource": "" }
q31605
train
function (req, res) { return function (err) { if (err) { res.writeHead(500); res.end(err.toString()); } else { res.writeHead(404); res.end(); } }; }
javascript
{ "resource": "" }
q31606
train
function (object) { ACCEPTABLE_METHODS.forEach(function (method) { /** * Bind the provided route with a specific method to the callback provided. * Since you cannot specify a route more than once, it is required to use bind to provide multiple methods. * * @param {String} routeName The name of the route. Should be a JavaScript identifier. Optional. * @param {String} route The URL for the route. * @param {Function} callback The callback to be called when the route is accessed. * * @throws Error the routeName is already specified * @throws Error the route is already specified * @throws Error the route does not start with "/" * @throws Error an unknown route converter was specified * * @api public * * @example routes.get("/", function(request, response) { * response.end("GET /"); * }); * @example routes.post("item", "/{name}", function(request, response, params) { * response.end("GET /" + params.name); * }); */ object[method] = function (routeName, route, callback) { if (arguments.length === 2) { callback = route; route = routeName; routeName = null; } var descriptor = {}; descriptor[method] = callback; if (arguments.length === 2) { return this.bind(route, descriptor); } else { return this.bind(routeName, route, descriptor); } }; }); object.del = object.delete; }
javascript
{ "resource": "" }
q31607
train
function (value, length) { value = String(value); var numMissing = length - value.length; var prefix = ""; while (numMissing > 0) { prefix += "0"; numMissing -= 1; } return prefix + value; }
javascript
{ "resource": "" }
q31608
train
function (args) { if (!args) { args = {}; } var fixedDigits = args.fixedDigits; var min = args.min; var max = args.max; if (min === undefined) { min = null; } if (max === undefined) { max = null; } return spawn(IntegerConverter.prototype, { _fixedDigits: fixedDigits, _min: min, _max: max }); }
javascript
{ "resource": "" }
q31609
train
function () { var args = Array.prototype.slice.call(arguments, 0); if (args.length < 1) { throw new Error("Must specify at least one argument to AnyConverter"); } var values = {}; for (var i = 0, len = args.length; i < len; i += 1) { var arg = args[i]; values[arg.toLowerCase()] = arg; } return spawn(AnyConverter.prototype, { _values: values, regex: "(?:" + args.map(regexpEscape).join("|") + ")", weight: 200 }); }
javascript
{ "resource": "" }
q31610
train
function(state, datasetId, items, matchFound, nestingLevel, stopExpandingParents) { // initialize whatever wasn't passed to a default value datasetId = datasetId || 'default'; items = items || concealed.items[datasetId]; matchFound = matchFound || false; nestingLevel = nestingLevel || 0; for (var i = items.length; --i >= 0;) { if (!!items[i].items && !!items[i].items.length) { // matchFound here would mean that a match was found in a descendant matchFound = visible.setActive(state, datasetId, items[i].items, matchFound, nestingLevel + 1, stopExpandingParents); if (matchFound && !stopExpandingParents) { items[i].expanded = true; if (nestingLevel === 0) { stopExpandingParents = true; } } } else { if (matchFound) { // matchFound here would mean either a sibling node or some other node was already matched // so we want to skip the comparison to save time items[i].isActive = false; } else { if (!!items[i].stateName && items[i].stateName === state) { // if the item's state is the one being searched for then set the item to active and flip the matched flag items[i].isActive = true; matchFound = true; stopExpandingParents = true; } else { items[i].isActive = false; } } } } return matchFound; }
javascript
{ "resource": "" }
q31611
requirifyImageReference
train
function requirifyImageReference(markdownImageReference) { const [, mdImageStart, mdImagePath, optionalMdTitle, mdImageEnd ] = imagePathRE.exec(markdownImageReference) || [] if (!mdImagePath) { return JSON.stringify(markdownImageReference) } else { const imageRequest = loaderUtils.stringifyRequest( this, loaderUtils.urlToRequest(mdImagePath) ) const mdImageTitleAndEnd = optionalMdTitle ? JSON.stringify(optionalMdTitle + mdImageEnd) : JSON.stringify(mdImageEnd) return `${JSON.stringify(mdImageStart)} + require(${imageRequest}) + ${mdImageTitleAndEnd}` } }
javascript
{ "resource": "" }
q31612
checkPointerDown
train
function checkPointerDown(e) { if (config.clickOutsideDeactivates && !container.contains(e.target)) { deactivate({ returnFocus: false }); } }
javascript
{ "resource": "" }
q31613
applyTransformers
train
function applyTransformers(options, state, file) { var transformationSucceededAtLeastOnce = false; if (options.transformations && state.ext == "js") { options.transformations.forEach(function (transformation) { transformationSucceededAtLeastOnce |= transformAndTest(transformation, options, state, file); }); } return transformationSucceededAtLeastOnce; }
javascript
{ "resource": "" }
q31614
TObject
train
function TObject(qname, meta) { this.qname = qname; this.properties = new Map; this.modules = new Map; this.calls = [] this.types = new Map; this.supers = [] this.typeParameters = [] this.brand = null; this.meta = { kind: meta.kind, origin: meta.origin, isEnum: false } }
javascript
{ "resource": "" }
q31615
addModuleMember
train
function addModuleMember(member, moduleObject, qname) { current_node = member; var topLevel = qname === ''; if (member instanceof TypeScript.FunctionDeclaration) { var obj = moduleObject.getMember(member.name.text()) if (obj instanceof TObject) { obj.calls.push(parseFunctionType(member)) } else { throw new TypeError(member.name.text() + " is not a function") } } else if (member instanceof TypeScript.VariableStatement) { member.declaration.declarators.members.forEach(function(decl) { moduleObject.setMember(decl.id.text(), parseType(decl.typeExpr)) }) } else if (member instanceof TypeScript.ModuleDeclaration) { var name = member.name.text() if (member.isEnum()) { // enums are ModuleDeclarations in the AST, but they are semantically quite different var enumObj = moduleObject.getModule(name) enumObj.meta.isEnum = true var enumResult = parseEnum(member, enumObj, qname) moduleObject.types.push(name, enumResult.enum) } else { if (name[0] === '"' || name[0] === "'") { // external module? parseExternModule(member) } else { var submodule = moduleObject.getModule(name) parseModule(member, submodule, qualify(qname, name)) } } } else if (member instanceof TypeScript.ClassDeclaration) { var name = member.name.text() var clazzObj = moduleObject.getModule(name) var clazz = parseClass(member, clazzObj, qname) // moduleObject.setMember(member.name.text(), clazz.constructorType) moduleObject.types.push(member.name.text(), clazz.instanceType) } else if (member instanceof TypeScript.InterfaceDeclaration) { var name = member.name.text() var t = parseInterface(member, qname) moduleObject.types.push(name, t) } else if (member instanceof TypeScript.ImportDeclaration) { var ref = parseType(member.alias) if (topLevel || TypeScript.hasFlag(member.getVarFlags(), TypeScript.VariableFlags.Exported)) { moduleObject.types.push(member.id.text(), ref) } else { // private alias to (potentially) publicly visible type current_scope.env.push(member.id.text(), ref) } } else if (member instanceof TypeScript.ExportAssignment) { // XXX: I think we can actually just ignore these in the tscheck project, // but for completeness, maybe we should export this information somehow // For reference, this is what I *think* happens: // declare module "foo" { export = X } // This means import("foo") will return the value in global variable X. // Maybe we need these for modular analysis? } else { throw new TypeError("Unexpected member in module " + qname + ": " + member.constructor.name) } }
javascript
{ "resource": "" }
q31616
resolveReference
train
function resolveReference(x, isModule) { if (x instanceof TReference) { if (isBuiltin(x.name)) return new TBuiltin(x.name) if (x.resolution) return x.resolution if (x.resolving) throw new TypeError("Cyclic reference involving " + x) x.resolving = true var t = lookupInScope(x.scope, x.name, isModule) if (!t) { t = new TQualifiedReference(x.name) // XXX: for now assume global reference // throw new TypeError("Unresolved type: " + x.name) } t = resolveReference(t, isModule) x.resolution = t; return t; } else if (x instanceof TMember) { if (x.resolution) return x.resolution if (x.resolving) throw new TypeError("Cyclic reference involving " + x) x.resolving = true var base = resolveReference(x.base, true) var t = resolveReference(lookupInType(base, x.name, isModule), isModule) x.resolution = t return t; } else if (x instanceof TTypeQuery) { if (x.resolution) return x.resolution; if (x.resolving) throw new TypeError("Cyclic reference involving " + x) x.resolving = true var t = lookupPrtyInScope(x.scope, x.names[0]) if (!t) throw new TypeError("Name not found: " + x.names[0]) t = resolveReference(t) for (var i=1; i<x.names.length; i++) { var prty = t.properties.get(x.names[i]) var module = t.modules.get(x.names[i]) var t = prty ? prty.type : module; if (!t) throw new TypeError("Name not found: " + x.names.slice(0,i).join('.')) t = resolveReference(t) } if (t instanceof TObject && !t.qname) { t = synthesizeName(t) // don't create aliasing } x.resolution = t; return t; } else { return x; } }
javascript
{ "resource": "" }
q31617
resolveType
train
function resolveType(x) { if (x instanceof TReference) { return resolveReference(x) } else if (x instanceof TMember) { return resolveReference(x) } else if (x instanceof TObject) { if (x.qname) return new TQualifiedReference(x.qname) // can happen if a qname was synthesized by resolveReference return resolveObject(x); } else if (x instanceof TQualifiedReference) { return x; } else if (x instanceof TTypeParam) { return new TTypeParam(x.name, x.constraint && resolveType(x.constraint)) } else if (x instanceof TGeneric) { return new TGeneric(resolveType(x.base), x.args.map(resolveType)) } else if (x instanceof TString) { return x; } else if (x instanceof TBuiltin) { return x; } else if (x instanceof TTypeQuery) { return resolveReference(x); } else if (x instanceof TEnum) { return x; } var msg; if (x.constructor.name === 'Object') msg = util.inspect(x) else msg = '' + x; throw new TypeError("Cannot canonicalize reference to " + (x && x.constructor.name + ': ' + msg)) }
javascript
{ "resource": "" }
q31618
hasBrand
train
function hasBrand(value, brand) { var ctor = lookupPath(brand, function() { return null }) if (!ctor || typeof ctor !== 'object') return null; var proto = lookupObject(ctor.key).propertyMap.get('prototype') if (!proto || !proto.value || typeof proto.value !== 'object') return null; while (value && typeof value === 'object') { if (value.key === proto.value.key) return true value = lookupObject(value.key).prototype } return false; }
javascript
{ "resource": "" }
q31619
getEnclosingFunction
train
function getEnclosingFunction(node) { while (node.type !== 'FunctionDeclaration' && node.type !== 'FunctionExpression' && node.type !== 'Program') { node = node.$parent; } return node; }
javascript
{ "resource": "" }
q31620
getEnclosingScope
train
function getEnclosingScope(node) { while (node.type !== 'FunctionDeclaration' && node.type !== 'FunctionExpression' && node.type !== 'CatchClause' && node.type !== 'Program') { node = node.$parent; } return node; }
javascript
{ "resource": "" }
q31621
isElement
train
function isElement(value) { return isNonNullObject(value) && value.nodeType === 1 && toString.call(value).indexOf('Element') > -1; }
javascript
{ "resource": "" }
q31622
isVueComponent
train
function isVueComponent(value) { return isPlainObject(value) && (isNonEmptyString(value.template) || isFunction(value.render) || isNonEmptyString(value.el) || isElement(value.el) || isVueComponent(value.extends) || isNonEmptyArray(value.mixins) && value.mixins.some(function (val) { return isVueComponent(val); })); }
javascript
{ "resource": "" }
q31623
initialize
train
function initialize() { var flags = []; Object.keys( levels ).forEach(function( type, level ) { var method = type.toLowerCase(); exports[ method ] = log.bind( exports, type, level, false ); exports[ method ].json = log.bind( exports, type, level, true ); if ( new RegExp( '\\b' + type + '\\b', 'i' ).test( env ) ) { flags.push( level ); } }); loglevel = Math.min.apply( Math, flags ); }
javascript
{ "resource": "" }
q31624
format
train
function format( type, args ) { var now = new Date().toISOString(), tmpl = '[%s] %s: %s\n', msg; msg = args[ 0 ] instanceof Error ? args[ 0 ].stack : util.format.apply( util, args ); return util.format( tmpl, now, type, msg ); }
javascript
{ "resource": "" }
q31625
readConfig
train
function readConfig() { let options = {} let cFile = '' if (program.config) { cFile = path.resolve(cwd, program.config) if (fs.existsSync(cFile)) { Object.assign(config, require(cFile)) } else { console.warn(`Cannot find configuration file ${program.config}`) process.exit() } } else { cFile = path.resolve(cwd, 'deploy.js') } if (fs.existsSync(cFile)) { options = require(cFile) } ;['server', 'ignore'].forEach(function(name) { if (typeof program[name] !== 'undefined') { options[name] = program[name] } }) if (program.args[0]) { options.workspace = path.resolve(cwd, program.args[0]) } if (program.args[1]) { options.deployTo = program.args[1] } return options }
javascript
{ "resource": "" }
q31626
shutdown
train
function shutdown() { var instance = this; instance.active = false; instance.transmitter = null; instance.remoteTimeout = 0; instance.localTimeout = 0; instance.localComponents = {}; instance.remoteComponents = {}; instance.outbox.requests.length = 0; instance.outbox.responses.length = 0; instance.inbox = {}; instance.exposed = {}; Object.keys(instance.localTimers).forEach(function(key) { clearTimeout(instance.localTimers[key]); delete instance.localTimers[key]; }); Object.keys(instance.outTimers).forEach(function(key) { clearTimeout(instance.outTimers[key]); delete instance.outTimers[key]; }); return instance; }
javascript
{ "resource": "" }
q31627
confirmTransmit
train
function confirmTransmit(outpacket, err) { if (this.active && err) { // Roll it all back into outbox (which may not be empty anymore) if (outpacket.responses.length > 0) { Array.prototype.push.apply(this.outbox.responses, outpacket.responses); } if (outpacket.requests.length > 0) { Array.prototype.push.apply(this.outbox.requests, outpacket.requests); } } }
javascript
{ "resource": "" }
q31628
receive
train
function receive(msg) { var requests = []; var responses = []; if (!this.active) { return this; } // If we got JSON, parse it if (typeof msg === 'string') { try { msg = JSON.parse(msg); } catch (e) { // The specification doesn't force us to respond in error, ignoring return this; } } // If we get a standard single-type batch, dispatch it if (msg.constructor === Array) { if (msg.length === 0) { return this; } // Hint of request batch if (typeof msg[0].method === 'string') { requests = msg; } else { responses = msg; } } else if (typeof msg === 'object') { // Could we be a 'dual-batch' extended message? if ( typeof msg.requests !== 'undefined' && typeof msg.responses !== 'undefined' ) { requests = msg.requests; responses = msg.responses; } else if (typeof msg.method === 'string') { // We're a single request requests.push(msg); } else { // We must be a single response responses.push(msg); } } responses.forEach(deliverResponse.bind(this)); requests.forEach(serveRequest.bind(this)); return this; }
javascript
{ "resource": "" }
q31629
upgrade
train
function upgrade() { if (!this.active) { return this; } return this.call( 'system.listComponents', this.localComponents, (function(err, result) { if (!err && typeof result === 'object') { this.remoteComponents = result; this.remoteComponents['system._upgraded'] = true; } }).bind(this) ); }
javascript
{ "resource": "" }
q31630
call
train
function call(methodName, params, next) { var request = { jsonrpc: '2.0', method : methodName }; if (!this.active) { return this; } if (typeof params === 'function') { next = params; params = null; } if ( 'system._upgraded' in this.remoteComponents && !(methodName in this.remoteComponents) ) { // We're upgraded, yet method name isn't found, immediate error! if (typeof next === 'function') { setImmediate(next, { code : -32601, message: 'Unknown remote method' }); } return this; } if (typeof params === 'object') { request.params = params; } this.serial++; if (typeof next === 'function') { request.id = this.serial; this.inbox[this.serial] = next; } this.outbox.requests.push(request); // If we're interactive, send the new request this.transmit(); if (typeof next !== 'function') { return this; } if (this.remoteTimeout > 0) { this.outTimers[this.serial] = setTimeout( deliverResponse.bind( this, { jsonrpc: '2.0', id : this.serial, error : { code : -1000, message: 'Timed out waiting for response' } } ), this.remoteTimeout ); } else { this.outTimers[this.serial] = true; // Placeholder } return this; }
javascript
{ "resource": "" }
q31631
deliverResponse
train
function deliverResponse(res) { var err = false; var result = null; if (this.active && 'id' in res && res['id'] in this.outTimers) { clearTimeout(this.outTimers[res['id']]); // Passing true instead of a timeout is safe delete this.outTimers[res['id']]; } else { // Silently ignoring second response to same request return; } if (res['id'] in this.inbox) { if ('error' in res) { err = res['error']; } else { result = res['result']; } setImmediate(this.inbox[res['id']], err, result); delete this.inbox[res['id']]; } // Silently ignore timeout duplicate and malformed responses }
javascript
{ "resource": "" }
q31632
expose
train
function expose(subject, callback) { var name; if (!this.active) { return this; } if (typeof subject === 'string') { this.localComponents[subject] = true; this.exposed[subject] = callback; } else if (typeof subject === 'object') { for (name in subject) { if (subject.hasOwnProperty(name)) { this.localComponents[name] = true; this.exposed[name] = subject[name]; } } } return this; }
javascript
{ "resource": "" }
q31633
serveRequest
train
function serveRequest(request) { var id = null; var params = null; if (!this.active || typeof request !== 'object' || request === null) { return; } if (!(typeof request.jsonrpc === 'string' && request.jsonrpc === '2.0')) { return; } id = (typeof request.id !== 'undefined' ? request.id : null); if (typeof request.method !== 'string') { if (id !== null) { this.localTimers[id] = true; setImmediate(sendResponse.bind(this, id, -32600)); } return; } if (!(request.method in this.exposed)) { if (id !== null) { this.localTimers[id] = true; setImmediate(sendResponse.bind(this, id, -32601)); } return; } if ('params' in request) { if (typeof request['params'] === 'object') { params = request['params']; } else { if (id !== null) { this.localTimers[id] = true; setImmediate(sendResponse.bind(this, id, -32602)); } return; } } if (id !== null) { if (this.localTimeout > 0) { this.localTimers[id] = setTimeout( sendResponse.bind( this, id, { code : -1002, message: 'Method handler timed out' } ), this.localTimeout ); } else { this.localTimers[id] = true; } } setImmediate( this.exposed[request.method], params, sendResponse.bind(this, id) ); return; }
javascript
{ "resource": "" }
q31634
sendResponse
train
function sendResponse(id, err, result) { var response = { jsonrpc: '2.0', id : id }; if (id === null) { return; } if (this.active && id in this.localTimers) { clearTimeout(this.localTimers[id]); // Passing true instead of a timeout is safe delete this.localTimers[id]; } else { // Silently ignoring second response to same request return; } if (typeof err !== 'undefined' && err !== null && err !== false) { if (typeof err === 'number') { response.error = { code : err, message: 'error' }; } else if (err === true) { response.error = { code : -1, message: 'error' }; } else if (typeof err === 'string') { response.error = { code : -1, message: err }; } else if ( typeof err === 'object' && 'code' in err && 'message' in err ) { response.error = err; } else { response.error = { code : -2, message: 'error', data : err }; } } else { response.result = result; } this.outbox.responses.push(response); // If we're interactive, send the new response this.transmit(); }
javascript
{ "resource": "" }
q31635
train
function (route, converters) { var literals = route.literals; var params = route.params; var conv = []; var fun = ""; fun += "var generate = function (params) {\n"; fun += " if (arguments.length === 1 && typeof params === 'object' && params.constructor !== String) {\n"; fun += " return "; fun += JSON.stringify(literals[0]); for (var i = 0, len = params.length; i < len; i += 1) { fun += "+converters["; fun += i; fun += "](params["; fun += JSON.stringify(params[i].name); fun += "])"; if (literals[i + 1]) { fun += "+"; fun += JSON.stringify(literals[i + 1]); } var paramType = params[i].type; if (!has.call(converters, paramType)) { throw new Error("Unknown converter: " + paramType); } var converter = converters[paramType]; if (!converter) { throw new Error("Misconfigured converter: " + paramType); } conv.push(converter(params[i])); } fun += ";\n"; fun += " }\n"; fun += " return generate({"; for (i = 0, len = params.length; i < len; i += 1) { if (i > 0) { fun += ", "; } fun += JSON.stringify(params[i].name); fun += ":arguments["; fun += i; fun += "]"; } fun += "});\n"; fun += "};\n"; fun += "return generate;\n"; return new Function("converters", fun)(conv); }
javascript
{ "resource": "" }
q31636
train
function (routes, converters) { var staticRoute, dynamicRoute; // we traverse backwards because the beginning ones take precedence and thus can override. for (var i = routes.length - 1; i >= 0; i -= 1) { var route = routes[i]; if (route.path) { staticRoute = route.path; } else { dynamicRoute = route; } } if (dynamicRoute) { dynamicRoute = generateDynamicUrlFunction(dynamicRoute, converters); } if (staticRoute) { staticRoute = generateStaticUrlFunction(staticRoute); if (dynamicRoute) { // this can occur if the url is like "/posts" and "/posts/page/{page}" return function () { if (arguments.length === 0) { return staticRoute(); } else { return dynamicRoute.apply(this, slice.call(arguments, 0)); } }; } else { return staticRoute; } } else { if (dynamicRoute) { return dynamicRoute; } else { return null; } } }
javascript
{ "resource": "" }
q31637
getTempFileName
train
function getTempFileName(state) { var fn = state.tmp_dir + "/delta_js_" + state.round + "." + state.ext; state.round++; return fn; }
javascript
{ "resource": "" }
q31638
copyToOut
train
function copyToOut(src, out, multiFileMode) { try { fs.copySync(src, out); fs.statSync(out) return out; } catch (err) { } }
javascript
{ "resource": "" }
q31639
train
function (method) { var str = '' + method, i = str.indexOf(SUPER) ; return i < 0 ? false : isBoundary(str.charCodeAt(i - 1)) && isBoundary(str.charCodeAt(i + 5)); }
javascript
{ "resource": "" }
q31640
addMixins
train
function addMixins(mixins, target, inherits, isNOTExtendingNative) { for (var source, init = [], i = 0; i < mixins.length; i++ ) { source = transformMixin(mixins[i]); if (hOP.call(source, INIT)) { init.push(source[INIT]); } copyOwn(source, target, inherits, false, false, isNOTExtendingNative); } return init; }
javascript
{ "resource": "" }
q31641
copyMerged
train
function copyMerged(source, target) { for (var key, descriptor, value, tvalue, names = oK(source), i = 0; i < names.length; i++ ) { key = names[i]; descriptor = gOPD(source, key); // target already has this property if (hOP.call(target, key)) { // verify the descriptor can be merged if (hOP.call(descriptor, VALUE)) { value = descriptor[VALUE]; // which means, verify it's an object if (isObject(value)) { // in such case, verify the target can be modified descriptor = gOPD(target, key); // meaning verify it's a data descriptor if (hOP.call(descriptor, VALUE)) { tvalue = descriptor[VALUE]; // and it's actually an object if (isObject(tvalue)) { copyMerged(value, tvalue); } } } } } else { // target has no property at all if (hOP.call(descriptor, VALUE)) { // copy deep if it's an object copyValueIfObject(descriptor, copyDeep); } defineProperty(target, key, descriptor); } } }
javascript
{ "resource": "" }
q31642
copyOwn
train
function copyOwn(source, target, inherits, publicStatic, allowInit, isNOTExtendingNative) { for (var key, noFunctionCheck = typeof source !== 'function', names = oK(source), i = 0; i < names.length; i++ ) { key = names[i]; if ( (noFunctionCheck || indexOf.call(nativeFunctionOPN, key) < 0) && isNotASpecialKey(key, allowInit) ) { if (hOP.call(target, key)) { warn('duplicated: ' + key.toString()); } setProperty(inherits, target, key, gOPD(source, key), publicStatic, isNOTExtendingNative); } } }
javascript
{ "resource": "" }
q31643
copyValueIfObject
train
function copyValueIfObject(where, how) { var what = where[VALUE]; if (isObject(what)) { where[VALUE] = how(what); } }
javascript
{ "resource": "" }
q31644
createConstructor
train
function createConstructor(hasParentPrototype, parent) { var Class = function Class() {}; return hasParentPrototype && ('' + parent) !== ('' + Class) ? function Class() { return parent.apply(this, arguments); } : Class ; }
javascript
{ "resource": "" }
q31645
define
train
function define(target, key, value, publicStatic) { var configurable = isConfigurable(key, publicStatic); defineProperty(target, key, { enumerable: false, // was: publicStatic, configurable: configurable, writable: configurable, value: value }); }
javascript
{ "resource": "" }
q31646
isNotASpecialKey
train
function isNotASpecialKey(key, allowInit) { return key !== CONSTRUCTOR && key !== EXTENDS && key !== IMPLEMENTS && // Blackberry 7 and old WebKit bug only: // user defined functions have // enumerable prototype and constructor key !== PROTOTYPE && key !== STATIC && key !== SUPER && key !== WITH && (allowInit || key !== INIT); }
javascript
{ "resource": "" }
q31647
isPublicStatic
train
function isPublicStatic(key) { for(var c, i = 0; i < key.length; i++) { c = key.charCodeAt(i); if ((c < 65 || 90 < c) && c !== 95) { return false; } } return true; }
javascript
{ "resource": "" }
q31648
transformMixin
train
function transformMixin(trait) { if (isObject(trait)) return trait; else { var i, key, keys, object, proto; if (trait.isClass) { if (trait.length) { warn((trait.name || 'Class') + ' should not expect arguments'); } for ( object = {init: trait}, proto = trait.prototype; proto && proto !== Object.prototype; proto = gPO(proto) ) { for (i = 0, keys = oK(proto); i < keys.length; i++) { key = keys[i]; if (isNotASpecialKey(key, false) && !hOP.call(object, key)) { defineProperty(object, key, gOPD(proto, key)); } } } } else { for ( i = 0, object = {}, proto = trait({}), keys = oK(proto); i < keys.length; i++ ) { key = keys[i]; if (key !== INIT) { // if this key is the mixin one if (~key.toString().indexOf('mixin:init') && isArray(proto[key])) { // set the init simply as own method object.init = proto[key][0]; } else { // simply assign the descriptor defineProperty(object, key, gOPD(proto, key)); } } } } return object; } }
javascript
{ "resource": "" }
q31649
setProperty
train
function setProperty(inherits, target, key, descriptor, publicStatic, isNOTExtendingNative) { var hasValue = hOP.call(descriptor, VALUE), configurable, value ; if (publicStatic) { if (hOP.call(target, key)) { // in case the value is not a static one if ( inherits && isObject(target[key]) && isObject(inherits[CONSTRUCTOR][key]) ) { copyMerged(inherits[CONSTRUCTOR][key], target[key]); } return; } else if (hasValue) { // in case it's an object perform a deep copy copyValueIfObject(descriptor, copyDeep); } } else if (hasValue) { value = descriptor[VALUE]; if (typeof value === 'function' && trustSuper(value)) { descriptor[VALUE] = wrap(inherits, key, value, publicStatic); } } else if (isNOTExtendingNative) { wrapGetOrSet(inherits, key, descriptor, 'get'); wrapGetOrSet(inherits, key, descriptor, 'set'); } configurable = isConfigurable(key, publicStatic); descriptor.enumerable = false; // was: publicStatic; descriptor.configurable = configurable; if (hasValue) { descriptor.writable = configurable; } defineProperty(target, key, descriptor); }
javascript
{ "resource": "" }
q31650
verifyImplementations
train
function verifyImplementations(interfaces, target) { for (var current, key, i = 0; i < interfaces.length; i++ ) { current = interfaces[i]; for (key in current) { if (hOP.call(current, key) && !hOP.call(target, key)) { warn(key.toString() + ' is not implemented'); } } } }
javascript
{ "resource": "" }
q31651
vel
train
function vel (rend) { assert.equal(typeof rend, 'function') var update = null render.toString = toString render.render = render render.vtree = vtree return render // render the element's vdom tree to DOM nodes // which can be mounted on the DOM // any? -> DOMNode function render (state) { if (update) return update(state) const loop = mainLoop(state, renderFn(rend), vdom) update = loop.update return loop.target } // render the element's vdom tree to a string // any? -> str function toString (state) { return toHtml(renderFn(rend)(state)) } // Get the element's vdom tree. // any? -> obj function vtree (state) { return rend(h, state) } }
javascript
{ "resource": "" }
q31652
render
train
function render (state) { if (update) return update(state) const loop = mainLoop(state, renderFn(rend), vdom) update = loop.update return loop.target }
javascript
{ "resource": "" }
q31653
disconnect
train
function disconnect(socket) { if (socket.namespace.name === '') return socket.disconnect(); socket.packet({type:'disconnect'}); socket.manager.onLeave(socket, socket.namespace.name); socket.$emit('disconnect', 'booted'); }
javascript
{ "resource": "" }
q31654
back
train
function back (self, cb, cancel) { if (!cb) cb = noop if (self._back.length === 0 || self._pending) return cb(null) var previous = self._back.pop() var current = self.current() load(self, previous, done) function done (err) { if (err) return cb(err) if (!cancel) self._forward.push(current) self._current = previous unload(self, current) cb(null) } }
javascript
{ "resource": "" }
q31655
addProperty
train
function addProperty(col, func) { // Exposed on top of the namespace colour[col] = function(str) { return func.apply(str); }; // And on top of all strings try { String.prototype.__defineGetter__(col, func); definedGetters[col] = func; } catch (e) {} // #25 }
javascript
{ "resource": "" }
q31656
stylize
train
function stylize(str, style) { if (colour.mode == 'console') { return consoleStyles[style][0] + str + consoleStyles[style][1]; } else if (colour.mode == 'browser') { return browserStyles[style][0] + str + browserStyles[style][1]; } else if (colour.mode == 'browser-css') { return cssStyles[style][0] + str + browserStyles[style][1]; } return str+''; }
javascript
{ "resource": "" }
q31657
applyTheme
train
function applyTheme(theme) { Object.keys(theme).forEach(function(prop) { if (prototypeBlacklist.indexOf(prop) >= 0) { return; } if (typeof theme[prop] == 'string') { // Multiple colours white-space seperated #45, e.g. "red bold", #18 theme[prop] = theme[prop].split(' '); } addProperty(prop, function () { var ret = this; for (var t=0; t<theme[prop].length; t++) { ret = colour[theme[prop][t]](ret); } return ret; }); }); }
javascript
{ "resource": "" }
q31658
sequencer
train
function sequencer(map) { return function () { if (this == undefined) return ""; var i=0; return String.prototype.split.apply(this, [""]).map(map).join(""); }; }
javascript
{ "resource": "" }
q31659
choiceListener
train
function choiceListener(index) { return function (event) { event.preventDefault(); if (choicesAnimating) return; clearChoiceListeners(); story.ChooseChoiceIndex(index); saveGame(index); clearOldChoices().then(() => progressGame()); } }
javascript
{ "resource": "" }
q31660
createChoiceListener
train
function createChoiceListener(li, index) { li.clickListener = choiceListener(index); li.addEventListener('click', li.clickListener); li.clearListener = (function () { this.removeEventListener('click', this.clickListener); }).bind(li); }
javascript
{ "resource": "" }
q31661
clearChoiceListeners
train
function clearChoiceListeners() { const lis = document.querySelectorAll('li'); Array.from(lis).forEach(li => { if (li.clearListener) li.clearListener(); }) }
javascript
{ "resource": "" }
q31662
createChoiceUl
train
function createChoiceUl () { const lis = story.currentChoices .map(choice => { const li = document.createElement('li'); li.innerHTML = choice.text; createChoiceListener(li, choice.index); return li; }); const ul = document.createElement('ul'); Array.from(lis).forEach(li => ul.appendChild(li)); ul.className = "choices current"; return ul; }
javascript
{ "resource": "" }
q31663
placeChoices
train
function placeChoices () { const ul = createChoiceUl(); ul.addEventListener('animationend', () => choicesAnimating = false); choicesAnimating = true; choiceDiv.appendChild(ul); }
javascript
{ "resource": "" }
q31664
clearOldChoices
train
function clearOldChoices () { const oldChoices = choiceDiv.querySelector('.choices.current'); return new Promise(resolve => { oldChoices.addEventListener('transitionend', () => { oldChoices.remove(); resolve(); }); oldChoices.className = "choices old"; }) }
javascript
{ "resource": "" }
q31665
deltaDebugFiles
train
function deltaDebugFiles(file) { try { logging.increaseIndentation(); state.fileUnderTest = file; logging.logTargetChange(file, state.tmpDir); // try removing fileUnderTest completely var backup = makeBackupFileName(); fs.renameSync(file, backup); if (options.predicate.test(state.mainFileTmpDir)) { return true; } else { // if that fails, then restore the fileUnderTest fs.renameSync(backup, file); if (fs.statSync(file).isDirectory()) { var performedAtLeastOneReduction = false; readDirSorted(file).forEach(function (child) { // recurse on all files in the directory performedAtLeastOneReduction |= deltaDebugFiles(child); }); return performedAtLeastOneReduction; } else { // specialized reductions if (isJsOrJsonFile(file)) { return delta_single.reduce(makeOptionsForSingleFileMode(file)); } return false; } } } finally { logging.decreaseIndentation(); } }
javascript
{ "resource": "" }
q31666
train
function () { var http = false; // Use IE's ActiveX items to load the file. if (typeof ActiveXObject != 'undefined') { try { http = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { http = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { http = false; } } // If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document. } else if (window.XMLHttpRequest) { try { http = new XMLHttpRequest(); } catch (e) { http = false; } } return http; }
javascript
{ "resource": "" }
q31667
ifft2DArray
train
function ifft2DArray(ft, ftRows, ftCols) { var tempTransform = new Array(ftRows * ftCols); var nRows = ftRows / 2; var nCols = (ftCols - 1) * 2; // reverse transform columns FFT.init(nRows); var tmpCols = {re: new Array(nRows), im: new Array(nRows)}; var iRow, iCol; for (iCol = 0; iCol < ftCols; iCol++) { for (iRow = nRows - 1; iRow >= 0; iRow--) { tmpCols.re[iRow] = ft[(iRow * 2) * ftCols + iCol]; tmpCols.im[iRow] = ft[(iRow * 2 + 1) * ftCols + iCol]; } //Unnormalized inverse transform FFT.bt(tmpCols.re, tmpCols.im); for (iRow = nRows - 1; iRow >= 0; iRow--) { tempTransform[(iRow * 2) * ftCols + iCol] = tmpCols.re[iRow]; tempTransform[(iRow * 2 + 1) * ftCols + iCol] = tmpCols.im[iRow]; } } // reverse row transform var finalTransform = new Array(nRows * nCols); FFT.init(nCols); var tmpRows = {re: new Array(nCols), im: new Array(nCols)}; var scale = nCols * nRows; for (iRow = 0; iRow < ftRows; iRow += 2) { tmpRows.re[0] = tempTransform[iRow * ftCols]; tmpRows.im[0] = tempTransform[(iRow + 1) * ftCols]; for (iCol = 1; iCol < ftCols; iCol++) { tmpRows.re[iCol] = tempTransform[iRow * ftCols + iCol]; tmpRows.im[iCol] = tempTransform[(iRow + 1) * ftCols + iCol]; tmpRows.re[nCols - iCol] = tempTransform[iRow * ftCols + iCol]; tmpRows.im[nCols - iCol] = -tempTransform[(iRow + 1) * ftCols + iCol]; } //Unnormalized inverse transform FFT.bt(tmpRows.re, tmpRows.im); var indexB = (iRow / 2) * nCols; for (iCol = nCols - 1; iCol >= 0; iCol--) { finalTransform[indexB + iCol] = tmpRows.re[iCol] / scale; } } return finalTransform; }
javascript
{ "resource": "" }
q31668
convolute2DI
train
function convolute2DI(ftSignal, ftFilter, ftRows, ftCols) { var re, im; for (var iRow = 0; iRow < ftRows / 2; iRow++) { for (var iCol = 0; iCol < ftCols; iCol++) { // re = ftSignal[(iRow * 2) * ftCols + iCol] * ftFilter[(iRow * 2) * ftCols + iCol] - ftSignal[(iRow * 2 + 1) * ftCols + iCol] * ftFilter[(iRow * 2 + 1) * ftCols + iCol]; im = ftSignal[(iRow * 2) * ftCols + iCol] * ftFilter[(iRow * 2 + 1) * ftCols + iCol] + ftSignal[(iRow * 2 + 1) * ftCols + iCol] * ftFilter[(iRow * 2) * ftCols + iCol]; // ftSignal[(iRow * 2) * ftCols + iCol] = re; ftSignal[(iRow * 2 + 1) * ftCols + iCol] = im; } } }
javascript
{ "resource": "" }
q31669
crop
train
function crop(data, rows, cols, nRows, nCols) { if (rows === nRows && cols === nCols) { //Do nothing. Returns the same input!!! Be careful return data; } var output = new Array(nCols * nRows); var shiftR = Math.floor((rows - nRows) / 2); var shiftC = Math.floor((cols - nCols) / 2); var destinyRow, sourceRow, i, j; for (i = 0; i < nRows; i++) { destinyRow = i * nCols; sourceRow = (i + shiftR) * cols; for (j = 0; j < nCols; j++) { output[destinyRow + j] = data[sourceRow + (j + shiftC)]; } } return output; }
javascript
{ "resource": "" }
q31670
train
function (Cptfn) { if (!Cptfn || Cptfn.constructor !== Function) { log.error("[CptWrapper] Invalid Component constructor!"); } else { this.cpt = new Cptfn(); this.nodeInstance = null; // reference to set the node instance adirty when an attribute changes this.root=null; // reference to the root template node this.initialized = false; this.needsRefresh = true; // update attribute values for simpler processing var atts = this.cpt.$attributes, att, bnd; if (atts) { for (var k in atts) { att = atts[k]; if (k.match(/^on/)) { // this is a callback if (!att.type) { log.error("Attribute type 'callback' should be set to '" + k + "'"); } else if (att.type !== "callback") { log.error("Attribute type 'callback' should be set to '" + k + "' instead of: " + att.type); att.type = "callback"; } continue; } bnd = att.binding; // set the internal _binding value 0=none 1=1-way 2=2-way if (bnd) { bnd = BINDING_VALUES[bnd]; if (bnd !== undefined) { att._binding = bnd; } else { log.error("Invalid attribute binding value: " + att.binding); att._binding = 0; } } else { att._binding = 0; } // check type if (att.type) { if (att.type === "callback") { log.error("Attribute of type 'callback' must start with 'on' - please rename: " + k); } else if (ATTRIBUTE_TYPES[att.type] === undefined) { log.error("Invalid attribute type: " + att.type); att.type = 'string'; } } else { att.type = 'string'; } } } } }
javascript
{ "resource": "" }
q31671
train
function (change) { var chg = change, cpt = this.cpt; if (change.constructor === Array) { if (change.length > 0) { chg = change[0]; } else { log.error('[CptNode] Invalid change - nbr of changes: '+change.length); return; } } this.needsRefresh=true; var nm = chg.name; // property name if (nm === "") { return; // doesn't make sens (!) } var callControllerCb = true; // true if the onXXXChange() callback must be called on the controller var att, isAttributeChange = false; if (cpt.$attributes) { att = cpt.$attributes[nm]; isAttributeChange = (att !== undefined); if (isAttributeChange) { // adapt type if applicable var t = att.type; if (t) { var v = ATTRIBUTE_TYPES[t].convert(chg.newValue, att); chg.newValue = v; cpt[nm] = v; // change is already raised, no need to trigger another one through json.set() } } if (isAttributeChange && this.nodeInstance) { // notify attribute changes to the node instance (and the host) if attribute has a 2-way binding if (att._binding === 2) { chg.newValue = this.cpt[nm]; // attribute value may have been changed by the controller this.nodeInstance.onAttributeChange(chg); } } if (isAttributeChange) { // check if cb must be called depending on binding mode if (att._binding === 0) { callControllerCb = false; } } } if (callControllerCb) { if (this.processingChange === true) { // don't re-enter the change loop if we are already processing changes return; } this.processingChange = true; try { // calculate the callback name (e.g. onValueChange for the 'value' property) var cbnm=''; if (isAttributeChange) { cbnm=att.onchange; } if (!cbnm) { cbnm = ["$on", nm.charAt(0).toUpperCase(), nm.slice(1), "Change"].join(''); } if (cpt[cbnm]) { cpt[cbnm].call(cpt, chg.newValue, chg.oldValue); } } finally { this.processingChange = false; } } }
javascript
{ "resource": "" }
q31672
createCptWrapper
train
function createCptWrapper(Ctl, cptArgs) { var cw = new CptWrapper(Ctl), att, t, v; // will also create a new controller instance if (cptArgs) { var cpt=cw.cpt, ni=cptArgs.nodeInstance; if (ni.isCptComponent || ni.isCptAttElement) { // set the nodeInstance reference on the component var $attributes=cptArgs.$attributes, $content=cptArgs.$content; cw.nodeInstance = ni; cw.cpt.nodeInstance = ni; if ($attributes) { for (var k in $attributes) { // set the template attribute value on the component instance if ($attributes.hasOwnProperty(k)) { att=cw.cpt.$attributes[k]; t=att.type; v=$attributes[k]; if (t && ATTRIBUTE_TYPES[t]) { // in case of invalid type an error should already have been logged // a type is defined - so let's convert the value v=ATTRIBUTE_TYPES[t].convert(v, att); } json.set(cpt,k,v); } } } if ($content) { if (cpt.$content) { log.error(ni+" Component controller cannot use '$content' for another property than child attribute elements"); } else { // create the content property on the component instance json.set(cpt,"$content",$content); } } } } return cw; }
javascript
{ "resource": "" }
q31673
XKCDPassword
train
function XKCDPassword() { if (!(this instanceof XKCDPassword)) return new XKCDPassword() var self = this events.EventEmitter.call(self) self.wordlist = null self.wordfile = null // if we've got a wordlist at the ready self.ready = false self.initialized = false return this }
javascript
{ "resource": "" }
q31674
fft2d
train
function fft2d(re, im) { var tre = [], tim = [], i = 0; // x-axis for (var y = 0; y < _n; y++) { i = y * _n; for (var x1 = 0; x1 < _n; x1++) { tre[x1] = re[x1 + i]; tim[x1] = im[x1 + i]; } fft1d(tre, tim); for (var x2 = 0; x2 < _n; x2++) { re[x2 + i] = tre[x2]; im[x2 + i] = tim[x2]; } } // y-axis for (var x = 0; x < _n; x++) { for (var y1 = 0; y1 < _n; y1++) { i = x + y1 * _n; tre[y1] = re[i]; tim[y1] = im[i]; } fft1d(tre, tim); for (var y2 = 0; y2 < _n; y2++) { i = x + y2 * _n; re[i] = tre[y2]; im[i] = tim[y2]; } } }
javascript
{ "resource": "" }
q31675
ifft2d
train
function ifft2d(re, im) { var tre = [], tim = [], i = 0; // x-axis for (var y = 0; y < _n; y++) { i = y * _n; for (var x1 = 0; x1 < _n; x1++) { tre[x1] = re[x1 + i]; tim[x1] = im[x1 + i]; } ifft1d(tre, tim); for (var x2 = 0; x2 < _n; x2++) { re[x2 + i] = tre[x2]; im[x2 + i] = tim[x2]; } } // y-axis for (var x = 0; x < _n; x++) { for (var y1 = 0; y1 < _n; y1++) { i = x + y1 * _n; tre[y1] = re[i]; tim[y1] = im[i]; } ifft1d(tre, tim); for (var y2 = 0; y2 < _n; y2++) { i = x + y2 * _n; re[i] = tre[y2]; im[i] = tim[y2]; } } }
javascript
{ "resource": "" }
q31676
formatExpression
train
function formatExpression (expression, firstIndex, walker) { var category = expression.category, codeStmts, code = '', nextIndex = firstIndex; var exprIndex = firstIndex; var expAst; if (category === 'jsexptext') { //compile the expression to detect errors and parse-out identifiers try { expAst = exParser(expression.value); exIdentifiers(expAst).forEach(function(ident){ walker.addGlobalRef(ident); }); codeStmts = ['e', exprIndex, ':[9,"', ('' + expression.value).replace(/"/g, "\\\"").replace(/\\\\"/g, "\\\""), '"']; if (expression.bound === false) { codeStmts.push(',false'); } codeStmts.push(']'); code = codeStmts.join(''); } catch (err) { walker.logError("Invalid expression: '" + expression.value + "'", expression); } nextIndex++; } else { walker.logError("Unsupported expression: " + category, expression); } return { code : code, ast: expAst, exprIdx : exprIndex, nextIndex : nextIndex }; }
javascript
{ "resource": "" }
q31677
formatTextBlock
train
function formatTextBlock (node, nextExprIndex, walker) { var content = node.content, item, exprArray = [], args = [], index = 0; // idx is the index in the $text array // (=args) for (var i = 0; i < content.length; i++) { item = content[i]; if (item.type === "text") { if (index % 2 === 0) { // even index: arg must be a string args[index] = '"' + escapeNewLines(item.value.replace(/"/g, "\\\"")) + '"'; index++; } else { // odd index: arg must be an expression - so add the text to the previous item if (index > 0) { args[index - 1] = args[index - 1].slice(0, -1) + escapeNewLines(item.value.replace(/"/g, "\\\"")) + '"'; } else { // we should never get there as index is odd ! walker.logError("Invalid textblock structure", node); } } } else if (item.type === "expression") { if (index % 2 === 0) { // even index: arg must be a string args[index] = '""'; index++; } var expr = formatExpression(item, nextExprIndex, walker); nextExprIndex = expr.nextIndex; if (expr.code) { if (expr.ast instanceof Array) { //it is a multi-statement expression that is not allowed in this context walker.logError("Invalid expression: " + item.value, item); args[index] = 0; // invalid expression } else { exprArray.push(expr.code); args[index] = expr.exprIdx; // expression index } } else { args[index] = 0; // invalid expression } index++; } } return { exprArg : exprArray.length ? '{' + exprArray.join(",") + '}' : "0", nextIndex : nextExprIndex, blockArgs : args.length ? '[' + args.join(',') + ']' : "[]" }; }
javascript
{ "resource": "" }
q31678
formatValue
train
function formatValue(v,depth) { if (depth===undefined || depth===null) { depth=1; } var tp=typeof(v), val; if (v===null) { return "null"; } else if (v===undefined) { return "undefined"; } else if (tp==='object') { if (depth>0) { var properties=[]; if (v.constructor===Array) { for (var i=0,sz=v.length;sz>i;i++) { val=v[i]; if (typeof(val)==='string') { properties.push(i+':"'+formatValue(val,depth-1)+'"'); } else { properties.push(i+":"+formatValue(val,depth-1)); } } return "["+properties.join(", ")+"]"; } else { var keys=[]; for (var k in v) { if (k.match(/^\+/)) { // this is a meta-data property continue; } keys.push(k); } // sort keys as IE 8 uses a different order than other browsers keys.sort(lexicalSort); for (var i=0,sz=keys.length;sz>i;i++) { val=v[keys[i]]; if (typeof(val)==='string') { properties.push(keys[i]+':"'+formatValue(val,depth-1)+'"'); } else { properties.push(keys[i]+':'+formatValue(val,depth-1)); } } return "{"+properties.join(", ")+"}"; } } else { if (v.constructor===Array) { return "Array["+v.length+"]"; } else if (v.constructor===Function) { return "Function"; } else { return "Object"; } } } else if (tp==='function') { return "Function"; } else { return ''+v; } }
javascript
{ "resource": "" }
q31679
train
function(scope, defaultValue) { var val = evaluator(tree, scope); if( typeof defaultValue === 'undefined') { return val; } else { return (val === undefined || val === null || val != val) ? defaultValue : val; } }
javascript
{ "resource": "" }
q31680
train
function(scope, newValue) { if (!isAssignable) { throw new Error('Expression "' + input + '" is not assignable'); } if (tree.a === 'idn') { json.set(scope, tree.v, newValue); } else if (tree.a === 'bnr') { json.set(evaluator(tree.l, scope), evaluator(tree.r, scope), newValue); } }
javascript
{ "resource": "" }
q31681
setURLParameter
train
function setURLParameter(url, key, value) { if(typeof url !== 'string') { throw new Error('URLs must be a string'); } if(urlUtils) { //node.js url = urlUtils.parse(url); url.search = ((url.search) ? url.search + '&' : '?') + key + '=' + value; url = urlUtils.format(url); } else { //browser url = url.split('?'); url[1] = ((url[1]) ? url[1] + '&' : '') + key + '=' + value; url = url.join('?'); } return url; }
javascript
{ "resource": "" }
q31682
hashcons
train
function hashcons(node) { const keys = t.VISITOR_KEYS[node.type]; if (!keys) return; let hash = hashcode(node); for (const key of keys) { const subNode = node[key]; if (Array.isArray(subNode)) { for (const child of subNode) { if (child) { hash += hashcons(child); } } } else if (subNode) { hash += hashcons(subNode); } } return hash; }
javascript
{ "resource": "" }
q31683
formatError
train
function formatError (error, input) { var message = error.toString().replace(/\s*\(\d*\:\d*\)\s*$/i, ''); // remove line number / col number var beforeMatch = ('' + input.slice(0, error.pos)).match(/.*$/i); var afterMatch = ('' + input.slice(error.pos)).match(/.*/i); var before = beforeMatch ? beforeMatch[0] : ''; var after = afterMatch ? afterMatch[0] : ''; // Prepare line info for txt display var cursorPos = before.length; var errChar = (after.length) ? after.slice(0, 1) : 'X'; var lineStr = before + after; var lncursor = []; for (var i = 0; i < lineStr.length; i++) { lncursor[i] = (i === cursorPos) ? '^' : '-'; } var lineInfoTxt = lineStr + '\r\n' + lncursor.join(''); // Prepare line info for HTML display var lineInfoHTML = ['<span class="code">', before, '<span class="error" title="', message, '">', errChar, '</span>', after.slice(1), '</span>'].join(''); return { description : message, lineInfoTxt : lineInfoTxt, lineInfoHTML : lineInfoHTML, code : lineStr, line : error.loc ? error.loc.line : -1, column : error.loc ? error.loc.column : -1 }; }
javascript
{ "resource": "" }
q31684
raspi_i2c_devname
train
function raspi_i2c_devname() { try { var revisionBuffer = fs.readFileSync('/sys/module/bcm2708/parameters/boardrev'); var revisionInt = parseInt(revisionBuffer.toString(), 10); //console.log('Raspberry Pi board revision: ', revisionInt); // Older boards use i2c-0, newer boards use i2c-1 if ((revisionInt === 2) || (revisionInt === 3)) { return '/dev/i2c-0'; } else { return '/dev/i2c-1'; } } catch(e) { if (e.code === 'ENOENT') { //console.log('Not a Raspberry Pi'); return ''; } else { throw e; } } }
javascript
{ "resource": "" }
q31685
train
function() { // determine if cpt supports template arguments if (this.template) { // as template can be changed dynamically we have to sync the constructor this.ctlConstuctor=this.template.controllerConstructor; } var ctlProto=this.ctlConstuctor.prototype; this.ctlAttributes=ctlProto.$attributes; this.ctlElements=ctlProto.$elements; // load template arguments this.loadCptAttElements(); // load child elements before processing the template var cptArgs={ nodeInstance:this, $attributes:{}, $content:null }; var attributes=cptArgs.$attributes, att; if (this.atts) { // some attributes have been passed to this instance - so we push them to cptArgs // so that they are set on the controller when the template are rendered var atts = this.atts, eh = this.eh, pvs = this.vscope, nm; if (atts) { for (var i = 0, sz = this.atts.length; sz > i; i++) { att = atts[i]; nm = att.name; if (this.ctlAttributes[nm].type!=="template") { attributes[nm]=att.getValue(eh, pvs, null); } } } } if (this.tplAttributes) { var tpa=this.tplAttributes; for (var k in tpa) { // set the template attribute value on the controller if (tpa.hasOwnProperty(k)) { attributes[k]=tpa[k]; } } } if (this.childElements) { cptArgs.$content=this.getControllerContent(); } return cptArgs; }
javascript
{ "resource": "" }
q31686
train
function(localPropOnly) { if (this.ctlWrapper) { this.ctlWrapper.$dispose(); this.ctlWrapper=null; this.controller=null; } this.ctlAttributes=null; this.cleanObjectProperties(localPropOnly); this.ctlConstuctor=null; var tpa=this.tplAttributes; if (tpa) { for (var k in tpa) { if (tpa.hasOwnProperty(k)) { tpa[k].$dispose(); } } } var ag=this._attGenerators; if (ag) { for (var k in ag) { if (ag.hasOwnProperty(k)) { ag[k].$dispose(); } } } var en=this.attEltNodes; if (en) { for (var i=0,sz=en.length; sz>i; i++) { en[i].$dispose(); } this.attEltNodes=null; } }
javascript
{ "resource": "" }
q31687
train
function () { this.attEltNodes=null; this._attGenerators=null; // determine the possible template attribute names var tpAttNames={}, ca=this.ctlAttributes, defaultTplAtt=null, lastTplAtt=null, count=0; for (var k in ca) { if (ca.hasOwnProperty(k) && ca[k].type==="template") { // k is defined in the controller attributes collection // so k is a valid template attribute name tpAttNames[k]=true; count++; if (ca[k].defaultContent) { defaultTplAtt=k; } lastTplAtt=k; } } // if there is only one template attribute it will be automatically considered as default if (!defaultTplAtt) { if (count===1) { defaultTplAtt=lastTplAtt; } else if (count>1) { // error: a default must be defined log.error(this+" A default content element must be defined when multiple content elements are supported"); // use last as default defaultTplAtt=lastTplAtt; } } // check if a default attribute element has to be created and create it if necessary this.manageDefaultAttElt(defaultTplAtt); // Analyze node attributes to see if a template attribute is passed as text attribute var atts=this.atts, att, nm; if (atts) { for (var k in atts) { if (!atts.hasOwnProperty(k)) continue; att=atts[k]; nm=att.name; if (tpAttNames[nm]) { // nm is a template attribute passed as text attribute if (this.tplAttributes && this.tplAttributes[nm]) { // already defined: raise an error log.error(this+" Component attribute '" + nm + "' is defined multiple times - please check"); } else { // create new tpl Attribute Text Node and add it to the tplAttributes collection if (!att.generator) { var txtNode; if (att.value) { // static value txtNode = new $TextNode(0,[""+att.value]); } else { // dynamic value using expressions txtNode = new $TextNode(this.exps,atts[k].textcfg); } if (!this._attGenerators) { this._attGenerators = []; } att.generator = new $CptAttElement(nm,0,0,0,[txtNode]); // name, exps, attcfg, ehcfg, children this._attGenerators.push(att.generator); } // generate a real $CptAttElement using the TextNode as child element var ni=att.generator.createNodeInstance(this); ni.isCptContent=true; if (!this.attEltNodes) { this.attEltNodes=[]; } this.attEltNodes.push(ni); // attribute elements will automatically register through registerAttElement() } } } } this.retrieveAttElements(); }
javascript
{ "resource": "" }
q31688
train
function (defaultTplAtt) { if (!this.children) { return; } // TODO memoize result at prototype level to avoid processing this multiple times var ct=this.getCptContentType(), loadCpts=true; if (ct==="ERROR") { loadCpts=false; log.error(this.info+" Component content cannot mix attribute elements with content elements"); } else if (ct!=="ATTELT") { if (defaultTplAtt) { // ct is CONTENT or INDEFINITE - so we create a default attribute element var catt=new $CptAttElement(defaultTplAtt,0,0,0,this.children); // name, exps, attcfg, ehcfg, children // add this default cpt att element as unique child this.children=[catt]; } else { // there is no defaultTplAtt loadCpts=false; } } if (loadCpts) { var ni, cn=this.children, sz=cn.length; if (!this.attEltNodes) { this.attEltNodes=[]; } for (var i=0;sz>i;i++) { if (!cn[i].isEmptyTextNode) { ni=cn[i].createNodeInstance(this); ni.isCptContent=true; this.attEltNodes.push(ni); // attribute elements will automatically register through registerAttElement() } } } }
javascript
{ "resource": "" }
q31689
train
function() { var aen=this.attEltNodes; if (!aen) { return null; } var attElts=[], cta=this.ctlAttributes; for (var i=0,sz=aen.length; sz>i;i++) { aen[i].registerAttElements(attElts); } // check that all elements are valid (i.e. have valid names) var nm, elt, ok, elts=[], cte=this.ctlElements? this.ctlElements : []; for (var i=0,sz=attElts.length; sz>i; i++) { elt=attElts[i]; nm=elt.name; ok=true; if (cta && cta[nm]) { // valid tpl attribute if (!this.tplAttributes) { this.tplAttributes={}; } this.tplAttributes[nm]=elt; ok = false; } else { if (!nm) { log.error(this+" Invalid attribute element (unnamed)"); ok=false; } else if (!cte[nm]) { log.error(this+" Invalid attribute element: @"+nm); ok=false; } } if (ok) { elts.push(elt); } } if (elts.length===0) { elts=null; } this.childElements=elts; return elts; }
javascript
{ "resource": "" }
q31690
train
function() { var ce=this.childElements; if (!ce || !ce.length) { return; } var cw; for (var i=0,sz=ce.length;sz>i;i++) { cw=ce[i].ctlWrapper; if (cw && !cw.initialized) { cw.init(null,this.controller); } } }
javascript
{ "resource": "" }
q31691
train
function (evt) { var evh = this.evtHandlers, et = evt.type; if (evh) { for (var i = 0, sz = evh.length; sz > i; i++) { if (evh[i].evtType === et) { evh[i].executeCb(evt, this.eh, this.parent.vscope); break; } } } }
javascript
{ "resource": "" }
q31692
train
function (prevNode, newNode) { if (prevNode === newNode) { return; } TNode.replaceNodeBy.call(this,prevNode, newNode); var aen=this.attEltNodes; if (aen) { for (var i=0,sz=aen.length; sz>i;i++) { aen[i].replaceNodeBy(prevNode, newNode); } } }
javascript
{ "resource": "" }
q31693
train
function() { var c=[], ce=this.childElements, celts=this.ctlElements, eltType; if (ce && ce.length) { for (var i=0, sz=ce.length;sz>i;i++) { eltType=celts[ce[i].name].type; if (eltType==="component") { c.push(ce[i].controller); } else if (eltType==="template") { c.push(ce[i]); } else { log.error(this+" Invalid element type: "+eltType); } } } return c.length>0? c : null; }
javascript
{ "resource": "" }
q31694
train
function () { if (this.edirty) { var en=this.attEltNodes; if (en) { for (var i=0,sz=en.length; sz>i; i++) { en[i].refresh(); } // if content changed we have to rebuild childElements this.retrieveAttElements(); this.initChildComponents(); } // Change content of the controller json.set(this.controller,"$content",this.getControllerContent()); this.edirty=false; } // warning: the following refresh may change the component type and // as such ctlWrapper could become null if new component is a template $CptNode.refresh.call(this); if (this.ctlWrapper) { // refresh cpt through $refresh if need be this.ctlWrapper.refresh(); } }
javascript
{ "resource": "" }
q31695
getAction
train
function getAction(controllerName, actionName) { controllerName = controllerName.camelize(); var controller = app.controllers[controllerName]; if (controller === undefined && app.models[controllerName]) controller = defaultController; if (controller) return controller[actionName || 'index']; else return null; }
javascript
{ "resource": "" }
q31696
addSingleRoute
train
function addSingleRoute(verb, routePath, controllerName, actionName) { // add controller and action fields to the request var reqExtender = function(req, res, next) { req.controller = controllerName; req.action = actionName || 'index'; next(); }; var params = [routePath, reqExtender]; params = params.concat(getPolicies(controllerName, actionName)); params.push(getAction(controllerName, actionName)); app[verb].apply(app, params); }
javascript
{ "resource": "" }
q31697
train
function(req, res, next) { req.controller = controllerName; req.action = actionName || 'index'; next(); }
javascript
{ "resource": "" }
q31698
getPolicies
train
function getPolicies(controller, action) { var policies = config.policies; var currentPolicies = []; if (policies[controller] && policies[controller][action]) { currentPolicies = policies[controller][action]; } else if (Object.isString(policies[controller])) { currentPolicies = policies[controller]; } else if (policies[controller] && policies[controller]['*']) { currentPolicies = policies[controller]['*']; } else if (policies['*']) { currentPolicies = policies['*']; } if (currentPolicies === true) { currentPolicies = []; } if (!Object.isArray(currentPolicies)) { currentPolicies = [currentPolicies]; } currentPolicies = currentPolicies.map(function(policy) { var policyPath = path.join(config.rootDir, config.paths.policies, policy); return require(policyPath); }); return currentPolicies; }
javascript
{ "resource": "" }
q31699
addResourceRoute
train
function addResourceRoute(routePath, controllerName) { resourceRouting.forEach(function(route) { var actionPath = route.path.replace(':controller', controllerName); route.verbs.forEach(function (verb) { addSingleRoute(verb, actionPath, controllerName, route.target.action); }); }); }
javascript
{ "resource": "" }