_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q800 | echoWarningsAndErrors | train | function echoWarningsAndErrors(antWarnings, antErrors){
//Define the echo task to use for warnings and errors
var echo = project.createTask("echo");
var error = new org.apache.tools.ant.taskdefs.Echo.EchoLevel();
error.setValue("error");
echo.setLevel(error);
//Display all the detected warnings
for(var i = 0; i < antWarnings.length; i++){
echo.setMessage("WARNING: " + antWarnings[i]);
echo.perform();
}
//Display all the detected errors
for(i = 0; i < antErrors.length; i++){
echo.setMessage("ERROR: " + antErrors[i]);
echo.perform();
}
//Set a failure to the ant build if errors are present
if(antErrors.length > 0){
project.setProperty("javascript.fail.message", "Source analisis detected errors.");
}
} | javascript | {
"resource": ""
} |
q801 | flatten | train | function flatten (expression) {
const expanded = Array.from(expandInner(expression))
const flattened = expanded.reduce(function (result, clause) {
return Object.assign(result, clause)
}, {})
return sort([flattened])[0]
} | javascript | {
"resource": ""
} |
q802 | _gpfNewApply | train | function _gpfNewApply (Constructor, parameters) {
if (parameters.length > _gpfGenericFactory.length) {
_gpfGenericFactory = _gpfGenerateGenericFactory(parameters.length);
}
return _gpfGenericFactory.apply(Constructor, parameters);
} | javascript | {
"resource": ""
} |
q803 | train | function (context) {
var replacements;
if (context) {
replacements = {};
_gpfObjectForEach(context, function (value, key) {
replacements["{" + key + "}"] = value.toString();
});
this.message = _gpfStringReplaceEx(this.message, replacements);
}
} | javascript | {
"resource": ""
} |
|
q804 | _gpfGenenerateErrorFunction | train | function _gpfGenenerateErrorFunction (code, name, message) {
var result = _gpfErrorFactory(code, name, message);
result.CODE = code;
result.NAME = name;
result.MESSAGE = message;
return result;
} | javascript | {
"resource": ""
} |
q805 | _gpfErrorDeclare | train | function _gpfErrorDeclare (source, dictionary) {
_gpfIgnore(source);
_gpfObjectForEach(dictionary, function (message, name) {
var code = ++_gpfLastErrorCode;
gpf.Error["CODE_" + name.toUpperCase()] = code;
gpf.Error[name] = _gpfGenenerateErrorFunction(code, name, message);
});
} | javascript | {
"resource": ""
} |
q806 | EventEmitter | train | function EventEmitter() {
this._events = { };
this._once = { };
// default to 10 max liseners
this._maxListeners = 10;
this._add = function (event, listener, once) {
var entry = { listener: listener };
if (once) {
entry.once = true;
}
if (this._events[event]) {
this._events[event].push(entry);
} else {
this._events[event] = [ entry ];
}
if (this._maxListeners && this._events[event].count > this._maxListeners && console && console.warn) {
console.warn("EventEmitter Error: Maximum number of listeners");
}
return this;
};
this.on = function (event, listener) {
return this._add(event, listener);
};
this.addListener = this.on;
this.once = function (event, listener) {
return this._add(event, listener, true);
};
this.removeListener = function (event, listener) {
if (!this._events[event]) {
return this;
}
for(var i = this._events.length-1; i--;) {
if (this._events[i].listener === callback) {
this._events.splice(i, 1);
}
}
return this;
};
this.removeAllListeners = function (event) {
this._events[event] = undefined;
return this;
};
this.setMaxListeners = function (count) {
this._maxListeners = count;
return this;
};
this.emit = function () {
var args = Array.prototype.slice.apply(arguments);
var remove = [ ], i;
if (args.length) {
var event = args.shift();
if (this._events[event]) {
for (i = this._events[event].length; i--;) {
this._events[event][i].listener.apply(null, args);
if (this._events[event][i].once) {
remove.push(listener);
}
}
}
for (i = remove.length; i--;) {
this.removeListener(event, remove[i]);
}
}
return this;
};
} | javascript | {
"resource": ""
} |
q807 | _gpfAttributesCheckAppliedOnBaseClass | train | function _gpfAttributesCheckAppliedOnBaseClass (classDefinition, ExpectedBaseClass) {
var Extend = classDefinition._extend;
if (Extend !== ExpectedBaseClass) {
_gpfAttributesCheckAppliedOnBaseClassIsInstanceOf(Extend.prototype, ExpectedBaseClass);
}
} | javascript | {
"resource": ""
} |
q808 | _gpfAttributesCheckAppliedOnlyOnce | train | function _gpfAttributesCheckAppliedOnlyOnce (member, classDefinition, AttributeClass) {
var attributes = _gpfAttributesCheckGetMemberAttributes(member, classDefinition, AttributeClass);
if (_gpfArrayTail(attributes).length) {
gpf.Error.uniqueAttributeUsedTwice();
}
} | javascript | {
"resource": ""
} |
q809 | _GpfClassDefMember | train | function _GpfClassDefMember (name, defaultValue, type) {
/*jshint validthis:true*/ // constructor
this._name = name;
this._setDefaultValue(defaultValue);
this._setType(type || "undefined");
} | javascript | {
"resource": ""
} |
q810 | train | function (member) {
_gpfAsserts({
"Expected a _GpfClassDefMember": member instanceof _GpfClassDefMember,
"Member is already assigned to a class": null === member._classDef
});
this._checkMemberBeforeAdd(member);
this._members[member.getName()] = member;
member._classDef = this;
return this;
} | javascript | {
"resource": ""
} |
|
q811 | mergeInner | train | function mergeInner(base, mixin, mergeArrays) {
if (base === null || typeof base !== 'object' || Array.isArray(base)) {
throw new Error('base must be object');
}
if (mixin === null || typeof mixin !== 'object' || Array.isArray(mixin)) {
throw new Error('mixin must be object');
}
Object.keys(mixin).forEach((name) => {
mergeHelper(base, mixin, name, mergeArrays);
});
} | javascript | {
"resource": ""
} |
q812 | mergeHelper | train | function mergeHelper(base, mixin, name, mergeArrays) {
if (Array.isArray(mixin[name])) {
if (!mergeArrays && base[name] && Array.isArray(base[name])) {
base[name] = base[name].concat(mixin[name]);
} else {
base[name] = mixin[name];
}
} else if (typeof mixin[name] === 'object' && mixin[name] !== null) {
let newBase = base[name] || {};
if (Array.isArray(newBase)) {
newBase = {};
}
mergeInner(newBase, mixin[name], mergeArrays);
base[name] = newBase;
} else {
base[name] = mixin[name];
}
} | javascript | {
"resource": ""
} |
q813 | handler | train | function handler(notification) {
debug('summoner received a mention notification!');
return notification.getUser()
.then((user) => {
debug(`summoner responding to summons by ${user.name}`);
const index = Math.floor(Math.random() * messages.length);
const message = messages[index].replace(/%(\w+)%/g, (_, key) => {
let value = user[key];
if (key === 'name' && !value) {
value = user.username;
}
value = value || `%${key}%`;
if (typeof value !== 'string') {
value = `%${key}%`;
}
return value;
});
debug(`summoner replying with: ${message}`);
return forum.Post.reply(notification.topicId, notification.postId, message);
}).catch((err) => {
forum.emit('error', err);
return Promise.reject(err);
});
} | javascript | {
"resource": ""
} |
q814 | sendChat | train | function sendChat(roomId, content) {
return retryAction(() => forum._emit('modules.chats.send', {
roomId: roomId,
message: content
}), 5);
} | javascript | {
"resource": ""
} |
q815 | handleChat | train | function handleChat(payload) {
if (!payload.message) {
return Promise.reject(new Error('Event payload did not include chat message'));
}
const message = ChatRoom.Message.parse(payload.message);
forum.emit('chatMessage', message);
const ids = {
post: -1,
topic: -1,
user: message.from.id,
pm: message.room,
chat: message.id
};
return forum.Commands.get(ids, message.content, (content) => message.reply(content))
.then((command) => command.execute());
} | javascript | {
"resource": ""
} |
q816 | train | function (dependencies) {
this._dependsOn = dependencies[this._name] || [];
this._dependencyOf = [];
Object.keys(dependencies).forEach(function (name) {
var nameDependencies = dependencies[name];
if (nameDependencies.indexOf(this._name) !== NOT_FOUND) {
this._dependencyOf.push(name);
}
}, this);
} | javascript | {
"resource": ""
} |
|
q817 | train | function () {
var result = {
name: this._name
};
if (!this._test) {
result.test = false;
}
if (this._tags.length) {
result.tags = this._tags.join(" ");
}
return result;
} | javascript | {
"resource": ""
} |
|
q818 | train | function(primitive){
completed++;
if ( primitive ){
var geometry = new Terraformer.Primitive(primitive.geometry);
if (shapeGeometryTest(geometry, shape)){
if (self._stream) {
if (completed === found.length) {
if (operationName == "within") {
self._stream.emit("done", primitive);
} else {
self._stream.emit("data", primitive);
}
self._stream.emit("end");
} else {
self._stream.emit("data", primitive);
}
} else {
results.push(primitive);
}
}
if(completed >= found.length){
if(!errors){
if (self._stream) {
self._stream = null;
} else if (callback) {
callback( null, results );
}
} else {
if (callback) {
callback("Could not get all geometries", null);
}
}
}
}
} | javascript | {
"resource": ""
} |
|
q819 | train | function () {
var parts = new RegExp("(.*)\\.([^\\.]+)$").exec(this._name),
NAME_PART = 2,
NAMESPACE_PART = 1;
if (parts) {
this._name = parts[NAME_PART];
return parts[NAMESPACE_PART];
}
} | javascript | {
"resource": ""
} |
|
q820 | train | function () {
var namespaces = [
this._initialDefinition.$namespace,
this._extractRelativeNamespaceFromName()
].filter(function (namespacePart) {
return namespacePart;
});
if (namespaces.length) {
this._namespace = namespaces.join(".");
}
} | javascript | {
"resource": ""
} |
|
q821 | _gpfCleanDefinition | train | function _gpfCleanDefinition (name, shortcut) {
/*jshint validthis:true*/ // Bound to the definition below
var shortcutValue = this[shortcut];
if (undefined !== shortcutValue) {
this[name] = shortcutValue;
delete this[shortcut];
}
} | javascript | {
"resource": ""
} |
q822 | parsePlugins | train | function parsePlugins(config) {
let plugins = [];
function parse(plugins) {
return plugins.map(plugin => {
if ('string' == typeof plugin) plugin = path.resolve(plugin);
return plugin;
});
}
// Handle plugin paths defined in config file
if (config.plugins) {
plugins.push(...parse(config.plugins));
delete config.plugins;
}
// Handle plugin paths/functions defined in runtime options
if (config.runtimeOptions.plugins) {
plugins.push(...parse(config.runtimeOptions.plugins));
delete config.runtimeOptions.plugins;
}
return plugins;
} | javascript | {
"resource": ""
} |
q823 | _gpfProcessDefineParamCheckIfRelativeName | train | function _gpfProcessDefineParamCheckIfRelativeName (rootNamespace, params) {
var name = params[_GPF_DEFINE_PARAM_NAME];
if (-1 === name.indexOf(".")) {
params[_GPF_DEFINE_PARAM_NAME] = rootNamespace + name;
}
} | javascript | {
"resource": ""
} |
q824 | _gpfProcessDefineParamResolveBase | train | function _gpfProcessDefineParamResolveBase (params) {
var Super = params[_GPF_DEFINE_PARAM_SUPER];
if (!(Super instanceof Function)) {
params[_GPF_DEFINE_PARAM_SUPER] = _gpfContext(Super.toString().split("."));
}
} | javascript | {
"resource": ""
} |
q825 | _gpfProcessDefineParamsCheck | train | function _gpfProcessDefineParamsCheck (params) {
_gpfAsserts({
"name is required (String)": "string" === typeof params[_GPF_DEFINE_PARAM_NAME],
"Super is required and must resolve to a Constructor": params[_GPF_DEFINE_PARAM_SUPER] instanceof Function,
"definition is required (Object)": "object" === typeof params[_GPF_DEFINE_PARAM_DEFINITION]
});
} | javascript | {
"resource": ""
} |
q826 | _gpfProcessDefineParams | train | function _gpfProcessDefineParams (rootNamespace, defaultSuper, params) {
_gpfProcessDefineParamNoSuperUsed(defaultSuper, params);
_gpfProcessDefineParamCheckIfRelativeName(rootNamespace, params);
_gpfProcessDefineParamDefaultSuper(defaultSuper, params);
_gpfProcessDefineParamDefaultDefinition(params);
_gpfProcessDefineParamResolveBase(params);
_gpfProcessDefineParamsCheck(params);
} | javascript | {
"resource": ""
} |
q827 | find | train | function find(id, type, sourcedir, options) {
const { cache, fileExtensions, nativeModules } = options;
const pkgDetails = pkg.getDetails(sourcedir, options);
let filepath = isRelativeFilepath(id) ? path.join(sourcedir, id) : id;
filepath = alias.resolve(filepath, pkgDetails && pkgDetails.aliases);
if (filepath === false || nativeModules.includes(filepath)) return false;
if (isAbsoluteFilepath(filepath)) {
filepath = findFilepath(filepath, type, fileExtensions);
filepath = alias.resolve(filepath, pkgDetails && pkgDetails.aliases);
// File doesn't exist or is disabled
if (filepath === '' || filepath === false) return filepath;
// File found
if (isAbsoluteFilepath(filepath)) {
// Cache
cache.setFile(
{
id: pkg.resolveId(pkgDetails, filepath),
path: filepath,
version: pkgDetails.version
},
versionDelimiter
);
return filepath;
}
}
// Update id if it has been resolved as package
if (!isFilepath(filepath)) id = filepath;
// Search paths for matches
pkgDetails.paths.some(sourcepath => {
if (id && sourcedir != sourcepath) {
let fp = path.join(sourcepath, id);
fp = find(fp, type, fp, options);
if (fp !== '') {
filepath = fp;
return true;
}
filepath = '';
}
});
return filepath;
} | javascript | {
"resource": ""
} |
q828 | _gpfWebGetNamespace | train | function _gpfWebGetNamespace (prefix) {
var namespace = _gpfWebNamespacePrefix[prefix];
if (undefined === namespace) {
gpf.Error.unknownNamespacePrefix();
}
return namespace;
} | javascript | {
"resource": ""
} |
q829 | _gpfWebGetNamespaceAndName | train | function _gpfWebGetNamespaceAndName (name) {
var EXPECTED_PARTS_COUNT = 2,
NAMESPACE_PREFIX = 0,
NAME = 1,
parts = name.split(":");
if (parts.length === EXPECTED_PARTS_COUNT) {
return {
namespace: _gpfWebGetNamespace(parts[NAMESPACE_PREFIX]),
name: parts[NAME]
};
}
} | javascript | {
"resource": ""
} |
q830 | _gpfWebTagFlattenChildren | train | function _gpfWebTagFlattenChildren (array, callback) {
array.forEach(function (item) {
if (_gpfIsArray(item)) {
_gpfWebTagFlattenChildren(item, callback);
} else {
callback(item);
}
});
} | javascript | {
"resource": ""
} |
q831 | train | function () {
return Object.keys(this._attributes).map(function (name) {
_gpfWebCheckNamespaceSafe(name);
return " " + _gpfWebTagAttributeAlias(name)
+ "=\"" + _gpfStringEscapeForHtml(this._attributes[name]) + "\"";
}, this).join("");
} | javascript | {
"resource": ""
} |
|
q832 | train | function (node) {
var ownerDocument = node.ownerDocument,
qualified = _gpfWebGetNamespaceAndName(this._nodeName);
if (qualified) {
return ownerDocument.createElementNS(qualified.namespace, qualified.name);
}
return ownerDocument.createElement(this._nodeName);
} | javascript | {
"resource": ""
} |
|
q833 | train | function (node) {
var element = this._createElement(node);
this._setAttributesTo(element);
this._appendChildrenTo(element);
return node.appendChild(element);
} | javascript | {
"resource": ""
} |
|
q834 | _gpfWebTagCreateFunction | train | function _gpfWebTagCreateFunction (nodeName) {
if (!nodeName) {
gpf.Error.missingNodeName();
}
return function (firstParam) {
var sliceFrom = 0,
attributes;
if (_gpfIsLiteralObject(firstParam)) {
attributes = firstParam;
++sliceFrom;
}
return new _GpfWebTag(nodeName, attributes, _gpfArraySlice(arguments, sliceFrom));
};
} | javascript | {
"resource": ""
} |
q835 | train | function (a, b) {
var done = this._done,
indexOfA,
comparedWith;
indexOfA = done.indexOf(a);
while (-1 < indexOfA) {
comparedWith = this._getPair(done, indexOfA);
if (comparedWith === b) {
return false; // Already compared
}
indexOfA = done.indexOf(a, indexOfA + 1);
}
return true;
} | javascript | {
"resource": ""
} |
|
q836 | train | function (a, b) {
var pending;
if (this._neverCompared(a, b)) {
pending = this._pending;
pending.push(a);
pending.push(b);
}
} | javascript | {
"resource": ""
} |
|
q837 | train | function () {
var pending = this._pending,
done = this._done,
a,
b;
while (0 !== pending.length) {
b = pending.pop();
a = pending.pop();
done.push(a, b);
if (this._areDifferent(a, b)) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
|
q838 | train | function (a, b) {
var me = this,
membersOfA = Object.keys(a);
// a members comparison with b
if (!membersOfA.every(function (member) {
return me.like(a[member], b[member]);
})) {
return true;
}
// Difference on members count?
return membersOfA.length !== Object.keys(b).length;
} | javascript | {
"resource": ""
} |
|
q839 | train | function (a, b) {
if (null === a || null === b || "object" !== typeof a) {
return false; // Because we know that a !== b
}
this._stack(a, b);
return true;
} | javascript | {
"resource": ""
} |
|
q840 | train | function (a, b) {
if (a === b) {
return true;
}
if (typeof a !== typeof b) {
return this._alike(a, b);
}
return this._objectLike(a, b);
} | javascript | {
"resource": ""
} |
|
q841 | _gpfCreateAbstractFunction | train | function _gpfCreateAbstractFunction (numberOfParameters) {
return _gpfFunctionBuild({
parameters: _gpfBuildFunctionParameterList(numberOfParameters),
body: "_throw_();"
}, {
_throw_: gpf.Error.abstractMethod
});
} | javascript | {
"resource": ""
} |
q842 | _gpfAddEventListener | train | function _gpfAddEventListener (event, eventsHandler) {
/*jshint validthis:true*/ // will be invoked as an object method
var listeners = _gpfAllocateEventDispatcherListeners(this);
if (undefined === listeners[event]) {
listeners[event] = [];
}
listeners[event].push(eventsHandler);
return this;
} | javascript | {
"resource": ""
} |
q843 | _gpfRemoveEventListener | train | function _gpfRemoveEventListener (event, eventsHandler) {
/*jshint validthis:true*/ // will be invoked as an object method
var listeners = this._eventDispatcherListeners,
eventListeners,
index;
if (listeners) {
eventListeners = listeners[event];
if (undefined !== eventListeners) {
index = eventListeners.indexOf(eventsHandler);
if (-1 !== index) {
eventListeners.splice(index, 1);
}
}
}
return this;
} | javascript | {
"resource": ""
} |
q844 | _gpfTriggerListeners | train | function _gpfTriggerListeners (eventObj, eventListeners) {
var index,
length = eventListeners.length;
for (index = 0; index < length; ++index) {
_gpfEventsFire.call(eventObj.scope, eventObj, {}, eventListeners[index]);
}
} | javascript | {
"resource": ""
} |
q845 | _gpfDispatchEvent | train | function _gpfDispatchEvent (event, params) {
/*jshint validthis:true*/ // will be invoked as an object method
var listeners = this._eventDispatcherListeners,
eventObj,
type,
eventListeners;
if (!listeners) {
return this; // No listeners at all
}
if (event instanceof _GpfEvent) {
eventObj = event;
type = event.type;
} else {
type = event;
}
eventListeners = this._eventDispatcherListeners[type];
if (undefined === eventListeners) {
return this; // Nothing listeners for this event
}
if (!eventObj) {
eventObj = new _GpfEvent(type, params, this);
}
_gpfTriggerListeners(eventObj, eventListeners);
return eventObj;
} | javascript | {
"resource": ""
} |
q846 | train | function (src) {
// https://github.com/Constellation/escodegen/issues/85
let ast = esprima.parse(src, {
range: true,
tokens: true,
comment: true
});
ast = escodegen.attachComments(ast, ast.comments, ast.tokens);
delete ast.tokens;
delete ast.comments;
return ast;
} | javascript | {
"resource": ""
} |
|
q847 | train | function (ast, setting, debug) {
let optimizer = new Optimizer(ast, setting, debug);
optimizer.analyze();
optimizer.optimize();
return ast;
} | javascript | {
"resource": ""
} |
|
q848 | _onKeyDown | train | function _onKeyDown(e) {
var keyCode = e.keyCode;
if (keyCode === 13 || keyCode === 32) {
this.keyDownFlag = true; // if host element does not naturally trigger a click event on spacebar, we can force one to trigger here.
// careful! if host already triggers click events naturally, we end up with a "double-click".
if (keyCode === 32 && this.options.simulateSpacebarClick === true) {
this.hostEl.click();
}
}
} | javascript | {
"resource": ""
} |
q849 | commentStrip | train | function commentStrip(string) {
// Remove commented lines
string = string.replace(RE_COMMENT_SINGLE_LINE, '');
string = string.replace(RE_COMMENT_MULTI_LINES, '');
return string;
} | javascript | {
"resource": ""
} |
q850 | commentWrap | train | function commentWrap(string, type) {
let open, close;
if (type == 'html') {
open = '<!-- ';
close = ' -->';
} else {
open = '/* ';
close = ' */';
}
return open + string + close;
} | javascript | {
"resource": ""
} |
q851 | indent | train | function indent(string, column) {
const spaces = new Array(++column).join(COLUMN);
return string.replace(RE_LINE_BEGIN, spaces);
} | javascript | {
"resource": ""
} |
q852 | uniqueMatch | train | function uniqueMatch(string, regexp) {
const results = [];
let match;
while ((match = regexp.exec(string))) {
results.push({
context: match[0],
match: match[1] || ''
});
}
// Filter duplicates
return unique(results, isEqual);
} | javascript | {
"resource": ""
} |
q853 | _gpfHostJava | train | function _gpfHostJava () {
_gpfDosPath = String(java.lang.System.getProperty("file.separator")) === "\\";
// Define console APIs
_gpfMainContext.console = _gpfConsoleGenerate(print);
/* istanbul ignore next */ // exit.1
_gpfExit = function (code) {
java.lang.System.exit(code);
};
} | javascript | {
"resource": ""
} |
q854 | train | function (name) {
var result, member, mappedName;
if (null === this._attributes) {
this._members();
}
if (undefined === name) {
result = {};
for (member in this._attributes) {
if (this._attributes.hasOwnProperty(member)) {
mappedName = this._attributes[member];
result[mappedName] = this._obj[member];
}
}
return result;
}
for (member in this._attributes) {
if (this._attributes.hasOwnProperty(member)) {
if (name === this._attributes[member]) {
return this._obj[member];
}
}
}
return undefined;
} | javascript | {
"resource": ""
} |
|
q855 | _nodeToXml | train | function _nodeToXml (node, wrapped) {
var
name = node.localName(),
attributes = node.attributes(),
children = node.children(),
text = node.textContent(),
idx;
wrapped.startElement({
uri: "",
localName: name,
qName: name
}, attributes);
// Today the XmlConstNode may not have both children and textual content
if (text) {
wrapped.characters(text);
} else {
for (idx = 0; idx < children.length; ++idx) {
_nodeToXml(children[idx], wrapped);
}
}
wrapped.endElement();
} | javascript | {
"resource": ""
} |
q856 | _gpfDefineBuildTypedEntity | train | function _gpfDefineBuildTypedEntity (definition) {
var EntityBuilder = _gpfDefineRead$TypedProperties(definition),
entityDefinition;
if (!EntityBuilder) {
EntityBuilder = _gpfDefineCheck$TypeProperty(definition);
}
entityDefinition = new EntityBuilder(definition);
entityDefinition.check();
return entityDefinition;
} | javascript | {
"resource": ""
} |
q857 | train | function (callback, thisArg) {
var me = this;
this._sources.forEach(function (source, index) {
callback(me._update(source), index);
}, thisArg);
} | javascript | {
"resource": ""
} |
|
q858 | train | function (name) {
var result;
this._sources.every(function (source) {
if (source.getName() === name) {
result = this._update(source);
return false;
}
return true;
}, this);
return result;
} | javascript | {
"resource": ""
} |
|
q859 | train | function (name) {
var dependencies = this.byName(name).getDependencies(),
names = this.getNames(),
minIndex = 1; // 0 being boot
dependencies.forEach(function (dependencyName) {
var index = names.indexOf(dependencyName);
++index;
if (index > minIndex) {
minIndex = index;
}
});
return minIndex;
} | javascript | {
"resource": ""
} |
|
q860 | train | function (sourceName, referenceSourceName) {
var sourceToMove,
sourcePos,
referenceSourcePos;
if (!this._sources.every(function (source, index) {
var name = source.getName();
if (name === sourceName) {
sourceToMove = source;
sourcePos = index;
} else if (name === referenceSourceName) {
referenceSourcePos = index;
}
return sourcePos === undefined || referenceSourcePos === undefined;
})) {
var KEEP_ITEM = 0,
REMOVE_ITEM = 1;
this._sources.splice(sourcePos, REMOVE_ITEM);
if (sourcePos > referenceSourcePos) {
++referenceSourcePos;
}
this._sources.splice(referenceSourcePos, KEEP_ITEM, sourceToMove);
this._rebuildSourcesIndex();
}
} | javascript | {
"resource": ""
} |
|
q861 | train | function (checkDictionary) {
this._checkDictionary = checkDictionary;
var newSources = Object.keys(checkDictionary)
.filter(function (name) {
return checkDictionary[name] === "new";
})
.map(function (name) {
return new Source(this, {
name: name,
load: false
}, null);
}, this);
// Add missing sources after the last loaded one
if (newSources.length) {
this.sources = this.sources.concat(newSources);
}
} | javascript | {
"resource": ""
} |
|
q862 | logstashLayout | train | function logstashLayout(logEvt, fields) {
var messageData = logEvt.data[0],
log = {
'@timestamp': (new Date()).toISOString(),
'@fields': {
category: logEvt.categoryName,
level: logEvt.level.levelStr
},
'@message' : (toType(messageData) === "string") ? messageData : JSON.stringify(messageData)
}
for (var key in fields) {
if (typeof fields[key] !== 'function') {
log['@fields'][key] = fields[key];
}
}
return JSON.stringify(log) + '\n';
} | javascript | {
"resource": ""
} |
q863 | logStashAppender | train | function logStashAppender(config, fields, layout) {
var time = process.hrtime(),
messages = [],
timeOutId = 0;
layout = layout || logstashLayout;
//Setup the connection to logstash
function pushToStash(config, msg) {
var client = net.connect({host: config.host, port: config.port}, function () {
client.write(msg);
client.end();
});
//Fail silently
client.on('error', function (evt) {
if (true === config.debug) {
console.log('An error happened in the logstash appender!', evt);
}
});
}
return function (logEvt) {
//do stuff with the logging event
var data = layout(logEvt, fields);
if (config.batch === true) {
messages.push(data);
clearTimeout(timeOutId);
if ((process.hrtime(time)[0] >= config.batchTimeout || messages.length > config.batchSize)) {
pushToStash(config, messages.join(''));
time = process.hrtime();
messages = [];
} else {
timeOutId = setTimeout(function () {
pushToStash(config, messages.join(''));
time = process.hrtime();
messages = [];
}, 1000);
}
} else {
pushToStash(config, data);
}
};
} | javascript | {
"resource": ""
} |
q864 | pushToStash | train | function pushToStash(config, msg) {
var client = net.connect({host: config.host, port: config.port}, function () {
client.write(msg);
client.end();
});
//Fail silently
client.on('error', function (evt) {
if (true === config.debug) {
console.log('An error happened in the logstash appender!', evt);
}
});
} | javascript | {
"resource": ""
} |
q865 | configure | train | function configure(config) {
var key,
layout = null,
fields = {},
options = {
port: (typeof config.port === "number") ? config.port : 5959,
host: (typeof config.host === "string") ? config.host : 'localhost',
debug: config.debug || false
};
if (config.batch) {
options.batch = true;
options.batchSize = config.batch.size;
options.batchTimeout = config.batch.timeout;
}
if (config.fields && typeof config.fields === 'object') {
for (key in config.fields) {
if (typeof config.fields[key] !== 'function') {
fields[key] = config.fields[key];
}
}
}
return logStashAppender(options, fields, layout);
} | javascript | {
"resource": ""
} |
q866 | _gpfHttpParseHeaders | train | function _gpfHttpParseHeaders (headers) {
var result = {};
_gpfArrayForEach(_gpfRegExpForEach(_gpfHttpHeadersParserRE, headers), function (match) {
result[match[_GPF_HTTP_HELPERS_HEADER_NAME]] = match[_GPF_HTTP_HELPERS_HEADER_VALUE];
});
return result;
} | javascript | {
"resource": ""
} |
q867 | _gpfHttpGenSetHeaders | train | function _gpfHttpGenSetHeaders (methodName) {
return function (httpObj, headers) {
if (headers) {
Object.keys(headers).forEach(function (headerName) {
httpObj[methodName](headerName, headers[headerName]);
});
}
};
} | javascript | {
"resource": ""
} |
q868 | _gpfHttpGenSend | train | function _gpfHttpGenSend (methodName) {
return function (httpObj, data) {
if (data) {
httpObj[methodName](data);
} else {
httpObj[methodName]();
}
};
} | javascript | {
"resource": ""
} |
q869 | create | train | function create(content, url) {
url = url || '<source>';
const map = new SourceMapGenerator({ file: url });
const lines = content.split('\n');
for (let l = 1, n = lines.length; l <= n; l++) {
// Skip empty
if (lines[l - 1]) {
map.addMapping({
source: url,
original: { line: l, column: 0 },
generated: { line: l, column: 0 }
});
}
}
map.setSourceContent(url, content);
return map;
} | javascript | {
"resource": ""
} |
q870 | createFromMap | train | function createFromMap(mapObject, content, url) {
url = url || '<source>';
if ('string' == typeof mapObject) {
try {
mapObject = JSON.parse(mapObject);
} catch (err) {
mapObject = {
version: 3,
names: [],
mappings: '',
file: ''
};
}
}
if (emptySources(mapObject)) {
mapObject.sources = [url];
mapObject.sourcesContent = [content];
}
return SourceMapGenerator.fromSourceMap(new SourceMapConsumer(mapObject));
} | javascript | {
"resource": ""
} |
q871 | insert | train | function insert(outMap, inMap, length, index) {
// Move existing mappings
if (length) {
outMap._mappings.unsortedForEach(mapping => {
if (mapping.generatedLine > index) mapping.generatedLine += length;
});
}
// Add new mappings
if (inMap) {
const inConsumer = new SourceMapConsumer(inMap.toJSON());
inConsumer.eachMapping(mapping => {
outMap.addMapping({
source: mapping.source,
original: mapping.source == null
? null
: {
line: mapping.originalLine,
column: mapping.originalColumn
},
generated: {
line: index + mapping.generatedLine - 1,
column: mapping.generatedColumn
}
});
});
inConsumer.sources.forEach((source, idx) => {
outMap.setSourceContent(source, inConsumer.sourcesContent[idx]);
});
}
} | javascript | {
"resource": ""
} |
q872 | emptySources | train | function emptySources(map) {
return !map.sources ||
!map.sources.length ||
!map.sourcesContent ||
!map.sourcesContent.length ||
map.sources.length != map.sourcesContent.length;
} | javascript | {
"resource": ""
} |
q873 | notifyHandler | train | function notifyHandler(data) {
const notification = Notification.parse(data);
return evalBlacklist(notification)
.then(() => {
forum.emit('log', `Notification ${notification.id}: ${notification.label} received`);
const ids = {
post: notification.postId,
topic: notification.topicId,
user: notification.userId,
pm: -1,
chat: -1
};
return notification.getText()
.then((postData) => forum.Commands.get(ids,
postData, (content) => forum.Post.reply(notification.topicId, notification.postId, content)))
.then((commands) => {
if (commands.commands.length === 0) {
debug(`Emitting events: 'notification' and 'notification:${notification.type}'`);
forum.emit(`notification:${notification.type}`, notification);
forum.emit('notification', notification);
}
return commands;
})
.then((commands) => commands.execute());
}).catch((err) => {
if (err === 'Ignoring notification') {
//We do not process the notification, but we can continue with life
return Promise.resolve();
}
throw err;
});
} | javascript | {
"resource": ""
} |
q874 | evalBlacklist | train | function evalBlacklist(notification) {
return new Promise((resolve, reject) => {
const ignoreCategories = forum.config.core.ignoreCategories || [];
//if there's no blacklist, we can ignore the hit for getting the category
if (ignoreCategories.length) {
if (ignoreCategories.some((elem) => elem.toString() === notification.categoryId.toString())) {
forum.emit('log', `Notification from category ${notification.categoryId} ignored`);
return reject('Ignoring notification');
}
}
return resolve(notification);
});
} | javascript | {
"resource": ""
} |
q875 | normalizeTuple | train | function normalizeTuple(target, path) {
var hasThis = HAS_THIS.test(path),
isGlobal = !hasThis && IS_GLOBAL_PATH.test(path),
key;
if (!target || isGlobal) target = Ember.lookup;
if (hasThis) path = path.slice(5);
if (target === Ember.lookup) {
key = firstKey(path);
target = get(target, key);
path = path.slice(key.length+1);
}
// must return some kind of path to be valid else other things will break.
if (!path || path.length===0) throw new Error('Invalid Path');
return [ target, path ];
} | javascript | {
"resource": ""
} |
q876 | chainsFor | train | function chainsFor(obj) {
var m = metaFor(obj), ret = m.chains;
if (!ret) {
ret = m.chains = new ChainNode(null, null, obj);
} else if (ret.value() !== obj) {
ret = m.chains = ret.copy(obj);
}
return ret;
} | javascript | {
"resource": ""
} |
q877 | train | function() {
var ret = Ember.A([]);
this.forEach(function(o, idx) { ret[idx] = o; });
return ret ;
} | javascript | {
"resource": ""
} |
|
q878 | train | function() {
if (Ember.Freezable && Ember.Freezable.detect(this)) {
return get(this, 'isFrozen') ? this : this.copy().freeze();
} else {
throw new Error(Ember.String.fmt("%@ does not support freezing", [this]));
}
} | javascript | {
"resource": ""
} |
|
q879 | train | function(keyName, increment) {
if (!increment) { increment = 1; }
set(this, keyName, (get(this, keyName) || 0)+increment);
return get(this, keyName);
} | javascript | {
"resource": ""
} |
|
q880 | _gpfGenSuperMember | train | function _gpfGenSuperMember (superMethod, method) {
return function GpfSuperableMethod () {
var previousSuper = this._super,
result;
// Add a new ._super() method pointing to the base class member
this._super = superMethod;
try {
// Execute the method
result = method.apply(this, arguments);
} finally {
// Remove it after execution
if (undefined === previousSuper) {
delete this._super;
} else {
this._super = previousSuper;
}
}
return result;
};
} | javascript | {
"resource": ""
} |
q881 | _GpfOldClassDefinition | train | function _GpfOldClassDefinition (name, Super, definition) {
/*jshint validthis:true*/ // constructor
this._uid = ++_gpfClassDefUID;
_gpfClassDefinitions[this._uid] = this;
this._Subs = [];
if ("function" === typeof name) {
this._name = name.compatibleName() || "anonymous";
// TODO how do we grab the parent constructor (?)
this._Constructor = name;
} else {
this._name = name;
this._Super = Super;
this._definition = definition;
this._build();
}
} | javascript | {
"resource": ""
} |
q882 | train | function (member, memberValue, visibility) {
if (undefined === visibility) {
visibility = _GPF_VISIBILITY_PUBLIC;
} else {
visibility = _gpfVisibilityKeywords.indexOf(visibility);
if (-1 === visibility) {
gpf.Error.classInvalidVisibility();
}
}
this._addMember(member, memberValue, visibility);
} | javascript | {
"resource": ""
} |
|
q883 | train | function (member, memberValue, visibility) {
if (_GPF_VISIBILITY_STATIC === visibility) {
_gpfAssert(undefined === this._Constructor[member], "Static members can't be overridden");
this._Constructor[member] = memberValue;
} else if ("constructor" === member) {
this._addConstructor(memberValue, visibility);
} else {
this._addNonStaticMember(member, memberValue, visibility);
}
} | javascript | {
"resource": ""
} |
|
q884 | train | function (memberValue, visibility) {
_gpfAsserts({
"Constructor must be a function": "function" === typeof memberValue,
"Own constructor can't be overridden": null === this._definitionConstructor
});
if (_gpfUsesSuper(memberValue)) {
memberValue = _gpfGenSuperMember(this._Super, memberValue);
}
_gpfIgnore(visibility); // TODO Handle constructor visibility
this._definitionConstructor = memberValue;
} | javascript | {
"resource": ""
} |
|
q885 | train | function (member, memberValue, visibility) {
var newType = typeof memberValue,
baseMemberValue,
baseType,
prototype = this._Constructor.prototype;
_gpfAssert(!prototype.hasOwnProperty(member), "Existing own member can't be overridden");
baseMemberValue = this._Super.prototype[member];
baseType = typeof baseMemberValue;
if ("undefined" !== baseType) {
if (null !== baseMemberValue && newType !== baseType) {
gpf.Error.classMemberOverloadWithTypeChange();
}
if ("function" === newType && _gpfUsesSuper(memberValue)) {
memberValue = _gpfGenSuperMember(baseMemberValue, memberValue);
}
}
_gpfIgnore(visibility); // TODO Handle constructor visibility
prototype[member] = memberValue;
} | javascript | {
"resource": ""
} |
|
q886 | train | function (member) {
if ("[" !== member.charAt(0) || "]" !== member.charAt(member.length - 1)) {
return "";
}
return _gpfEncodeAttributeMember(member.substr(1, member.length - 2)); // Extract & encode member name
} | javascript | {
"resource": ""
} |
|
q887 | train | function (attributeName, attributeValue) {
var attributeArray;
if (this._definitionAttributes) {
attributeArray = this._definitionAttributes[attributeName];
} else {
this._definitionAttributes = {};
}
if (undefined === attributeArray) {
attributeArray = [];
}
this._definitionAttributes[attributeName] = attributeArray.concat(attributeValue);
} | javascript | {
"resource": ""
} |
|
q888 | train | function (member, memberValue) {
var attributeName = this._extractAttributeName(member);
if (!attributeName) {
return false;
}
this._addToDefinitionAttributes(attributeName, memberValue);
return true;
} | javascript | {
"resource": ""
} |
|
q889 | train | function (memberName) {
var visibility = this._defaultVisibility;
if (_GPF_VISIBILITY_UNKNOWN === visibility) {
if (memberName.charAt(0) === "_") {
visibility = _GPF_VISIBILITY_PROTECTED;
} else {
visibility = _GPF_VISIBILITY_PUBLIC;
}
}
return visibility;
} | javascript | {
"resource": ""
} |
|
q890 | train | function (memberValue, memberName) {
if (this._filterAttribute(memberName, memberValue)) {
return;
}
var newVisibility = _gpfVisibilityKeywords.indexOf(memberName);
if (_GPF_VISIBILITY_UNKNOWN === newVisibility) {
return this._addMember(memberName, memberValue, this._deduceVisibility(memberName));
}
if (_GPF_VISIBILITY_UNKNOWN !== this._defaultVisibility) {
gpf.Error.classInvalidVisibility();
}
this._processDefinition(memberValue, newVisibility);
} | javascript | {
"resource": ""
} |
|
q891 | train | function (definition, visibility) {
var isWScript = _GPF_HOST.WSCRIPT === _gpfHost;
this._defaultVisibility = visibility;
_gpfObjectForEach(definition, this._processDefinitionMember, this);
if (isWScript && definition.hasOwnProperty("toString")) {
this._processDefinitionMember(definition.toString, "toString");
}
this._defaultVisibility = _GPF_VISIBILITY_UNKNOWN;
if (isWScript && definition.hasOwnProperty("constructor")) {
this._addConstructor(definition.constructor, this._defaultVisibility);
}
} | javascript | {
"resource": ""
} |
|
q892 | train | function () {
var
attributes = this._definitionAttributes,
Constructor,
newPrototype;
if (attributes) {
_gpfAssert("function" === typeof _gpfAttributesAdd, "Attributes can't be defined before they exist");
Constructor = this._Constructor;
newPrototype = Constructor.prototype;
_gpfObjectForEach(attributes, function (attributeList, attributeName) {
attributeName = _gpfDecodeAttributeMember(attributeName);
if (attributeName in newPrototype || attributeName === "Class") {
_gpfAttributesAdd(Constructor, attributeName, attributeList);
} else {
// 2013-12-15 ABZ Exceptional, trace it only
console.error("gpf.define: Invalid attribute name '" + attributeName + "'");
}
});
}
} | javascript | {
"resource": ""
} |
|
q893 | train | function () {
var
newClass,
newPrototype,
baseClassDef;
// The new class constructor
newClass = _getOldNewClassConstructor(this);
this._Constructor = newClass;
newClass[_GPF_CLASSDEF_MARKER] = this._uid;
// Basic JavaScript inheritance mechanism: Defines the newClass prototype as an instance of the super class
newPrototype = Object.create(this._Super.prototype);
// Populate our constructed prototype object
newClass.prototype = newPrototype;
// Enforce the constructor to be what we expect
newPrototype.constructor = newClass;
/*
* Defines the link between this class and its base one
* (It is necessary to do it here because of the gpf.addAttributes that will test the parent class)
*/
baseClassDef = _gpfGetClassDefinition(this._Super);
baseClassDef._Subs.push(newClass);
/*
* 2014-04-28 ABZ Changed again from two passes on all members to two passes in which the first one also
* collects attributes to simplify the second pass.
*/
this._processDefinition(this._definition, _GPF_VISIBILITY_UNKNOWN);
this._processAttributes();
// Optimization for the constructor
this._resolveConstructor();
} | javascript | {
"resource": ""
} |
|
q894 | _gpfHttMockMatchRequest | train | function _gpfHttMockMatchRequest (mockedRequest, request) {
var url = mockedRequest.url,
match;
url.lastIndex = 0;
match = url.exec(request.url);
if (match) {
return mockedRequest.response.apply(mockedRequest, [request].concat(_gpfArrayTail(match)));
}
} | javascript | {
"resource": ""
} |
q895 | _gpfHttMockMatch | train | function _gpfHttMockMatch (mockedRequests, request) {
var result;
mockedRequests.every(function (mockedRequest) {
result = _gpfHttMockMatchRequest(mockedRequest, request);
return result === undefined;
});
return result;
} | javascript | {
"resource": ""
} |
q896 | _gpfHttpMockAdd | train | function _gpfHttpMockAdd (definition) {
var method = definition.method.toUpperCase(),
id = method + "." + _gpfHttpMockLastId++;
_gpfHttpMockGetMockedRequests(method).unshift(Object.assign({
id: id
}, definition));
return id;
} | javascript | {
"resource": ""
} |
q897 | _gpfHttpMockRemove | train | function _gpfHttpMockRemove (id) {
var method = id.substring(_GPF_START, id.indexOf("."));
_gpfHttpMockedRequests[method] = _gpfHttpMockGetMockedRequests(method).filter(function (mockedRequest) {
return mockedRequest.id !== id;
});
} | javascript | {
"resource": ""
} |
q898 | resolveEnvSources | train | function resolveEnvSources(env) {
let paths = [];
if (process.env[env]) {
paths = process.env[env].includes(path.delimiter) ? process.env[env].split(path.delimiter) : [process.env[env]];
}
return paths;
} | javascript | {
"resource": ""
} |
q899 | train | function(target) {
// Only store the `module` in the local cache since `module.exports` may not be accurate
// if there was a circular dependency
var module = localCache[target] || (localCache[target] = requireModule(target, dirname));
return module.exports;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.