_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q900
define
train
function define(path, factoryOrObject, options) { /* $_mod.def('/baz$3.0.0/lib/index', function(require, exports, module, __filename, __dirname) { // module source code goes here }); */ var globals = options && options.globals; definitions[path] = factoryOrObject; if (globals) { var target = win || global; for (var i=0;i<globals.length; i++) { var globalVarName = globals[i]; var globalModule = loadedGlobalsByRealPath[path] = requireModule(path); target[globalVarName] = globalModule.exports; } } }
javascript
{ "resource": "" }
q901
normalizePathParts
train
function normalizePathParts(parts) { // IMPORTANT: It is assumed that parts[0] === "" because this method is used to // join an absolute path to a relative path var i; var len = 0; var numParts = parts.length; for (i = 0; i < numParts; i++) { var part = parts[i]; if (part === '.') { // ignore parts with just "." /* // if the "." is at end of parts (e.g. ["a", "b", "."]) then trim it off if (i === numParts - 1) { //len--; } */ } else if (part === '..') { // overwrite the previous item by decrementing length len--; } else { // add this part to result and increment length parts[len] = part; len++; } } if (len === 1) { // if we end up with just one part that is empty string // (which can happen if input is ["", "."]) then return // string with just the leading slash return '/'; } else if (len > 2) { // parts i s // ["", "a", ""] // ["", "a", "b", ""] if (parts[len - 1].length === 0) { // last part is an empty string which would result in trailing slash len--; } } // truncate parts to remove unused parts.length = len; return parts.join('/'); }
javascript
{ "resource": "" }
q902
_gpfReduceContext
train
function _gpfReduceContext (path, reducer) { var rootContext, pathToReduce; if (path[_GPF_START] === "gpf") { rootContext = gpf; pathToReduce = _gpfArrayTail(path); } else { rootContext = _gpfMainContext; pathToReduce = path; } return pathToReduce.reduce(reducer, rootContext); }
javascript
{ "resource": "" }
q903
train
function (definitions) { var result = [], len = definitions.length, idx, definition; for (idx = 0; idx < len; ++idx) { definition = definitions[idx]; if (!(definition instanceof gpf.Parameter)) { definition = this._createFromObject(definition); } result.push(definition); } return result; }
javascript
{ "resource": "" }
q904
train
function (definition) { var result = new gpf.Parameter(), typeDefaultValue; if (definition === gpf.Parameter.VERBOSE || definition.prefix === gpf.Parameter.VERBOSE) { definition = { name: "verbose", description: "Enable verbose mode", type: "boolean", defaultValue: false, prefix: gpf.Parameter.VERBOSE }; } else if (definition === gpf.Parameter.HELP || definition.prefix === gpf.Parameter.HELP) { definition = { name: "help", description: "Display help", type: "boolean", defaultValue: false, prefix: gpf.Parameter.HELP }; } gpf.json.load(result, definition); // name is required if (!result._name) { gpf.Error.paramsNameRequired(); } if (!result._multiple) { /** * When multiple is used, the default value will be an array * if not specified. * Otherwise, we get the default value based on the type */ typeDefaultValue = this.DEFAULTS[result._type]; if (undefined === typeDefaultValue) { gpf.Error.paramsTypeUnknown(); } if (result.hasOwnProperty("_defaultValue")) { result._defaultValue = gpf.value(result._defaultValue, typeDefaultValue, result._type); } } return result; }
javascript
{ "resource": "" }
q905
train
function (parameters, argumentsToParse) { var result = {}, len, idx, argument, parameter, name, lastNonPrefixIdx = 0; parameters = gpf.Parameter.create(parameters); len = argumentsToParse.length; for (idx = 0; idx < len; ++idx) { // Check if a prefix was used and find parameter argument = this.getPrefixValuePair(argumentsToParse[idx]); if (argument instanceof Array) { parameter = this.getOnPrefix(parameters, argument[0]); argument = argument[1]; } else { parameter = this.getOnPrefix(parameters, lastNonPrefixIdx); lastNonPrefixIdx = parameters.indexOf(parameter) + 1; } // If no parameter corresponds, ignore if (!parameter) { // TODO maybe an error might be more appropriate continue; } // Sometimes, the prefix might be used without value if (undefined === argument) { if ("boolean" === parameter._type) { argument = !parameter._defaultValue; } else { // Nothing to do with it // TODO maybe an error might be more appropriate continue; } } // Convert the value to match the type // TODO change when type will be an object argument = gpf.value(argument, parameter._defaultValue, parameter._type); // Assign the corresponding member of the result object name = parameter._name; if (parameter._multiple) { if (undefined === result[name]) { result[name] = []; } result[name].push(argument); if (parameter._prefix === "") { --lastNonPrefixIdx; } } else { // The last one wins result[name] = argument; } } this._finalizeParse(parameters, result); return result; }
javascript
{ "resource": "" }
q906
train
function (parameters, result) { var len, idx, parameter, name, value; len = parameters.length; for (idx = 0; idx < len; ++idx) { parameter = parameters[idx]; name = parameter._name; if (undefined === result[name]) { if (parameter._required) { gpf.Error.paramsRequiredMissing({ name: name }); } value = parameter._defaultValue; if (undefined !== value) { if (parameter._multiple) { value = [value]; } result[name] = value; } else if (parameter._multiple) { result[name] = []; } } } }
javascript
{ "resource": "" }
q907
_gpfClassSuperCreateWeakBoundWithSameSignature
train
function _gpfClassSuperCreateWeakBoundWithSameSignature (that, $super, superMethod) { var definition = _gpfFunctionDescribe(superMethod); definition.body = "return _superMethod_.apply(this === _$super_ ? _that_ : this, arguments);"; return _gpfFunctionBuild(definition, { _that_: that, _$super_: $super, _superMethod_: superMethod }); }
javascript
{ "resource": "" }
q908
train
function (method, methodName, superMembers) { return { _method_: method, _methodName_: methodName, _superMembers_: superMembers, _classDef_: this }; }
javascript
{ "resource": "" }
q909
train
function (method, methodName, superMembers) { // Keep signature var description = _gpfFunctionDescribe(method); description.body = this._superifiedBody; return _gpfFunctionBuild(description, this._getSuperifiedContext(method, methodName, superMembers)); }
javascript
{ "resource": "" }
q910
_gpfStreamPipeToFlushableWrite
train
function _gpfStreamPipeToFlushableWrite (intermediate, destination) { var state = _gpfStreamPipeAllocateState(intermediate, destination), read = _gpfStreamPipeAllocateRead(state), iFlushableIntermediate = state.iFlushableIntermediate, iFlushableDestination = state.iFlushableDestination, iWritableIntermediate = state.iWritableIntermediate; read(); return { flush: function () { return _gpfStreamPipeCheckIfReadError(state) || iFlushableIntermediate.flush() .then(function () { return iFlushableDestination.flush(); }); }, write: function (data) { read(); return _gpfStreamPipeCheckIfReadError(state) || _gpfStreamPipeWrapWrite(state, iWritableIntermediate.write(data)); } }; }
javascript
{ "resource": "" }
q911
_gpfStreamPipe
train
function _gpfStreamPipe (source, destination) { _gpfIgnore(destination); var iReadableStream = _gpfStreamQueryReadable(source), iWritableStream = _gpfStreamPipeToWritable(_gpfArrayTail(arguments)), iFlushableStream = _gpfStreamPipeToFlushable(iWritableStream); try { return iReadableStream.read(iWritableStream) .then(function () { return iFlushableStream.flush(); }); } catch (e) { return Promise.reject(e); } }
javascript
{ "resource": "" }
q912
_gpfLoadSources
train
function _gpfLoadSources () { //jshint ignore:line var sourceListContent = _gpfSyncReadForBoot(gpfSourcesPath + "sources.json"), _gpfSources = _GpfFunc("return " + sourceListContent)(), allContent = [], idx = 0; for (; idx < _gpfSources.length; ++idx) { _gpfProcessSource(_gpfSources[idx], allContent); } return allContent.join("\n"); }
javascript
{ "resource": "" }
q913
_gpfBuildPropertyFunc
train
function _gpfBuildPropertyFunc (template, member) { var src, params, start, end; // Replace all occurrences of _MEMBER_ with the right name src = template.toString().split("_MEMBER_").join(member); // Extract parameters start = src.indexOf("(") + 1; end = src.indexOf(")", start) - 1; params = src.substr(start, end - start + 1).split(",").map(function (name) { return name.trim(); }); // Extract body start = src.indexOf("{") + 1; end = src.lastIndexOf("}") - 1; src = src.substr(start, end - start + 1); return _gpfFunc(params, src); }
javascript
{ "resource": "" }
q914
train
function(object, customizer) { var foundStack = [], //Stack to keep track of discovered objects queueOfModifiers = [], //Necessary to change our JSON as we take elements from the queue (BFS algorithm) queue = []; //queue of JSON elements, following the BFS algorithm //We instantiate our result root. var result = _.isArray(object) ? [] : {}; //We first put all the JSON source in our queues queue.push(object); queueOfModifiers.push(new ObjectEditor(object, "")); var positionStack; var nextInsertion; //BFS algorithm while(queue.length > 0) { //JSON to be modified and its editor var value = queue.shift(); var editor = queueOfModifiers.shift(); //The path that leads to this JSON, so we can build other paths from it var path = editor.path; //We first attempt to make any personalized replacements //If customizer doesn't affect the value, customizer(value) returns undefined and we jump this if if(customizer !== undefined) { //By using this variable, customizer(value) is called only once. var customizedValue = customizer(value); if(customizedValue !== undefined) value = customizedValue; } if(typeof value === "object") { positionStack = _.chain(foundStack) .map("value") .indexOf(value) .value(); //If the value has already been discovered, we only fix its circular reference if(positionStack !== -1) { nextInsertion = foundStack[positionStack].makePathName(); } else { //At the first time we discover a certain value, we put it in the stack foundStack.push(new FoundObject(value, path)); nextInsertion = value; for(var component in value) { if(_.has(value, component)) { queue.push(value[component]); var newPath = path + "[" + component + "]"; queueOfModifiers.push(new ObjectEditor(result, newPath)); } } } } //If it's an elementary value, it can't be circular, so we just put this value in our JSON result. else { nextInsertion = value; } editor.editObject(nextInsertion); } return result; }
javascript
{ "resource": "" }
q915
train
function (newPrototype) { _gpfObjectForEach(this._initialDefinition, function (value, memberName) { if (!memberName.startsWith("$")) { newPrototype[memberName] = value; } }, this); }
javascript
{ "resource": "" }
q916
_gpfEventsIsValidHandler
train
function _gpfEventsIsValidHandler (eventHandler) { var type = typeof eventHandler, validator = _gpfEventsHandlerValidators[type]; if (validator === undefined) { return false; } return validator(eventHandler); }
javascript
{ "resource": "" }
q917
_gpfEventsTriggerHandler
train
function _gpfEventsTriggerHandler (event, eventsHandler, resolvePromise) { var eventHandler = _getEventHandler(event, eventsHandler); eventHandler(event); if (undefined !== resolvePromise) { resolvePromise(event); } }
javascript
{ "resource": "" }
q918
_gpfEventsFire
train
function _gpfEventsFire (event, params, eventsHandler) { /*jshint validthis:true*/ // will be invoked with apply _gpfAssert(_gpfEventsIsValidHandler(eventsHandler), "Expected a valid event handler"); if (!(event instanceof _GpfEvent)) { event = new gpf.events.Event(event, params, this); } return new Promise(function (resolve/*, reject*/) { // This is used both to limit the number of recursion and increase the efficiency of the algorithm. if (++_gpfEventsFiring > 10) { // Too much recursion, use setTimeout to free some space on the stack setTimeout(_gpfEventsTriggerHandler.bind(null, event, eventsHandler, resolve), 0); } else { _gpfEventsTriggerHandler(event, eventsHandler); resolve(event); } --_gpfEventsFiring; }); }
javascript
{ "resource": "" }
q919
exists
train
function exists(filepath) { const cached = existsCache.has(filepath); // Only return positive to allow for generated files if (cached) return true; const filepathExists = fs.existsSync(filepath); if (filepathExists) existsCache.add(filepath); return filepathExists; }
javascript
{ "resource": "" }
q920
_gpfDefineEntitiesAdd
train
function _gpfDefineEntitiesAdd (entityDefinition) { _gpfAssert(entityDefinition._instanceBuilder !== null, "Instance builder must be set"); _gpfAssert(!_gpfDefineEntitiesFindByConstructor(entityDefinition.getInstanceBuilder()), "Already added"); _gpfDefinedEntities.push(entityDefinition); }
javascript
{ "resource": "" }
q921
train
function (unnormalizedPath) { var path = _gpfPathNormalize(unnormalizedPath); return new Promise(function (resolve) { _gpfNodeFs.exists(path, resolve); }) .then(function (exists) { if (exists) { return _gpfFsNodeFsCallWithPath("stat", path) .then(function (stats) { return { fileName: _gpfNodePath.basename(path), filePath: _gpfPathNormalize(_gpfNodePath.resolve(path)), size: stats.size, createdDateTime: stats.ctime, modifiedDateTime: stats.mtime, type: _gpfFsNodeGetType(stats) }; }); } return { type: _GPF_FS_TYPES.NOT_FOUND }; }); }
javascript
{ "resource": "" }
q922
getOptions
train
function getOptions () { return { compress: ('compress' in program) ? program.compress : false, debug: ('debug' in program) ? program.debug : false, deploy: false, grep: ('grep' in program) ? program.grep : false, invert: ('invert' in program) ? program.invert : false, maps: ('maps' in program) ? program.maps : false, reload: ('reload' in program) ? program.reload : false, script: ('script' in program) ? program.script : false, serve: ('serve' in program) ? program.serve : false, watch: false }; }
javascript
{ "resource": "" }
q923
define
train
function define(JSFile, utils) { return class JSXFile extends JSFile { /** * Parse 'content' for dependency references * @param {String} content * @returns {Array} */ parseDependencyReferences(content) { const references = super.parseDependencyReferences(content); references[0].push({ context: "require('react')", match: 'react', id: 'react' }); return references; } /** * Transpile file contents * @param {Object} buildOptions * - {Boolean} batch * - {Boolean} bootstrap * - {Boolean} boilerplate * - {Boolean} browser * - {Boolean} bundle * - {Boolean} compress * - {Boolean} helpers * - {Array} ignoredFiles * - {Boolean} import * - {Boolean} watchOnly * @param {Function} fn(err) */ transpile(buildOptions, fn) { super.transpile(buildOptions, (err) => { if (err) return fn && fn(); this.prependContent("var React = $m['react'].exports;"); fn(); }); } }; }
javascript
{ "resource": "" }
q924
_gpfIsLiteralObject
train
function _gpfIsLiteralObject (value) { return value instanceof Object && _gpfObjectToString.call(value) === "[object Object]" && Object.getPrototypeOf(value) === Object.getPrototypeOf({}); }
javascript
{ "resource": "" }
q925
startAppServer
train
function startAppServer(fn) { if (!checkingAppServerPort) { server = fork(appServer.file, [], appServer.options); server.on('exit', code => { checkingAppServerPort = false; server.removeAllListeners(); server = null; fn(Error('failed to start server')); }); checkingAppServerPort = true; waitForPortOpen(appServer.port, fn); } }
javascript
{ "resource": "" }
q926
echo
train
function echo(command) { return command.getUser() .then((user) => { const content = (command.parent.text || '').split('\n').map((line) => `> ${line}`); content.unshift(`@${user.username} said:`); command.reply(content.join('\n')); }); }
javascript
{ "resource": "" }
q927
_gpfRequireConfigureAddOption
train
function _gpfRequireConfigureAddOption (name, handler, highPriority) { if (highPriority) { _gpfRequireConfigureOptionNames.unshift(name); } else { _gpfRequireConfigureOptionNames.push(name); } _gpfRequireConfigureHandler[name] = handler; }
javascript
{ "resource": "" }
q928
loadPluginsFromDir
train
function loadPluginsFromDir(dir, config) { try { fs .readdirSync(dir) .filter(resource => { if (path.basename(dir) != 'plugins') return RE_PLUGIN.test(resource); return RE_JS_FILE.test(resource) || fs.statSync(path.join(dir, resource)).isDirectory(); }) .forEach(resource => { registerPlugin(path.join(dir, resource), config); }); } catch (err) { /* ignore */ } }
javascript
{ "resource": "" }
q929
registerPlugin
train
function registerPlugin(resource, config, silent) { let module; try { module = 'string' == typeof resource ? require(resource) : resource; } catch (err) { return warn(`unable to load plugin ${strong(resource)}`); } if (!('register' in module)) return warn(`invalid plugin ${strong(resource)}`); module.register(config); if (!silent) print(`registered plugin ${strong(module.name)}`, 0); }
javascript
{ "resource": "" }
q930
_gpfJsonStringifyPolyfill
train
function _gpfJsonStringifyPolyfill (value, replacer, space) { return _gpfJsonStringifyMapping[typeof value](value, _gpfJsonStringifyCheckReplacer(replacer), _gpfJsonStringifyCheckSpaceValue(space)); }
javascript
{ "resource": "" }
q931
_gpfFunctionDescribe
train
function _gpfFunctionDescribe (functionToDescribe) { var result = {}; _gpfFunctionDescribeName(functionToDescribe, result); _gpfFunctionDescribeSource(functionToDescribe, result); return result; }
javascript
{ "resource": "" }
q932
train
function (event) { var eventsHandler; if (event && event.type() === _gpfI.IWritableStream.EVENT_ERROR) { gpfFireEvent.call(this, event, this._eventsHandler); } else if (0 === this._buffer.length) { eventsHandler = this._eventsHandler; this._eventsHandler = null; gpfFireEvent.call(this, _gpfI.IWritableStream.EVENT_READY, eventsHandler); } else { this._stream.write(this._buffer.shift(), this._flushed.bind(this)); } }
javascript
{ "resource": "" }
q933
train
function (name) { var newName; if (gpf.xml.isValidName(name)) { return name; } // Try with a starting _ newName = "_" + name; if (!gpf.xml.isValidName(newName)) { gpf.Error.xmlInvalidName(); } return newName; }
javascript
{ "resource": "" }
q934
train
function (char) { var newState, tagsOpened = 0 < this._openedTags.length; if ("#" === char) { this._hLevel = 1; newState = this._parseTitle; } else if ("*" === char || "0" <= char && "9" >= char ) { if (char !== "*") { this._numericList = 1; } else { this._numericList = 0; } newState = this._parseList; tagsOpened = false; // Wait for disambiguation } else if (" " !== char && "\t" !== char && "\n" !== char) { if (tagsOpened) { this._output(" "); tagsOpened = false; // Avoid closing below } else { this._openTag("p"); } newState = this._parseContent(char); if (!newState) { newState = this._parseContent; } } if (tagsOpened) { this._closeTags(); } return newState; }
javascript
{ "resource": "" }
q935
train
function () { var url = this._linkUrl.join(""), text = this._linkText.join(""); if (0 === this._linkType) { this._output("<a href=\""); this._output(url); this._output("\">"); this._output(text); this._output("</a>"); } else if (1 === this._linkType) { this._output("<img src=\""); this._output(url); this._output("\" alt=\""); this._output(text); this._output("\" title=\""); this._output(text); this._output("\">"); } return this._parseContent; }
javascript
{ "resource": "" }
q936
train
function (event) { var reader = event.target, buffer, len, result, idx; _gpfAssert(reader === this._reader, "Unexpected change of reader"); if (reader.error) { gpfFireEvent.call(this, gpfI.IReadableStream.ERROR, { // According to W3C // http://www.w3.org/TR/domcore/#interface-domerror error: { name: reader.error.name, message: reader.error.message } }, this._eventsHandler ); } else if (reader.readyState === FileReader.DONE) { buffer = new Int8Array(reader.result); len = buffer.length; result = []; for (idx = 0; idx < len; ++idx) { result.push(buffer[idx]); } gpfFireEvent.call(this, gpfI.IReadableStream.EVENT_DATA, {buffer: result}, this._eventsHandler); } }
javascript
{ "resource": "" }
q937
train
function (domObject) { var selector = this._selector; if (selector) { if (this._globalSelector) { return document.querySelector(selector); } else { return domObject.querySelector(selector); } } return undefined; }
javascript
{ "resource": "" }
q938
_getHandlerAttribute
train
function _getHandlerAttribute (member, handlerAttributeArray) { var attribute; if (1 !== handlerAttributeArray.length()) { gpf.Error.htmlHandlerMultiplicityError({ member: member }); } attribute = handlerAttributeArray.get(0); if (!(attribute instanceof _HtmEvent)) { return attribute; } return null; }
javascript
{ "resource": "" }
q939
_onResize
train
function _onResize () { _width = window.innerWidth; _height = window.innerHeight; var orientation, orientationChanged = false, toRemove = [], toAdd = []; if (_width > _height) { orientation = "gpf-landscape"; } else { orientation = "gpf-portrait"; } if (_orientation !== orientation) { toRemove.push(_orientation); _orientation = orientation; toAdd.push(orientation); orientationChanged = true; } gpf.html.alterClass(document.body, toAdd, toRemove); _broadcaster.broadcastEvent("resize", { width: _width, height: _height }); if (orientationChanged) { _broadcaster.broadcastEvent("rotate", { orientation: orientation }); } }
javascript
{ "resource": "" }
q940
_onScroll
train
function _onScroll () { _scrollY = window.scrollY; if (_monitorTop && _dynamicCss) { _updateDynamicCss(); } _broadcaster.broadcastEvent("scroll", { top: _scrollY }); }
javascript
{ "resource": "" }
q941
create
train
function create(options, callback) { var t = new TestObject(options); t.save(null, { success: callback }); }
javascript
{ "resource": "" }
q942
normalize
train
function normalize(obj) { if (obj === null || typeof obj !== 'object') { return JSON.stringify(obj); } if (obj instanceof Array) { return '[' + obj.map(normalize).join(', ') + ']'; } var answer = '{'; for (var key of Object.keys(obj).sort()) { answer += key + ': '; answer += normalize(obj[key]); answer += ', '; } answer += '}'; return answer; }
javascript
{ "resource": "" }
q943
_gpfFuncUnsafe
train
function _gpfFuncUnsafe (params, source) { var args; if (!params.length) { return _GpfFunc(source); } args = [].concat(params); args.push(source); return _GpfFunc.apply(null, args); }
javascript
{ "resource": "" }
q944
_gpfFunc
train
function _gpfFunc (params, source) { if (undefined === source) { return _gpfFuncImpl([], params); } return _gpfFuncImpl(params, source); }
javascript
{ "resource": "" }
q945
start
train
function start(id) { if (!timers[id]) { timers[id] = { start: 0, elapsed: 0 }; } timers[id].start = process.hrtime(); }
javascript
{ "resource": "" }
q946
pause
train
function pause(id) { if (!timers[id]) return start(id); timers[id].elapsed += msDiff(process.hrtime(), timers[id].start); }
javascript
{ "resource": "" }
q947
stop
train
function stop(id, formatted) { const elapsed = timers[id].elapsed + msDiff(process.hrtime(), timers[id].start); clear(id); return formatted ? format(elapsed) : elapsed; }
javascript
{ "resource": "" }
q948
msDiff
train
function msDiff(t1, t2) { t1 = (t1[0] * 1e9 + t1[1]) / 1e6; t2 = (t2[0] * 1e9 + t2[1]) / 1e6; return Math.ceil((t1 - t2) * 100) / 100; }
javascript
{ "resource": "" }
q949
_gpfRequireLoad
train
function _gpfRequireLoad (name) { var me = this; return _gpfLoadOrPreload(me, name) .then(function (content) { return me.preprocess({ name: name, content: content, type: _gpfPathExtension(name).toLowerCase() }); }) .then(function (resource) { return _gpfLoadGetProcessor(resource).call(me, resource.name, resource.content); }); }
javascript
{ "resource": "" }
q950
upToSourceRow
train
function upToSourceRow (target) { var current = target; while (current && (!current.tagName || current.tagName.toLowerCase() !== "tr")) { current = current.parentNode; } return current; }
javascript
{ "resource": "" }
q951
refreshSourceRow
train
function refreshSourceRow (target, source) { var row = upToSourceRow(target), newRow = rowFactory(source, source.getIndex()); sourceRows.replaceChild(newRow, row); updateSourceRow(source); }
javascript
{ "resource": "" }
q952
reload
train
function reload () { sourceRows.innerHTML = ""; // Clear content sources.forEach(function (source, index) { if (flavor && !flavor[index]) { return; } sourceRows.appendChild(rowFactory(source, index)); updateSourceRow(source); }); }
javascript
{ "resource": "" }
q953
compare
train
function compare (checkDictionary, path, pathContent) { var subPromises = []; pathContent.forEach(function (name) { var JS_EXT = ".js", JS_EXT_LENGTH = JS_EXT.length, contentFullName = path + name, contentFullNameLength = contentFullName.length; if (contentFullNameLength > JS_EXT_LENGTH && contentFullName.indexOf(JS_EXT) === contentFullNameLength - JS_EXT_LENGTH) { contentFullName = contentFullName.substring(START, contentFullNameLength - JS_EXT_LENGTH); if (checkDictionary[contentFullName] === "obsolete") { checkDictionary[contentFullName] = "exists"; } else { checkDictionary[contentFullName] = "new"; } } else if (name.indexOf(".") === NOT_FOUND) { subPromises.push(gpf.http.get("/fs/src/" + contentFullName) .then(function (response) { return JSON.parse(response.responseText); }) .then(function (subPathContent) { return compare(checkDictionary, contentFullName + "/", subPathContent); })); } }); if (!subPromises.length) { return Promise.resolve(); } return Promise.all(subPromises); }
javascript
{ "resource": "" }
q954
signupUser
train
async function signupUser(form) { await client.connect(); try { await api.signup( { credentials: { login: form.login.value, password: form.password.value }, profile: { email: form.email.value } }, 'user' ); displayMessage( 'Account created', 'Your account has been created, please check your emails to confirm your account', 'is-success' ); goTo('login'); } catch (e) { displayMessage('Account not created', `Your account could not been created. Cause: ${e.message}`, 'is-danger'); } }
javascript
{ "resource": "" }
q955
readYaml
train
function readYaml(filePath) { return new Promise((resolve, reject) => { if (!filePath || typeof filePath !== 'string') { throw new Error('Path must be a string'); } fs.readFile(filePath, (err, data) => { if (err) { return reject(err); } // Remove UTF-8 BOM if present if (data.length >= 3 && data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf) { data = data.slice(3); } try { return resolve(yaml.safeLoad(data)); } catch (yamlerr) { return reject(yamlerr); } }); }); }
javascript
{ "resource": "" }
q956
_gpfPathJoin
train
function _gpfPathJoin (path) { var splitPath = _gpfPathDecompose(path); _gpfArrayTail(arguments).forEach(_gpfPathAppend.bind(null, splitPath)); return splitPath.join("/"); }
javascript
{ "resource": "" }
q957
_gpfPathRelative
train
function _gpfPathRelative (from, to) { var length, splitFrom = _gpfPathDecompose(from), splitTo = _gpfPathDecompose(to); _gpfPathShiftIdenticalBeginning(splitFrom, splitTo); // For each remaining part in from, unshift .. in to length = splitFrom.length; while (length--) { splitTo.unshift(".."); } return splitTo.join("/"); }
javascript
{ "resource": "" }
q958
train
function (path) { var name = _gpfPathName(path), pos = name.lastIndexOf("."); if (pos === _GPF_NOT_FOUND) { return name; } return name.substring(_GPF_START, pos); }
javascript
{ "resource": "" }
q959
sync
train
function sync(str, options) { var tmpl = this.cache(options) || this.cache(options, this.engine.compile(str, options)); return tmpl(options); }
javascript
{ "resource": "" }
q960
train
function (str, options, cb) { var ECT = this.engine; var tmpl = this.cache(options) || this.cache(options, new ECT({ root: { page: str }})); tmpl.render('page', options, cb); }
javascript
{ "resource": "" }
q961
train
function (str, options, cb) { var tmpl = this.cache(options) || this.cache(options, this.engine.compile(str, options)); tmpl.eval(options, function(str){ cb(null, str); }); }
javascript
{ "resource": "" }
q962
train
function (str, options, cb) { var self = this; if (self.cache(options)) return cb(null, self.cache(options)); if (options.filename) { options.paths = options.paths || [dirname(options.filename)]; } // If this.cache is enabled, compress by default if (options.compress !== true && options.compress !== false) { options.compress = options.cache || false; } var initial = this.engine(str); // Special handling for stylus js api functions // given { define: { foo: 'bar', baz: 'quux' } } // runs initial.define('foo', 'bar').define('baz', 'quux') var allowed = ['set', 'include', 'import', 'define', 'use']; var special = {} var normal = clone(options); for (var v in options) { if (allowed.indexOf(v) > -1) { special[v] = options[v]; delete normal[v]; } } // special options through their function names for (var k in special) { for (var v in special[k]) { initial[k](v, special[k][v]); } } // normal options through set() for (var k in normal) { initial.set(k, normal[k]); } initial.render(function (err, res) { if (err) return cb(err); self.cache(options, res); cb(null, res); }); }
javascript
{ "resource": "" }
q963
askResetPassword
train
async function askResetPassword(form) { await client.connect(); try { await api.askResetPassword( { login: form.login.value }, "user" ); displayMessage( "Reset password", "A link was sent to reset your password", "is-success" ); goTo("login"); } catch (e) { displayMessage( "Reset password", `Failed to send the link to reset your password. Cause: ${e.message}`, "is-danger" ); } }
javascript
{ "resource": "" }
q964
confirmResetPassword
train
async function confirmResetPassword(form) { await client.connect(); try { console.log("token : ", sessionStorage.getItem("token")); await api.confirmResetPassword( { token: sessionStorage.getItem("token"), firstPassword: form.firstPassword.value, secondPassword: form.secondPassword.value }, "user" ); displayMessage("Reset password", "Password changed", "is-success"); goTo("login"); sessionStorage.clear(); } catch (e) { displayMessage( "Reset password", `Failed to reset the password. Cause: ${e.message}`, "is-danger" ); } }
javascript
{ "resource": "" }
q965
_gpfHttpSetRequestImplIf
train
function _gpfHttpSetRequestImplIf (host, httpRequestImpl) { var result = _gpfHttpRequestImpl; if (host === _gpfHost) { _gpfHttpRequestImpl = httpRequestImpl; } return result; }
javascript
{ "resource": "" }
q966
_gpfProcessAlias
train
function _gpfProcessAlias (method, url, data) { if (typeof url === "string") { return _gpfHttpRequest({ method: method, url: url, data: data }); } return _gpfHttpRequest(Object.assign({ method: method }, url)); }
javascript
{ "resource": "" }
q967
_gpfSerialPropertyCheck
train
function _gpfSerialPropertyCheck (property) { var clonedProperty = Object.assign(property); [ _gpfSerialPropertyCheckName, _gpfSerialPropertyCheckType, _gpfSerialPropertyCheckRequired, _gpfSerialPropertyCheckReadOnly ].forEach(function (checkFunction) { checkFunction(clonedProperty); }); return clonedProperty; }
javascript
{ "resource": "" }
q968
_gpfArrayForEachFalsy
train
function _gpfArrayForEachFalsy(array, callback, thisArg) { var result, index = 0, length = array.length; for (; index < length && !result; ++index) { result = callback.call(thisArg, array[index], index, array); } return result; }
javascript
{ "resource": "" }
q969
_gpfCompatibilityInstallMethods
train
function _gpfCompatibilityInstallMethods(typeName, description) { var on = description.on; _gpfInstallCompatibleMethods(on, description.methods); _gpfInstallCompatibleStatics(on, description.statics); }
javascript
{ "resource": "" }
q970
_gpfArrayFromString
train
function _gpfArrayFromString(array, string) { var length = string.length, index = 0; for (; index < length; ++index) { array.push(string.charAt(index)); } }
javascript
{ "resource": "" }
q971
train
function (searchElement) { var result = -1; _gpfArrayEveryOwn(this, function (value, index) { if (value === searchElement) { result = index; return false; } return true; }, _gpfArrayGetFromIndex(arguments)); return result; }
javascript
{ "resource": "" }
q972
train
function (callback) { var REDUCE_INITIAL_VALUE_INDEX = 1, initialValue = arguments[REDUCE_INITIAL_VALUE_INDEX], thisLength = this.length, index = 0, value; if (undefined === initialValue) { value = this[index++]; } else { value = initialValue; } for (; index < thisLength; ++index) { value = callback(value, this[index], index, this); } return value; }
javascript
{ "resource": "" }
q973
_GpfDate
train
function _GpfDate() { var firstArgument = arguments[_GPF_START], values = _gpfIsISO8601String(firstArgument); if (values) { return new _GpfGenuineDate(_GpfGenuineDate.UTC.apply(_GpfGenuineDate.UTC, values)); } return _gpfNewApply(_GpfGenuineDate, arguments); }
javascript
{ "resource": "" }
q974
_gpfSortOnDt
train
function _gpfSortOnDt(a, b) { if (a.dt === b.dt) { return a.id - b.id; } return a.dt - b.dt; }
javascript
{ "resource": "" }
q975
_gpfJsonParsePolyfill
train
function _gpfJsonParsePolyfill(text, reviver) { var result = _gpfFunc("return " + text)(); if (reviver) { return _gpfJsonParseApplyReviver(result, "", reviver); } return result; }
javascript
{ "resource": "" }
q976
_gpfDefineClassImport
train
function _gpfDefineClassImport(InstanceBuilder) { var entityDefinition = _gpfDefineEntitiesFindByConstructor(InstanceBuilder); if (entityDefinition) { return entityDefinition; } return _gpfDefineClassImportFrom(InstanceBuilder, _gpfDefineClassImportGetDefinition(InstanceBuilder)); }
javascript
{ "resource": "" }
q977
train
function (name, value) { var overriddenMember = this._extend.prototype[name]; if (undefined !== overriddenMember) { this._checkOverridenMember(value, overriddenMember); } }
javascript
{ "resource": "" }
q978
train
function (newPrototype, memberName, value) { if (typeof value === "function") { this._addMethodToPrototype(newPrototype, memberName, value); } else { newPrototype[memberName] = value; } }
javascript
{ "resource": "" }
q979
_gpfInterfaceIsImplementedBy
train
function _gpfInterfaceIsImplementedBy(interfaceSpecifier, inspectedObject) { var result = true; _gpfObjectForEach(interfaceSpecifier.prototype, function (referenceMethod, name) { if (name === "constructor") { // ignore return; } if (_gpfInterfaceIsInvalidMethod(referenceMethod, inspectedObject[name])) { result = false; } }); return result; }
javascript
{ "resource": "" }
q980
_gpfInterfaceQueryThroughIUnknown
train
function _gpfInterfaceQueryThroughIUnknown(interfaceSpecifier, queriedObject) { var result = queriedObject.queryInterface(interfaceSpecifier); _gpfAssert(result === null || _gpfInterfaceIsImplementedBy(interfaceSpecifier, result), "Invalid result of queryInterface (must be null or an object implementing the interface)"); return result; }
javascript
{ "resource": "" }
q981
_gpfInterfaceQueryTryIUnknown
train
function _gpfInterfaceQueryTryIUnknown(interfaceSpecifier, queriedObject) { if (_gpfInterfaceIsImplementedBy(gpf.interfaces.IUnknown, queriedObject)) { return _gpfInterfaceQueryThroughIUnknown(interfaceSpecifier, queriedObject); } }
javascript
{ "resource": "" }
q982
_gpfDefineInterface
train
function _gpfDefineInterface(name, definition) { var interfaceDefinition = { $interface: "gpf.interfaces.I" + name }; Object.keys(definition).forEach(function (methodName) { interfaceDefinition[methodName] = _gpfCreateAbstractFunction(definition[methodName]); }); return _gpfDefine(interfaceDefinition); }
javascript
{ "resource": "" }
q983
_gpfStreamSecureInstallProgressFlag
train
function _gpfStreamSecureInstallProgressFlag(constructor) { constructor.prototype[_gpfStreamProgressRead] = false; constructor.prototype[_gpfStreamProgressWrite] = false; }
javascript
{ "resource": "" }
q984
_gpfFsExploreEnumerator
train
function _gpfFsExploreEnumerator(iFileStorage, listOfPaths) { var pos = GPF_FS_EXPLORE_BEFORE_START, info; return { reset: function () { pos = GPF_FS_EXPLORE_BEFORE_START; return Promise.resolve(); }, moveNext: function () { ++pos; info = undefined; if (pos < listOfPaths.length) { return iFileStorage.getInfo(listOfPaths[pos]).then(function (fsInfo) { info = fsInfo; return info; }); } return Promise.resolve(); }, getCurrent: function () { return info; } }; }
javascript
{ "resource": "" }
q985
train
function (stream, close) { this._stream = stream; if (typeof close === "function") { this._close = close; } stream.on("error", this._onError.bind(this)); }
javascript
{ "resource": "" }
q986
train
function (output, chunk) { var me = this, stream = me._stream; stream.pause(); output.write(chunk).then(function () { stream.resume(); }, me._reject); }
javascript
{ "resource": "" }
q987
train
function (e) { if (e instanceof java.util.NoSuchElementException || e.message.startsWith("java.util.NoSuchElementException")) { // Empty stream return Promise.resolve(); } return Promise.reject(e); }
javascript
{ "resource": "" }
q988
train
function () { var me = this; if (me._readNotWriting) { me._readNotWriting = false; me._readWriteToOutput().then(undefined, function (reason) { me._readReject(reason); }); } }
javascript
{ "resource": "" }
q989
train
function () { var me = this, lines = me._consolidateLines(); me._buffer.length = 0; me._pushBackLastLineIfNotEmpty(lines); _gpfArrayForEach(lines, function (line) { me._appendToReadBuffer(line); }); }
javascript
{ "resource": "" }
q990
_gpfRequireWrapGpf
train
function _gpfRequireWrapGpf(context, name) { return _gpfRequirePlugWrapper(_gpfRequireAllocateWrapper(), _gpfRequireAllocate(context, { base: _gpfPathParent(name) })); }
javascript
{ "resource": "" }
q991
_gpfRequireGet
train
function _gpfRequireGet(name) { var me = this, promise; if (me.cache[name]) { return me.cache[name]; } promise = _gpfRequireLoad.call(me, name); me.cache[name] = promise; return promise["catch"](function (reason) { _gpfRequireDocumentStack(reason, name); return Promise.reject(reason); }); }
javascript
{ "resource": "" }
q992
_gpfRequireAllocate
train
function _gpfRequireAllocate(parentContext, options) { var context = Object.create(parentContext), // cache content is shared but other properties are protected require = {}; require.define = _gpfRequireDefine.bind(context); require.resolve = _gpfRequireResolve.bind(context); require.configure = _gpfRequireConfigure.bind(context); if (options) { require.configure(options); } return require; }
javascript
{ "resource": "" }
q993
train
function (parserOptions) { var me = this; if (parserOptions) { _gpfArrayForEach([ "header", "separator", "quote", "newLine" ], function (optionName) { if (parserOptions[optionName]) { me["_" + optionName] = parserOptions[optionName]; } }); } }
javascript
{ "resource": "" }
q994
train
function () { var header = this._header; this._separator = _gpfArrayForEachFalsy(_gpfCsvSeparators, function (separator) { if (header.includes(separator)) { return separator; } }) || _gpfCsvSeparators[_GPF_START]; }
javascript
{ "resource": "" }
q995
train
function (match) { var UNQUOTED = 1, QUOTED = 2; if (match[UNQUOTED]) { this._values.push(match[UNQUOTED]); } else /* if (match[QUOTED]) */ { this._values.push(this._unescapeQuoted(match[QUOTED])); } }
javascript
{ "resource": "" }
q996
train
function (match) { var lengthOfMatchedString = match[_GPF_START].length, charAfterValue = this._content.charAt(lengthOfMatchedString); if (charAfterValue) { _gpfAssert(charAfterValue === this._separator, "Positive lookahead works"); return this._nextValue(++lengthOfMatchedString); } delete this._content; return false; // No value means end of content }
javascript
{ "resource": "" }
q997
train
function (line) { if (this._content) { this._content = this._content + this._newLine + line; } else { this._values = []; this._content = line; } return this._parseContent(); }
javascript
{ "resource": "" }
q998
train
function (values) { var record = {}; _gpfArrayForEach(this._columns, function (name, idx) { var value = values[idx]; if (value !== undefined) { record[name] = values[idx]; } }); return record; }
javascript
{ "resource": "" }
q999
train
function () { if (this._content) { var error = new gpf.Error.InvalidCSV(); this._setReadError(error); return Promise.reject(error); } this._completeReadBuffer(); return Promise.resolve(); }
javascript
{ "resource": "" }