_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q11400 | train | function(number, precision) {
const multiplier = !!precision ? Math.pow(10, precision) : 1;
return Math.round(number * multiplier) / multiplier;
} | javascript | {
"resource": ""
} | |
q11401 | train | function(number, precision) {
const multiplier = !!precision ? Math.pow(10, precision) : 1;
return Math.ceil(number * multiplier) / multiplier;
} | javascript | {
"resource": ""
} | |
q11402 | train | function(number, precision) {
const multiplier = !!precision ? Math.pow(10, precision) : 1;
return Math.floor(number * multiplier) / multiplier;
} | javascript | {
"resource": ""
} | |
q11403 | getFunctionOverhead | train | function getFunctionOverhead(runs) {
var result,
dummy,
start,
i;
// The dummy has to return something,
// or it'll get insanely optimized
dummy = Function('return 1');
// Call dummy now to get it jitted
dummy();
start = Blast.performanceNow();
for (i = 0; i < runs; i++) {
dummy();
}
result = Blast.performanceNow() - start;
// When doing coverage this can increase a lot, giving weird results
if (result > 1) {
result = 0.5;
}
return result;
} | javascript | {
"resource": ""
} |
q11404 | doSyncBench | train | function doSyncBench(fn, callback) {
var start,
fnOverhead,
pretotal,
result,
runs,
name;
runs = 0;
// For the initial test, to determine how many iterations we should
// test later, we just use Date.now()
start = Date.now();
// See how many times we can get it to run for 50ms
// This doesn't need to be precise yet. We don't use these results
// for the ops count because Date.now() takes time, too
do {
fn();
runs++;
pretotal = Date.now() - start;
} while (pretotal < 50);
// See how long it takes to run an empty function
fnOverhead = getFunctionOverhead(runs);
result = syncTest(fn, runs, fnOverhead);
if (callback) {
result.name = fn.name || '';
callback(null, result);
} else {
name = fn.name || '';
if (name) name = 'for "' + name + '" ';
console.log('Benchmark ' + name + 'did ' + Bound.Number.humanize(result.ops) + '/s (' + Bound.Number.humanize(result.iterations) + ' iterations)');
}
return result;
} | javascript | {
"resource": ""
} |
q11405 | doAsyncBench | train | function doAsyncBench(fn, callback) {
var fnOverhead,
pretotal,
result,
args,
i;
if (benchRunning > 0) {
// Keep function optimized by not leaking the `arguments` object
args = new Array(arguments.length);
for (i = 0; i < args.length; i++) args[i] = arguments[i];
benchQueue.push(args);
return;
}
benchRunning++;
// See how many times we can get it to run for 300ms
Collection.Function.doTime(300, fn, function(err, runs, elapsed) {
// See how the baseline latency is like
Blast.getEventLatencyBaseline(function(err, median) {
asyncTest(fn, runs, median+(getFunctionOverhead(runs)*8), function asyncDone(err, result) {
var next,
name;
// Call the callback
if (callback) {
result.name = fn.name || '';
callback(err, result);
} else {
name = fn.name || '';
if (name) name = 'for "' + name + '" ';
console.log('Benchmark ' + name + 'did ' + Bound.Number.humanize(result.ops) + '/s (' + Bound.Number.humanize(result.iterations) + ' iterations)');
}
benchRunning--;
// Schedule a next benchmark
if (benchRunning == 0 && benchQueue.length > 0) {
// Get the top of the queue
next = benchQueue.shift();
Blast.setImmediate(function() {
doAsyncBench.apply(null, next);
});
}
});
});
});
} | javascript | {
"resource": ""
} |
q11406 | WhileStatement | train | function WhileStatement(node, print) {
this.keyword("while");
this.push("(");
print.plain(node.test);
this.push(")");
print.block(node.body);
} | javascript | {
"resource": ""
} |
q11407 | buildForXStatement | train | function buildForXStatement(op) {
return function (node, print) {
this.keyword("for");
this.push("(");
print.plain(node.left);
this.push(" " + op + " ");
print.plain(node.right);
this.push(")");
print.block(node.body);
};
} | javascript | {
"resource": ""
} |
q11408 | CatchClause | train | function CatchClause(node, print) {
this.keyword("catch");
this.push("(");
print.plain(node.param);
this.push(") ");
print.plain(node.body);
} | javascript | {
"resource": ""
} |
q11409 | SwitchStatement | train | function SwitchStatement(node, print) {
this.keyword("switch");
this.push("(");
print.plain(node.discriminant);
this.push(")");
this.space();
this.push("{");
print.sequence(node.cases, {
indent: true,
addNewlines: function addNewlines(leading, cas) {
if (!leading && node.cases[node.cases.length - 1] === cas) return -1;
}
});
this.push("}");
} | javascript | {
"resource": ""
} |
q11410 | has | train | function has(object) {
// The intent of this method is to replace unsafe tests relying on type
// coercion for optional arguments or obj properties:
// | function on(event,options){
// | options = options || {}; // type coercion
// | if (!event || !event.data || !event.data.value){
// | // unsafe due to type coercion: all falsy values '', false, 0
// | // are discarded, not just null and undefined
// | return;
// | }
// | // ...
// | }
// with a safer test without type coercion:
// | function on(event,options){
// | options = has(options)? options : {}; // no type coercion
// | if (!has(event,'data','value'){
// | // safe check: only null/undefined values are rejected;
// | return;
// | }
// | // ...
// | }
//
// Returns:
// * false if no argument is provided or if the obj is null or
// undefined, whatever the number of arguments
// * true if the full chain of nested properties is found in the obj
// and the corresponding value is neither null nor undefined
// * false otherwise
var i,
// iterative variable
length,
o = object,
property;
if (!is(o)) {
return false;
}
for (i = 1, length = arguments.length; i < length; i += 1) {
property = arguments[i];
o = o[property];
if (!is(o)) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
q11411 | extend | train | function extend(receiver, extension, path) {
var props = has(path) ? path.split('.') : [],
target = receiver,
i; // iterative variable
for (i = 0; i < props.length; i += 1) {
if (!has(target, props[i])) {
target[props[i]] = {};
}
target = target[props[i]];
}
mix(target, extension);
return target;
} | javascript | {
"resource": ""
} |
q11412 | get | train | function get(o, path, defaultValue) {
var props = path.split('.'),
i,
// iterative variable
p,
// current property
success = true;
for (i = 0; i < props.length; i += 1) {
p = props[i];
if (has(o, p)) {
o = o[p];
} else {
success = false;
break;
}
}
return success ? o : defaultValue;
} | javascript | {
"resource": ""
} |
q11413 | stringify | train | function stringify(obj) {
var cache = [];
return JSON.stringify(obj, function (key, value) {
if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
return '[Circular]';
}
cache.push(value);
}
return value;
});
} | javascript | {
"resource": ""
} |
q11414 | getClassNames | train | function getClassNames(classObject) {
var classNames = [];
for (var key in classObject) {
if (classObject.hasOwnProperty(key)) {
let check = classObject[key];
let className = _.kebabCase(key);
if (_.isFunction(check)) {
if (check()) {
classNames.push(className);
}
} else if (_.isString(check)) {
if (className === 'include' || _.includes(check, ' ')) {
classNames = _.concat(classNames, check.split(' '));
} else {
classNames.push(className + '-' + _.kebabCase(check));
}
} else if (check) {
classNames.push(className);
}
}
}
classNames = _.uniq(classNames);
return classNames.join(' ');
} | javascript | {
"resource": ""
} |
q11415 | train | function (data){
//create a new item object, place data in
var node = {
data: data,
next: null,
prev: null
};
//special case: no items in the list yet
if (this._length == 0) {
this._head = node;
this._tail = node;
} else {
//attach to the tail node
this._tail.next = node;
node.prev = this._tail;
this._tail = node;
}
//don't forget to update the count
this._length++;
} | javascript | {
"resource": ""
} | |
q11416 | train | function(index){
//check for out-of-bounds values
if (index > -1 && index < this._length){
var current = this._head,
i = 0;
while(i++ < index){
current = current.next;
}
return current.data;
} else {
return null;
}
} | javascript | {
"resource": ""
} | |
q11417 | train | function(start, end){
//subQueue to Array
if(start >= 0 && start < end && end <= this._length) {
var result = [],
current = this._head,
i = 0;
while(i++ < start) {
current = current.next;
}
while(start++ < end) {
var value = current.data.value;
if(value != null) {
result.push(current.data.value);
}
current = current.next;
}
return result;
}
var result = [],
current = this._head;
while(current){
result.push(current.data);
current = current.next;
}
return result;
} | javascript | {
"resource": ""
} | |
q11418 | formatError | train | function formatError(e) {
var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
} | javascript | {
"resource": ""
} |
q11419 | formatObject | train | function formatObject(o) {
var s = String(o);
if(s === '[object Object]' && typeof JSON !== 'undefined') {
s = tryStringify(o, s);
}
return s;
} | javascript | {
"resource": ""
} |
q11420 | init | train | function init(resolver) {
var handler = new Pending();
try {
resolver(promiseResolve, promiseReject, promiseNotify);
} catch (e) {
promiseReject(e);
}
return handler;
/**
* Transition from pre-resolution state to post-resolution state, notifying
* all listeners of the ultimate fulfillment or rejection
* @param {*} x resolution value
*/
function promiseResolve (x) {
handler.resolve(x);
}
/**
* Reject this promise with reason, which will be used verbatim
* @param {Error|*} reason rejection reason, strongly suggested
* to be an Error type
*/
function promiseReject (reason) {
handler.reject(reason);
}
/**
* @deprecated
* Issue a progress event, notifying all progress listeners
* @param {*} x progress event payload to pass to all listeners
*/
function promiseNotify (x) {
handler.notify(x);
}
} | javascript | {
"resource": ""
} |
q11421 | resolve | train | function resolve(x) {
return isPromise(x) ? x
: new Promise(Handler, new Async(getHandler(x)));
} | javascript | {
"resource": ""
} |
q11422 | race | train | function race(promises) {
if(typeof promises !== 'object' || promises === null) {
return reject(new TypeError('non-iterable passed to race()'));
}
// Sigh, race([]) is untestable unless we return *something*
// that is recognizable without calling .then() on it.
return promises.length === 0 ? never()
: promises.length === 1 ? resolve(promises[0])
: runRace(promises);
} | javascript | {
"resource": ""
} |
q11423 | getHandler | train | function getHandler(x) {
if(isPromise(x)) {
return x._handler.join();
}
return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
} | javascript | {
"resource": ""
} |
q11424 | getHandlerUntrusted | train | function getHandlerUntrusted(x) {
try {
var untrustedThen = x.then;
return typeof untrustedThen === 'function'
? new Thenable(untrustedThen, x)
: new Fulfilled(x);
} catch(e) {
return new Rejected(e);
}
} | javascript | {
"resource": ""
} |
q11425 | Pending | train | function Pending(receiver, inheritedContext) {
Promise.createContext(this, inheritedContext);
this.consumers = void 0;
this.receiver = receiver;
this.handler = void 0;
this.resolved = false;
} | javascript | {
"resource": ""
} |
q11426 | Thenable | train | function Thenable(then, thenable) {
Pending.call(this);
tasks.enqueue(new AssimilateTask(then, thenable, this));
} | javascript | {
"resource": ""
} |
q11427 | Rejected | train | function Rejected(x) {
Promise.createContext(this);
this.id = ++errorId;
this.value = x;
this.handled = false;
this.reported = false;
this._report();
} | javascript | {
"resource": ""
} |
q11428 | AssimilateTask | train | function AssimilateTask(then, thenable, resolver) {
this._then = then;
this.thenable = thenable;
this.resolver = resolver;
} | javascript | {
"resource": ""
} |
q11429 | Fold | train | function Fold(f, z, c, to) {
this.f = f; this.z = z; this.c = c; this.to = to;
this.resolver = failIfRejected;
this.receiver = this;
} | javascript | {
"resource": ""
} |
q11430 | tryCatchReject3 | train | function tryCatchReject3(f, x, y, thisArg, next) {
try {
f.call(thisArg, x, y, next);
} catch(e) {
next.become(new Rejected(e));
}
} | javascript | {
"resource": ""
} |
q11431 | copy | train | function copy(out, a) {
out[0] = a[0]
out[1] = a[1]
out[2] = a[2]
out[3] = a[3]
return out
} | javascript | {
"resource": ""
} |
q11432 | RESTController | train | function RESTController(i,o,a,r){
var fn
for (var j=0; j < RESTController.filters.length; j++) {
fn = RESTController.filters[j]
if (typeof fn === 'function')
fn(i,o,a,r)
}
fn = RESTController[i.method.toLowerCase()]
if (fn)
fn(i,o,a,r)
else
r.error('404')
} | javascript | {
"resource": ""
} |
q11433 | train | function(element, options) {
var $el = $(element);
// React on every server/socket.io message.
// If the element is defined with a data-react-on-event attribute
// we take that as an eventType the user wants to be warned on this
// element and we forward the event via jQuery events on $(this).
this.initReactOnEveryMessage($el, options.reactOnMessage);
// React on server message.
// If the element is defined with a data-react-on-event attribute
// we take that as an eventType the user wants to be warned on this
// element and we forward the event via jQuery events on $(this).
if (options.reactOnMessage) {
this.initReactOnMessage($el, options.reactOnMessage);
}
// React on events originated from a data update in the backend
// The user decides which object wants to be notified from with the
// attribute data-react-on-dataupdate
if (options.reactOnDataupdate) {
this.initReactOnDataupdate($el, options.reactOnDataupdate);
}
if (options.reactOnUserinput) {
// And make every form submit trigger the userinput message
this.initReactOnUserInput($el, options.reactOnUserinput);
}
// react on routes updates using page.js
// the attribute data-react-on-page holds the route
// that is passed to page(...);
if (options.onRoute) {
this.initOnRoute($el, options.onRoute);
}
$myelements.attachDefaultEventHandlers(element);
// Render first time. empty. passing data- attributes
// as locals to the EJS engine.
// TODO: Should load from localstorage.
// Take the innerHTML as a template.
$myelements.updateElementScope(element);
// Init page routing using page.js
// multiple calls to page() are ignored
// so it's safe to callit on every element initialization
page();
$(element).trigger("init");
} | javascript | {
"resource": ""
} | |
q11434 | train | function(el, data) {
var dataupdateScope = $(el).data().reactOnDataupdate;
var templateScope = $(el).data().templateScope;
var userinputScope = $(el).data().reactOnUserinput;
if (data) {
$myelements.doRender(el, data);
} else if (!data && templateScope) {
$myelements.recoverTemplateScopeFromCache(el, templateScope);
return;
} else if (!data && dataupdateScope) {
$myelements.recoverTemplateScopeFromCache(el, dataupdateScope);
return;
} else if (!data && userinputScope) {
$myelements.recoverTemplateScopeFromCache(el, userinputScope);
}
} | javascript | {
"resource": ""
} | |
q11435 | train | function(el, scope) {
var tplScopeObject = {};
$myelements.debug("Trying to update Element Scope without data from scope: %s", scope);
// If no data is passed
// we look up in localstorage
$myelements.localDataForElement(el, scope, function onLocalDataForElement(err, data) {
if (err) {
// Maybe this is useless if there's no data to update.
// If I don't do this, the element keeps its EJS tags untouched
$myelements.debug("Updating element scope with empty object");
// Default to [] because it's an object and its iterable.
// This way EJS templates cand use $().each to avoid 'undefined'errors
data = [];
}
tplScopeObject[scope] = data;
$myelements.doRender(el, tplScopeObject);
});
} | javascript | {
"resource": ""
} | |
q11436 | train | function(el, data, done) {
if (!el.template) {
$myelements.debug("Creating EJS template from innerHTML for element: ", el);
// Save the compiled template only once
try {
el.template = new EJS({
element: el
});
} catch (e) {
console.error("myelements.jquery: Error parsing element's innerHTML as an EJS template: ", e.toString(),
"\nThis parsing error usually happens when there are syntax errors in your EJS code.",
"\nThe elements that errored is ", el);
el.template = undefined;
return;
}
}
try {
// pass a locals variable as render scope`
var html = el.template.render({
locals: data
});
} catch (e) {
console.error("myelements.jquery: Error rendering element's template: ", e.toString(),
"\nThis rendering error usually happens when refering an undefined variable.",
"\nThe elements that errored is ", el);
return;
}
el.innerHTML = html;
// $this.html(html);
// Ensure every form in the element
// is submitted via myelements.
// Called after render because the original forms get dumped on render
$myelements.handleFormSubmissions(el);
if (typeof done === "function") {
return done(html);
}
} | javascript | {
"resource": ""
} | |
q11437 | train | function(cb) {
// If we're inside phonegap use its event.
if (window.phonegap) {
return document.addEventListener("offline", cb, false);
} else if (window.addEventListener) {
// With the offline HTML5 event from the window
this.addLocalEventListener(window, "offline", cb);
} else {
/*
Works in IE with the Work Offline option in the
File menu and pulling the ethernet cable
Ref: http://robertnyman.com/html5/offline/online-offline-events.html
*/
document.body.onoffline = cb;
}
} | javascript | {
"resource": ""
} | |
q11438 | train | function($el) {
// Reaction to socket.io messages
$myelements.socket.on("message", function onMessage(message) {
if ($el.data().templateScope === message.event) {
// Update element scope (maybe re-render)
var scope = {};
scope[message.event] = message.data;
$myelements.updateElementScope($el.get(0), scope);
}
// we forward socket.io's message as a jQuery event on the $el.
$myelements.debug("forwarding backend message '%s' as jQuery event '%s' to element %s with data: %j", message.event, message.event, $el.get(0), message.data);
// Kludge: If jQuery's trigger received an array as second parameters
// it assumes you're trying to send multiple parameters to the event handlers,
// so we enclose message.data in another array if message.data is an array
// sent from the backend
if ($.isArray(message.data)) {
$el.trigger(message.event, [message.data]);
} else {
$el.trigger(message.event, message.data);
}
});
// Reaction on local events triggered on the element by jQuery
$el.on("message", function onElementMessageEvent(jQueryEvent, message) {
if (message.event === undefined || message.data === undefined) {
$myelements.debug("event key or data not present in second argument to trigger()", message.event, message.data);
console.error("myelements.jquery: $.fn.trigger('message') must be called with an object having the keys 'event' and 'data' as second argument. ");
return;
}
$myelements.debug("Sending message '%s' to backend with data: %j", message.event, message.data);
$myelements.socket.send(message);
});
} | javascript | {
"resource": ""
} | |
q11439 | execute | train | function execute() {
var context = getDefaultContext();
var compiledOutput = fs.readFileSync(this.outputPath)
vm.runInContext(compiledOutput, context, this.outputPath);
var module = extractModule(this.moduleName, context);
this.compiledModule = context.Elm.fullscreen(module, this.defaults);
} | javascript | {
"resource": ""
} |
q11440 | wrap | train | function wrap() {
var ports = this.compiledModule.ports;
var incomingEmitter = new EventEmitter();
var outgoingEmitter = new EventEmitter();
var emit = incomingEmitter.emit.bind(incomingEmitter);
Object.keys(ports).forEach(function(key) {
outgoingEmitter.addListener(key, function() {
var args = Array.prototype.slice.call(arguments)
ports[key].send.apply(ports[key], args);
});
if (ports[key].subscribe) {
ports[key].subscribe(function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(key);
emit.apply(incomingEmitter, args);
});
}
});
incomingEmitter.emit = outgoingEmitter.emit.bind(outgoingEmitter);;
this.emitter = incomingEmitter;
this.ports = this.compiledModule.ports;
} | javascript | {
"resource": ""
} |
q11441 | mkdirsInner | train | function mkdirsInner(dirnames, currentPath, callback) {
// Check for completion and call callback
if (dirnames.length === 0) {
return _callback(callback);
}
// Make next directory
var dirname = dirnames.shift();
currentPath = path.join(currentPath, dirname);
fs.mkdir(currentPath, function(err) {
return mkdirsInner(dirnames, currentPath, callback);
});
} | javascript | {
"resource": ""
} |
q11442 | pushResultsArray | train | function pushResultsArray(obj, size) {
if (typeof obj === "string" && obj in stack) {
stack[obj]["size"] = size;
return;
}
if (!(obj.module in stack)) {
stack[obj.module] = obj;
}
} | javascript | {
"resource": ""
} |
q11443 | ClassBody | train | function ClassBody(node, print) {
this.push("{");
if (node.body.length === 0) {
print.printInnerComments();
this.push("}");
} else {
this.newline();
this.indent();
print.sequence(node.body);
this.dedent();
this.rightBrace();
}
} | javascript | {
"resource": ""
} |
q11444 | loadModule | train | function loadModule(loader, name, options) {
return new Promise(asyncStartLoadPartwayThrough({
step: options.address ? 'fetch' : 'locate',
loader: loader,
moduleName: name,
// allow metadata for import https://bugs.ecmascript.org/show_bug.cgi?id=3091
moduleMetadata: options && options.metadata || {},
moduleSource: options.source,
moduleAddress: options.address
}));
} | javascript | {
"resource": ""
} |
q11445 | requestLoad | train | function requestLoad(loader, request, refererName, refererAddress) {
// 15.2.4.2.1 CallNormalize
return new Promise(function(resolve, reject) {
resolve(loader.loaderObj.normalize(request, refererName, refererAddress));
})
// 15.2.4.2.2 GetOrCreateLoad
.then(function(name) {
var load;
if (loader.modules[name]) {
load = createLoad(name);
load.status = 'linked';
// https://bugs.ecmascript.org/show_bug.cgi?id=2795
load.module = loader.modules[name];
return load;
}
for (var i = 0, l = loader.loads.length; i < l; i++) {
load = loader.loads[i];
if (load.name != name)
continue;
return load;
}
load = createLoad(name);
loader.loads.push(load);
proceedToLocate(loader, load);
return load;
});
} | javascript | {
"resource": ""
} |
q11446 | asyncStartLoadPartwayThrough | train | function asyncStartLoadPartwayThrough(stepState) {
return function(resolve, reject) {
var loader = stepState.loader;
var name = stepState.moduleName;
var step = stepState.step;
if (loader.modules[name])
throw new TypeError('"' + name + '" already exists in the module table');
// adjusted to pick up existing loads
var existingLoad;
for (var i = 0, l = loader.loads.length; i < l; i++) {
if (loader.loads[i].name == name) {
existingLoad = loader.loads[i];
if (step == 'translate' && !existingLoad.source) {
existingLoad.address = stepState.moduleAddress;
proceedToTranslate(loader, existingLoad, Promise.resolve(stepState.moduleSource));
}
// a primary load -> use that existing linkset if it is for the direct load here
// otherwise create a new linkset unit
if (existingLoad.linkSets.length && existingLoad.linkSets[0].loads[0].name == existingLoad.name)
return existingLoad.linkSets[0].done.then(function() {
resolve(existingLoad);
});
}
}
var load = existingLoad || createLoad(name);
load.metadata = stepState.moduleMetadata;
var linkSet = createLinkSet(loader, load);
loader.loads.push(load);
resolve(linkSet.done);
if (step == 'locate')
proceedToLocate(loader, load);
else if (step == 'fetch')
proceedToFetch(loader, load, Promise.resolve(stepState.moduleAddress));
else {
console.assert(step == 'translate', 'translate step');
load.address = stepState.moduleAddress;
proceedToTranslate(loader, load, Promise.resolve(stepState.moduleSource));
}
}
} | javascript | {
"resource": ""
} |
q11447 | doLink | train | function doLink(linkSet) {
var error = false;
try {
link(linkSet, function(load, exc) {
linkSetFailed(linkSet, load, exc);
error = true;
});
}
catch(e) {
linkSetFailed(linkSet, null, e);
error = true;
}
return error;
} | javascript | {
"resource": ""
} |
q11448 | train | function(name, source, options) {
// check if already defined
if (this._loader.importPromises[name])
throw new TypeError('Module is already loading.');
return createImportPromise(this, name, new Promise(asyncStartLoadPartwayThrough({
step: 'translate',
loader: this._loader,
moduleName: name,
moduleMetadata: options && options.metadata || {},
moduleSource: source,
moduleAddress: options && options.address
})));
} | javascript | {
"resource": ""
} | |
q11449 | train | function(name) {
var loader = this._loader;
delete loader.importPromises[name];
delete loader.moduleRecords[name];
return loader.modules[name] ? delete loader.modules[name] : false;
} | javascript | {
"resource": ""
} | |
q11450 | train | function(source, options) {
var load = createLoad();
load.address = options && options.address;
var linkSet = createLinkSet(this._loader, load);
var sourcePromise = Promise.resolve(source);
var loader = this._loader;
var p = linkSet.done.then(function() {
return load.module.module;
});
proceedToTranslate(loader, load, sourcePromise);
return p;
} | javascript | {
"resource": ""
} | |
q11451 | getESModule | train | function getESModule(exports) {
var esModule = {};
// don't trigger getters/setters in environments that support them
if ((typeof exports == 'object' || typeof exports == 'function') && exports !== __global) {
if (getOwnPropertyDescriptor) {
for (var p in exports) {
// The default property is copied to esModule later on
if (p === 'default')
continue;
defineOrCopyProperty(esModule, exports, p);
}
}
else {
extend(esModule, exports);
}
}
esModule['default'] = exports;
defineProperty(esModule, '__useDefault', {
value: true
});
return esModule;
} | javascript | {
"resource": ""
} |
q11452 | getPackageConfigMatch | train | function getPackageConfigMatch(loader, normalized) {
var pkgName, exactMatch = false, configPath;
for (var i = 0; i < loader.packageConfigPaths.length; i++) {
var packageConfigPath = loader.packageConfigPaths[i];
var p = packageConfigPaths[packageConfigPath] || (packageConfigPaths[packageConfigPath] = createPkgConfigPathObj(packageConfigPath));
if (normalized.length < p.length)
continue;
var match = normalized.match(p.regEx);
if (match && (!pkgName || (!(exactMatch && p.wildcard) && pkgName.length < match[1].length))) {
pkgName = match[1];
exactMatch = !p.wildcard;
configPath = pkgName + packageConfigPath.substr(p.length);
}
}
if (!pkgName)
return;
return {
packageName: pkgName,
configPath: configPath
};
} | javascript | {
"resource": ""
} |
q11453 | combinePluginParts | train | function combinePluginParts(loader, argumentName, pluginName, defaultExtension) {
if (defaultExtension && argumentName.substr(argumentName.length - 3, 3) == '.js')
argumentName = argumentName.substr(0, argumentName.length - 3);
if (loader.pluginFirst) {
return pluginName + '!' + argumentName;
}
else {
return argumentName + '!' + pluginName;
}
} | javascript | {
"resource": ""
} |
q11454 | getElements | train | function getElements(input) {
if (typeof input === 'string') {
return _getElements(document, input);
}
if (input instanceof window.NodeList || input instanceof window.HTMLCollection) {
return _nodelistToArray(input);
}
if (input instanceof Array) {
if (input['_chrsh-valid']) {
return input;
}
var output = [];
forEach(input, _pushRecursive.bind(null, output));
return _chirasizeArray(output);
}
return _chirasizeArray(isDomElement(input) ? [input] : []);
} | javascript | {
"resource": ""
} |
q11455 | forIn | train | function forIn(object, callback) {
if ((typeof object === 'undefined' ? 'undefined' : _typeof(object)) !== 'object') return;
forEach(Object.keys(object), _forKey.bind(null, object, callback));
return object;
} | javascript | {
"resource": ""
} |
q11456 | getElement | train | function getElement(input) {
if (typeof input === 'string') {
return _getElement(document, input);
}
if (input instanceof window.NodeList || input instanceof window.HTMLCollection) {
return input[0];
}
if (input instanceof Array) {
return getElement(input[0]);
}
return isDomElement(input) && input;
} | javascript | {
"resource": ""
} |
q11457 | append | train | function append(element, nodes) {
element = getElement(element);
if (!element || !element.appendChild) return false;
forEach(nodes, _appendOne.bind(null, element));
return element;
} | javascript | {
"resource": ""
} |
q11458 | closest | train | function closest(element, tested) {
var limit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : document;
element = getElement(element);
if (!element || (typeof limit === 'string' ? element.matches(limit) : element === limit)) {
return false;
}
if (typeof tested === 'string' ? element.matches(tested) : element === tested) {
return element;
}
return !!element.parentNode && closest(element.parentNode, tested, limit);
} | javascript | {
"resource": ""
} |
q11459 | findOne | train | function findOne(element, selector) {
return (element = getElement(element)) ? _getElement(element, selector) : null;
} | javascript | {
"resource": ""
} |
q11460 | hasClass | train | function hasClass(element) {
element = getElement(element);
if (!element) return;
var n = arguments.length <= 1 ? 0 : arguments.length - 1;
var found = void 0;
var i = 0;
while (i < n && (found = element.classList.contains((_ref = i++ + 1, arguments.length <= _ref ? undefined : arguments[_ref])))) {
var _ref;
}
return found;
} | javascript | {
"resource": ""
} |
q11461 | removeClass | train | function removeClass(elements) {
for (var _len = arguments.length, classes = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
classes[_key - 1] = arguments[_key];
}
return _updateClassList(elements, 'remove', classes);
} | javascript | {
"resource": ""
} |
q11462 | setData | train | function setData(elements, dataAttributes) {
var attributes = {};
forIn(dataAttributes, _prefixAttribute.bind(null, attributes));
return setAttr(elements, attributes);
} | javascript | {
"resource": ""
} |
q11463 | toggleClass | train | function toggleClass(elements) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (_typeof(args[0]) === 'object') {
forIn(args[0], _toggleClassesWithForce.bind(null, elements));
} else {
forEach(args, _toggleClassName.bind(null, elements));
}
} | javascript | {
"resource": ""
} |
q11464 | on | train | function on(elements, input) {
elements = _setEvents(elements, 'add', input);
return function (offElements, events) {
_setEvents(offElements || elements, 'remove', events ? defineProperty({}, events, input[events]) : input);
};
} | javascript | {
"resource": ""
} |
q11465 | delegate | train | function delegate(selector, input) {
var target = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : document.body;
target = getElement(target);
var eventsObj = {};
forIn(input, _wrapOptions.bind(null, selector, target, eventsObj));
var off = on(target, eventsObj);
return function (events) {
off(target, events);
};
} | javascript | {
"resource": ""
} |
q11466 | once | train | function once(elements, input) {
var eachElement = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var eachEvent = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var off = void 0;
var eventsObj = {};
forIn(input, function (events, callback) {
eventsObj[events] = function (event) {
callback(event);
off(eachElement && event.currentTarget, eachEvent && events);
};
});
return off = on(elements, eventsObj);
} | javascript | {
"resource": ""
} |
q11467 | trigger | train | function trigger(elements, events) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
elements = getElements(elements);
if (!elements.length) return;
options = _extends({}, options, defaults$1);
forEach(_stringToArray(events), _createEvent.bind(null, elements, options));
return elements;
} | javascript | {
"resource": ""
} |
q11468 | clearStyle | train | function clearStyle(elements) {
var style = {};
for (var _len = arguments.length, props = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
props[_key - 1] = arguments[_key];
}
forEach(props, _resetProp.bind(null, style));
return setStyleProp(elements, style);
} | javascript | {
"resource": ""
} |
q11469 | getHeight | train | function getHeight(element) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
return _getLength(element, 'Height', offset);
} | javascript | {
"resource": ""
} |
q11470 | getWidth | train | function getWidth(element) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
return _getLength(element, 'Width', offset);
} | javascript | {
"resource": ""
} |
q11471 | getSize | train | function getSize(element) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
return {
width: getWidth(element, offset),
height: getHeight(element, offset)
};
} | javascript | {
"resource": ""
} |
q11472 | getStyleProp | train | function getStyleProp(element) {
var computedStyle = getComputedStyle(element);
if (!computedStyle) return false;
for (var _len = arguments.length, props = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
props[_key - 1] = arguments[_key];
}
return _getOneOrMore(props, _parseProp.bind(null, computedStyle));
} | javascript | {
"resource": ""
} |
q11473 | offset | train | function offset(element) {
var screenPos = screenPosition(element);
return screenPos && {
top: screenPos.top + window.scrollY,
left: screenPos.left + window.scrollX
};
} | javascript | {
"resource": ""
} |
q11474 | plugin | train | function plugin(plugins) {
var z, method, conf;
for(z in plugins) {
if(typeof plugins[z] === 'function') {
method = plugins[z];
}else{
method = plugins[z].plugin;
conf = plugins[z].conf;
}
if(opts.field && typeof method[opts.field] === 'function') {
method = method[opts.field];
}
method.call(proto, conf);
}
return main;
} | javascript | {
"resource": ""
} |
q11475 | hook | train | function hook() {
var comp = hook.proxy.apply(null, arguments);
for(var i = 0;i < hooks.length;i++) {
hooks[i].apply(comp, arguments);
}
return comp;
} | javascript | {
"resource": ""
} |
q11476 | widthTraverse | train | function widthTraverse (graph, reachable, start, depth, hops, iter) {
if(!start)
throw new Error('Graphmitter#traverse: start must be provided')
//var nodes = 1
reachable[start] = reachable[start] == null ? 0 : reachable[start]
var queue = [start] //{key: start, hops: depth}]
iter = iter || function () {}
while(queue.length) {
var o = queue.shift()
var h = reachable[o]
var node = graph[o]
if(node && (!hops || (h + 1 <= hops)))
for(var k in node) {
// If we have already been to this node by a shorter path,
// then skip this node (this only happens when processing
// a realtime edge)
if(!(reachable[k] != null && reachable[k] < h + 1)) {
if(false === iter(o, k, h + 1, reachable[k]))
return reachable
reachable[k] = h + 1
// nodes ++
queue.push(k)
}
}
}
return reachable
} | javascript | {
"resource": ""
} |
q11477 | toArray | train | function toArray (span, root) {
if(!span[root]) return null
var a = [root]
while(span[root])
a.push(root = span[root])
return a.reverse()
} | javascript | {
"resource": ""
} |
q11478 | train | function(oldObserved, newObserveSet, onchanged) {
for (var name in newObserveSet) {
bindOrPreventUnbinding(oldObserved, newObserveSet, name, onchanged);
}
} | javascript | {
"resource": ""
} | |
q11479 | train | function(oldObserved, newObserveSet, name, onchanged) {
if (oldObserved[name]) {
// After binding is set up, values
// in `oldObserved` will be unbound. So if a name
// has already be observed, remove from `oldObserved`
// to prevent this.
delete oldObserved[name];
} else {
// If current name has not been observed, listen to it.
var obEv = newObserveSet[name];
obEv.obj.bind(obEv.event, onchanged);
}
} | javascript | {
"resource": ""
} | |
q11480 | train | function() {
bundle.browserify.pipeline.get('deps').push(through.obj(function(row, enc, next) {
var file = row.expose ? bundle.browserify._expose[row.id] : row.file;
if (self.cache) {
bundle.browserifyOptions.cache[file] = {
source: row.source,
deps: xtend({}, row.deps)
};
}
this.push(row);
next();
}));
} | javascript | {
"resource": ""
} | |
q11481 | IkoReporter | train | function IkoReporter(baseReporterDecorator, config, loggerFactory, formatError) {
// extend the base reporter
baseReporterDecorator(this);
const logger = loggerFactory.create("reporter.iko");
const divider = "=".repeat(process.stdout.columns || 80);
let slow = 0;
let totalTime = 0;
let netTime = 0;
let failedTests = [];
let firstRun = true;
let isRunCompleted = false;
// disable chalk when colors is set to false
chalk.enabled = config.colors !== false;
const self = this;
const write = function () {
for (let i = 0; i < arguments.length; i++) {
self.write(arguments[i]);
}
}
this.onSpecComplete = (browser, result) => {
const suite = result.suite;
const description = result.description;
write(Colors.browserName(`${browser.name} `));
if (result.skipped) {
write(Colors.testSkip(`${Symbols.info} ${suiteName(suite)}${description}\n`));
} else if (result.success) {
write(Colors.testPass(`${Symbols.success} ${suiteName(suite)}${description}`));
if (config.reportSlowerThan && result.time > config.reportSlowerThan) {
write(Colors.testSlow(" (slow: " + formatTime(result.time) + ")"));
slow++;
}
write("\n");
} else {
failedTests.push({ browser: browser, result: result });
write(Colors.testFail(`${Symbols.error} ${suiteName(suite)}${description}\n`));
}
};
this.onRunStart = () => {
if (!firstRun && divider) {
write(Colors.divider(`${divider}\n\n`));
}
failedTests = [];
firstRun = false;
isRunCompleted = false;
totalTime = 0;
netTime = 0;
slow = 0;
};
this.onBrowserStart = () => {
};
this.onRunComplete = (browsers, results) => {
browsers.forEach(function (browser) {
totalTime += browser.lastResult.totalTime;
});
// print extra error message for some special cases, e.g. when having the error "Some of your tests did a full page
// reload!" the onRunComplete() method is called twice
if (results.error && isRunCompleted) {
write("\n");
write(colors.error(`${Symbols.error} Error while running the tests! Exit code: ${results.exitCode}\n\n`));
return;
}
isRunCompleted = true;
const currentTime = new Date().toTimeString();
write(Colors.duration(`\n Finished in ${formatTime(totalTime)} / ${formatTime(netTime)} @ ${currentTime}\n\n`));
if (browsers.length > 0 && !results.disconnected) {
write(Colors.testPass(` ${Symbols.success} ${results.success} ${getTestNounFor(results.success)} completed\n`));
if (slow) {
write(Colors.testSlow(` ${Symbols.warning} ${slow} ${getTestNounFor(slow)} slow\n`));
}
if (results.failed) {
write(Colors.testFail(` ${Symbols.error} ${results.failed} ${getTestNounFor(results.failed)} failed\n\n`));
write(Colors.sectionTitle("FAILED TESTS:\n\n"));
failedTests.forEach(function (failedTest) {
const browser = failedTest.browser;
const result = failedTest.result;
const logs = result.log;
const assertionErrors = result.assertionErrors;
write(Colors.browserName(browser.name), "\n");
write(Colors.errorTitle(` ${Symbols.error} ${suiteName(result.suite)}${result.description}\n\n`));
if (assertionErrors.length > 0) {
for (let i = 0; i < assertionErrors.length; i++) {
const error = assertionErrors[i];
const rawMessage = error.message;
const message = renderAssertionError({ text: rawMessage, annotations: error.annotations });
let stack = error.stack;
if (rawMessage) {
const index = stack.indexOf(rawMessage);
if (index !== -1) {
stack = stack.slice(index + rawMessage.length + 1);
}
}
stack = leftPad(" ", stack);
write(leftPad(" ", message), "\n");
write(Colors.errorStack(formatError(stack)), "\n");
}
} else if (logs.length > 0) {
for (let i = 0; i < logs.length; i++) {
write(Colors.errorMessage(leftPad(" ", formatError(logs[i]))), "\n");
}
}
});
}
}
write("\n");
};
} | javascript | {
"resource": ""
} |
q11482 | train | function(options){
if (!options) {
options = {
cwd: workingDirectory
};
return options;
} else {
workingDirectory = options.cwd;
return options;
}
} | javascript | {
"resource": ""
} | |
q11483 | train | function (command, options) {
var exec = require('child_process').exec;
var defer = Q.defer();
//Prepare the options object to be valid
options = prepareOptions(options);
//Activate-Deactivate command logging execution
printCommandExecution(command, options);
exec('git ' + prepareCommand(command), options, function (err, stdout, stderr) {
//Activate-deactivate err and out logging
printCommandResponse({err:err, stdout:stdout, stderr:stderr});
if (err) {
defer.reject({err: err, stderr: stderr});
} else {
defer.resolve({res:stdout, out:stderr});
}
});
return defer.promise;
} | javascript | {
"resource": ""
} | |
q11484 | plugin | train | function plugin(options){
options = options || {};
var keys = options.keys || [];
return function(files, metalsmith, done){
setImmediate(done);
Object.keys(files).forEach(function(file){
debug('checking file: %s', file);
if (!isHtml(file)) return;
var data = files[file];
var dir = dirname(file);
var html = basename(file, extname(file)) + '.html';
if ('.' != dir) html = dir + '/' + html;
debug('Encoding html entities in file: %s', file);
var reg = /\`\`\`([\s\S]+?)\`\`\`/gi;
var rep = function(match, group) {
if (group) {
return he.encode(group, {useNamedReferences: true});
}
else {
return "";
}
};
var encoded = data.contents.toString().replace(reg, rep);
data.contents = new Buffer(encoded);
keys.forEach(function(key) {
data[key] = data[key].replace(reg, rep);
});
delete files[file];
files[html] = data;
});
};
} | javascript | {
"resource": ""
} |
q11485 | npmInstall | train | function npmInstall(packageName)
{
return new Promise((resolve,reject) => {
npm.load({
save:false,
progress: false,
force:true
}, function (er) {
if (er)
{
PAILogger.error(er);
return reject(er);
}
npm.commands.install([packageName], function (er, data) {
if (er) {
PAILogger.error(er);
return reject(er);
}
resolve(data);
// command succeeded, and data might have some info
});
});
});
} | javascript | {
"resource": ""
} |
q11486 | train | function(filePath, currentPath){
if(/^(?:\/|[a-zA-Z]:(?:\/|\\))/.test(filePath)){ // Is the path absolute?
filePath = path.normalize(filePath);
}else{ // Relative paths need to be resolved first
filePath = path.resolve(currentPath, filePath);
}
return filePath;
} | javascript | {
"resource": ""
} | |
q11487 | View | train | function View(tplPath, tplFile, data){
this.data = data||{};
this.defines = {};
this.enabled = true;
// Default settings
this.settings = doT.templateSettings;
this.settings.varname = 'it,helpers'; // Add the helpers as a second data param for the parser
this.settings.cache = true; // Use memory cache for compiled template functions
this.settings.layout = /\{\{##\s*(?:def\.)?_layout\s*(?:\:|=)\s*([\s\S]+?)\s*#\}\}/; // Layout regex
if(tplPath){ this.path = tplPath; }
if(tplFile){
this.file = tplFile;
this.layout();
}
} | javascript | {
"resource": ""
} |
q11488 | fullWidth | train | function fullWidth(text, param) {
let cols = process.stdout.columns;
let lines = text.split('\n');
for (i = 0; i < lines.length; i++) {
let size = cols;
if (i === 0) size = size - 15;
if ((lines[i].indexOf('%') > 0) && (param !== undefined)) size = size - param.length + 2;
while (lines[i].length < size) {
lines[i] = lines[i] + ' ';
}
}
text = lines.join('\n');
return text;
} | javascript | {
"resource": ""
} |
q11489 | revertInit | train | function revertInit(reinit, list, prefix, name, currentVersion) {
exec('rm -Rf ./.versionFilesList.json', function(error, stdout, stderr) {
if (error) sendProcessError(stdout, stderr);
print('Deleted previous .versionFilesList.json', 'important', 'date');
if (reinit) init(list, prefix, name, currentVersion);
});
} | javascript | {
"resource": ""
} |
q11490 | loadConfiguration | train | function loadConfiguration() {
let configuration;
if (isInit()) {
configuration = jsonReader('./.versionFilesList.json');
// check configuration file's integrity
if (!configuration.name || !configuration.currentVersion || !configuration.filesList || !configuration.versionPrefix) {
sendError('E002');
}
// check .versionFilesList.json for missing informations
if (configuration.name.length === 0 || configuration.currentVersion.length === 0) {
sendError('E001');
}
}
return configuration;
} | javascript | {
"resource": ""
} |
q11491 | discoverVersion | train | function discoverVersion() {
// try to understand package name and current version
// from package.json or bower.json
let packageFile;
let packageFileExtension;
let packageType;
let results = {
name: '',
currentVersion: ''
};
let possiblePackageFiles = ['package.json', 'bower.json', 'package.js'];
for (possiblePackageFile of possiblePackageFiles) {
if (fs.existsSync(possiblePackageFile)) {
packageFile = possiblePackageFile;
break;
}
}
packageFileExtension = packageFile.substr(packageFile.lastIndexOf('.') + 1);
if (packageFile) {
let packageData;
if (packageFileExtension === 'json') {
packageData = jsonReader(packageFile);
}
if (packageFileExtension === 'js') {
let tmpData = fs.readFileSync(packageFile).toString().split('\n');
let nameFound = false;
let versionFound = false;
packageData = {};
for (line of tmpData) {
if (line.indexOf('name:') >= 0) {
nameFound = true;
packageData.name = line.split(' ').pop().replace(/'/g, '').replace(/,/g, '');
}
if (line.indexOf('version:') >= 0) {
versionFound = true;
packageData.version = line.split(' ').pop().replace(/'/g, '').replace(/,/g, '');
}
if (nameFound && versionFound) {
break;
}
}
}
debugLog('Reading packageFile for init:');
debugLog('Discovered pacakge name: ' + packageData.name + ' - discovered package version ' + packageData.version);
if (packageData.name) {
results.name = packageData.name;
}
else {
print('Can\'t discover package name automatically', 'msgWarning', 'spaced22');
}
if (packageData.version) {
results.currentVersion = packageData.version;
}
else {
print('Can\'t discover package\'s currentVersion automatically', 'msgWarning', 'spaced22');
}
}
else {
print('Can\'t discover package name and/or currentVersion automatically', 'msgWarning', 'spaced22');
print('Please fill .versionFilesList.json with the missing informations', 'msgWarning', 'spaced22');
}
return results;
} | javascript | {
"resource": ""
} |
q11492 | patch | train | function patch(node, languages) {
var data = node.data || {};
var primary = languages[0][0];
data.language = primary === 'und' ? null : primary;
data.languages = languages;
node.data = data;
} | javascript | {
"resource": ""
} |
q11493 | concatenateFactory | train | function concatenateFactory() {
var queue = [];
/**
* Gather a parent if not already gathered.
*
* @param {NLCSTChildNode} node - Child.
* @param {number} index - Position of `node` in
* `parent`.
* @param {NLCSTParentNode} parent - Parent of `child`.
*/
function concatenate(node, index, parent) {
if (
parent &&
(parent.type === 'ParagraphNode' || parent.type === 'RootNode') &&
queue.indexOf(parent) === -1
) {
queue.push(parent);
}
}
/**
* Patch one parent.
*
* @param {NLCSTParentNode} node - Parent
* @return {Array.<Array.<string, number>>} - Language
* map.
*/
function one(node) {
var children = node.children;
var length = children.length;
var index = -1;
var languages;
var child;
var dictionary = {};
var tuple;
while (++index < length) {
child = children[index];
languages = child.data && child.data.languages;
if (languages) {
tuple = languages[0];
if (tuple[0] in dictionary) {
dictionary[tuple[0]] += tuple[1];
} else {
dictionary[tuple[0]] = tuple[1];
}
}
}
return sortDistanceObject(dictionary);
}
/**
* Patch all parents in reverse order: this means
* that first the last and deepest parent is invoked
* up to the first and highest parent.
*/
function done() {
var index = queue.length;
while (index--) {
patch(queue[index], one(queue[index]));
}
}
concatenate.done = done;
return concatenate;
} | javascript | {
"resource": ""
} |
q11494 | concatenate | train | function concatenate(node, index, parent) {
if (
parent &&
(parent.type === 'ParagraphNode' || parent.type === 'RootNode') &&
queue.indexOf(parent) === -1
) {
queue.push(parent);
}
} | javascript | {
"resource": ""
} |
q11495 | one | train | function one(node) {
var children = node.children;
var length = children.length;
var index = -1;
var languages;
var child;
var dictionary = {};
var tuple;
while (++index < length) {
child = children[index];
languages = child.data && child.data.languages;
if (languages) {
tuple = languages[0];
if (tuple[0] in dictionary) {
dictionary[tuple[0]] += tuple[1];
} else {
dictionary[tuple[0]] = tuple[1];
}
}
}
return sortDistanceObject(dictionary);
} | javascript | {
"resource": ""
} |
q11496 | fromCallback | train | function fromCallback(source) {
var callCount = 0;
// Throw an error if the source is not a function
if (typeof source !== 'function') {
throw new TypeError('Expected `source` to be a function.');
}
return new Readable({
objectMode: true,
read: function () {
var self = this;
// Increment the number of calls so we know when to push null
callCount += 1;
// Call the method and push results if this is the first call
if (callCount === 1) {
source(_.rest(function (err, parameters) {
if (err) {
process.nextTick(function () {
self.emit('error', err);
});
return;
}
// Push all parameters of the callback to the stream as an array
self.push(parameters);
}));
return;
}
// End the stream
self.push(null);
}
});
} | javascript | {
"resource": ""
} |
q11497 | train | function() {
Object.keys(this.name2Ws).forEach(function(name) {
delete this.name2Ws[name];
}.bind(this));
Object.keys(this.ws2Name).forEach(function(wsId) {
delete this.ws2Name[wsId];
}.bind(this));
} | javascript | {
"resource": ""
} | |
q11498 | train | function(text, lang, callback) {
if (arguments.length == 4) {
var options = callback;
callback = arguments[arguments.length - 1];
}
var uri = url.format({
pathname: url.resolve(baseAddress, 'lookup'),
query: {
key: dis.APIkey,
lang: lang,
text: text,
ui: options ? options.ui : null,
flags: options ? options.flags : null,
}
});
makeRequest(uri, callback);
} | javascript | {
"resource": ""
} | |
q11499 | getPlatforms | train | function getPlatforms(tdef) {
const platforms = [];
if (tdef) {
tdef.deployUnits.array.forEach((du) => {
const platform = du.findFiltersByID('platform');
if (platform && platforms.indexOf(platform.value) === -1) {
platforms.push(platform.value);
}
});
}
return platforms;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.