_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q10000
|
browserSpecific
|
train
|
function browserSpecific() {
var data = '';
return through(
function(buf) {
data += buf;
},
function() {
this.queue(data.replace(/\.\/node\//g, './browser/'));
this.queue(null);
}
);
}
|
javascript
|
{
"resource": ""
}
|
q10001
|
setMiddleware
|
train
|
function setMiddleware(Model, modelName, path) {
var RefModel;
// We only apply the middleware on the provided
// paths in the plugin options.
if (opts.onDeleteRestrict.indexOf(path) === -1) {
return;
}
RefModel = models[modelName];
RefModel.schema.pre('remove', function (next) {
var doc = this,
q = {};
q[path] = doc._id;
Model
.findOne(q)
.exec()
.then(function (doc) {
if (doc) {
return next(new Error('Unable to delete as ref exist in ' + Model.modelName + ' id:' + doc._id));
}
next();
}, next);
});
}
|
javascript
|
{
"resource": ""
}
|
q10002
|
train
|
function (start, end, force) {
var bytesRead;
if (end - start > config.bufferSize) {
return reject(new Error("Range exceeds the max buffer size"));
}
if (force || start < currentRange.start || (start > currentRange.end)) {
bytesRead = fs.readSync(fd, buffer, 0, config.bufferSize, start);
currentRange.start = start;
currentRange.end = start + bytesRead;
debug("buffering new range: %s", JSON.stringify(currentRange));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q10003
|
train
|
function (start, end) {
var offsetStart;
var offsetEnd;
loadBufferIfRequired(start, end);
offsetStart = start - currentRange.start;
offsetEnd = offsetStart + (end - start);
return buffer.slice(offsetStart, offsetEnd);
}
|
javascript
|
{
"resource": ""
}
|
|
q10004
|
train
|
function (index) {
var rawItem;
var position = positions[index];
try {
rawItem = readEntry(position.start, position.end);
return JSON.parse(rawItem);
} catch (ex) {
debug("ERROR reading item: %s -> %s", ex, rawItem);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q10005
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof AtomContent)){
return new AtomContent(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(AtomContent.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q10006
|
isValidWIF
|
train
|
function isValidWIF (key, network) {
try {
let dec = wif.decode(key);
if (network) {
return dec.version === network.wif
} else {
return true
}
} catch (e) {
console.error(e);
return false
}
}
|
javascript
|
{
"resource": ""
}
|
q10007
|
_cleanObserver
|
train
|
function _cleanObserver(observer) {
if (!attachedNotifierCountMap.get(observer) && !pendingChangesMap.has(observer)) {
attachedNotifierCountMap.delete(observer);
var index = observerCallbacks.indexOf(observer);
if (index !== -1) {
observerCallbacks.splice(index, 1);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q10008
|
train
|
function(callback) {
if (self._cxnState !== self.cxnStates.CONNECTED) {
callback(new Error("(2) Error occurred while attempting to lock "+ name));
return;
}
try {
// client doesn't like paths ending in /, so chop it off if lockpath != '/'
self._zk.mkdirp(lockpath.length <= 1 ? lockpath : lockpath.slice(0, -1), callback);
} catch (err) {
callback(err);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q10009
|
$$
|
train
|
function $$(selector, ctx) {
return Array.prototype.slice.call((ctx || document).querySelectorAll(selector))
}
|
javascript
|
{
"resource": ""
}
|
q10010
|
toggleVisibility
|
train
|
function toggleVisibility(dom, show) {
dom.style.display = show ? '' : 'none';
dom['hidden'] = show ? false : true;
}
|
javascript
|
{
"resource": ""
}
|
q10011
|
setAttr
|
train
|
function setAttr(dom, name, val) {
var xlink = XLINK_REGEX.exec(name);
if (xlink && xlink[1])
{ dom.setAttributeNS(XLINK_NS, xlink[1], val); }
else
{ dom.setAttribute(name, val); }
}
|
javascript
|
{
"resource": ""
}
|
q10012
|
defineProperty
|
train
|
function defineProperty(el, key, value, options) {
Object.defineProperty(el, key, extend({
value: value,
enumerable: false,
writable: false,
configurable: true
}, options));
return el
}
|
javascript
|
{
"resource": ""
}
|
q10013
|
handleEvent
|
train
|
function handleEvent(dom, handler, e) {
var ptag = this.__.parent,
item = this.__.item;
if (!item)
{ while (ptag && !item) {
item = ptag.__.item;
ptag = ptag.__.parent;
} }
// override the event properties
/* istanbul ignore next */
if (isWritable(e, 'currentTarget')) { e.currentTarget = dom; }
/* istanbul ignore next */
if (isWritable(e, 'target')) { e.target = e.srcElement; }
/* istanbul ignore next */
if (isWritable(e, 'which')) { e.which = e.charCode || e.keyCode; }
e.item = item;
handler.call(this, e);
// avoid auto updates
if (!settings$1.autoUpdate) { return }
if (!e.preventUpdate) {
var p = getImmediateCustomParentTag(this);
// fixes #2083
if (p.isMounted) { p.update(); }
}
}
|
javascript
|
{
"resource": ""
}
|
q10014
|
inheritFrom
|
train
|
function inheritFrom(target, propsInSyncWithParent) {
var this$1 = this;
each(Object.keys(target), function (k) {
// some properties must be always in sync with the parent tag
var mustSync = !isReservedName(k) && contains(propsInSyncWithParent, k);
if (isUndefined(this$1[k]) || mustSync) {
// track the property to keep in sync
// so we can keep it updated
if (!mustSync) { propsInSyncWithParent.push(k); }
this$1[k] = target[k];
}
});
}
|
javascript
|
{
"resource": ""
}
|
q10015
|
unmountAll
|
train
|
function unmountAll(expressions) {
each(expressions, function(expr) {
if (expr instanceof Tag$1) { expr.unmount(true); }
else if (expr.tagName) { expr.tag.unmount(true); }
else if (expr.unmount) { expr.unmount(); }
});
}
|
javascript
|
{
"resource": ""
}
|
q10016
|
selectTags
|
train
|
function selectTags(tags) {
// select all tags
if (!tags) {
var keys = Object.keys(__TAG_IMPL);
return keys + selectTags(keys)
}
return tags
.filter(function (t) { return !/[^-\w]/.test(t); })
.reduce(function (list, t) {
var name = t.trim().toLowerCase();
return list + ",[" + IS_DIRECTIVE + "=\"" + name + "\"]"
}, '')
}
|
javascript
|
{
"resource": ""
}
|
q10017
|
safeRegex
|
train
|
function safeRegex (re) {
var arguments$1 = arguments;
var src = re.source;
var opt = re.global ? 'g' : '';
if (re.ignoreCase) { opt += 'i'; }
if (re.multiline) { opt += 'm'; }
for (var i = 1; i < arguments.length; i++) {
src = src.replace('@', '\\' + arguments$1[i]);
}
return new RegExp(src, opt)
}
|
javascript
|
{
"resource": ""
}
|
q10018
|
globalEval
|
train
|
function globalEval (js, url) {
if (typeof js === T_STRING) {
var
node = mkEl('script'),
root = document.documentElement;
// make the source available in the "(no domain)" tab
// of Chrome DevTools, with a .js extension
if (url) { js += '\n//# sourceURL=' + url + '.js'; }
node.text = js;
root.appendChild(node);
root.removeChild(node);
}
}
|
javascript
|
{
"resource": ""
}
|
q10019
|
parse
|
train
|
function parse(tokens) {
var ast = [];
var current = ast;
var _line = 0;
var _char = 0;
var openCount = 0;
var closeCount = 0;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
switch (token.type) {
case TYPES.open:
// Every time we open a list, we drop into a sub-array
var child = [];
child.parent = current;
current.push(child);
current = child;
openCount += 1;
break;
case TYPES.open_array:
case TYPES.quote:
var child = [];
var quote = {"'": child };
child.parent = current;
current.push(quote);
current = child;
openCount += 1;
break;
case TYPES.close_array:
case TYPES.close:
// If no current, we probably have too many closing parens
if (!current) _tooManyClosingParensErr(closeCount, openCount);
// If we close a list, jump back up to the parent list
current = current.parent;
closeCount += 1;
break;
case TYPES.identifier:
case TYPES.suffixed_number:
current.push(token.string);
break;
case TYPES.number:
current.push(Number(token.string));
break;
case TYPES.string:
// We need to strip the quotes off the string entity
var dequoted = token.string.slice(1).slice(0, token.string.length - 2);
current.push(dequoted);
break;
case TYPES.json:
try {
var deticked = token.string.slice(1).slice(0, token.string.length - 2);
current.push(JSON.parse(deticked));
}
catch (e) {
throw new Error([
'Runiq: Couldn\'t parse inlined JSON!',
'--- Error occurred at line ' + _line + ', char ' + _char
].join('\n'));
}
break;
}
// Capture line numbers and columns for future use
var lines = token.string.split(NEWLINE);
_line += lines.length - 1;
if (lines.length > 1) _char = lines[lines.length - 1].length;
else _char += token.string.length;
}
// Raise error if we have a parentheses mismatch
if (openCount > closeCount) _tooManyOpenParensErr(closeCount, openCount);
if (openCount < closeCount) _tooManyClosingParensErr(closeCount, openCount);
// For both safety and to ensure we actually have a JSON-able AST
return JSON.parse(JSONStableStringify(ast));
}
|
javascript
|
{
"resource": ""
}
|
q10020
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof NamePart)){
return new NamePart(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(NamePart.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q10021
|
pathmap
|
train
|
function pathmap(path, spec, callback) {
return spec.replace(regexp, function(match, replace, count, token) {
var pattern;
if (pattern = pathmap.patterns[token]) {
return pattern.call(path, replace, count, callback);
} else {
throw new Error(
'Unknown pathmap specifier ' + match + ' in "' + spec + '"');
}
});
}
|
javascript
|
{
"resource": ""
}
|
q10022
|
train
|
function(replace, count, callback) {
return pathmap.replace(
pathmap.basename(this, pathmap.extname(this)), replace, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q10023
|
train
|
function(replace, count, callback) {
return pathmap.replace(
pathmap.dirname(this, count), replace, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q10024
|
train
|
function(replace, count, callback) {
return pathmap.replace(
pathmap.chomp(this, pathmap.extname(this)), replace, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q10025
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof SourceReference)){
return new SourceReference(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(SourceReference.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q10026
|
middleware
|
train
|
function middleware(fns) {
return through.obj(function(file, enc, cb) {
eachSeries(arrayify(fns), function(fn, next) {
try {
fn(file, next);
} catch (err) {
next(err);
}
}, function(err) {
cb(err, file);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q10027
|
toXML
|
train
|
function toXML(obj) {
var xml = ''
for (var prop in obj) {
xml += `<${prop}>${obj[prop]}</${prop}>`
}
return xml
}
|
javascript
|
{
"resource": ""
}
|
q10028
|
go
|
train
|
function go() {
return new Promise(handler)
// Check for invalid `authCode`, this seems to happen at random intervals
// within the neulion API, so we will only know when a request fails
.catch(Errors.AuthenticationError, function(err) {
// Authenticate and then try one more time
return self
.auth()
.then(function() {
return new Promise(handler)
})
})
}
|
javascript
|
{
"resource": ""
}
|
q10029
|
request
|
train
|
function request(meth, url, headers, query, data, cb) {
var req = SA(meth, url);
if (headers) req.set(headers);
if (query) req.query(query);
if (data) req.send(data);
return req.end(function(err, res) {
if (err) return cb(err);
return cb(null, res.text);
});
}
|
javascript
|
{
"resource": ""
}
|
q10030
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Event)){
return new Event(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Event.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q10031
|
loadNonCriticalCSS
|
train
|
function loadNonCriticalCSS (href) {
var link = window.document.createElement('link');
link.rel = 'stylesheet';
link.href = href;
window.document.getElementsByTagName('head')[0].appendChild(link);
}
|
javascript
|
{
"resource": ""
}
|
q10032
|
async
|
train
|
function async(value, bool) {
var def = promise()
setTimeout(function() {
if(!bool) def.fulfill(value)
else def.reject('error')
}, 10)
return def.promise
}
|
javascript
|
{
"resource": ""
}
|
q10033
|
Registry
|
train
|
function Registry(options) {
if (!(this instanceof Registry)) {
return new Registry(options);
}
options = options || {};
debug('New Registry: %j', options);
this.manager = options.manager || new UdpBroadcast();
this.services = {};
this._initProperties(options);
this._initManager();
assert(this.manager instanceof Manager, 'Invalid Manager type.');
}
|
javascript
|
{
"resource": ""
}
|
q10034
|
UdpBroadcastManager
|
train
|
function UdpBroadcastManager(options) {
if (!(this instanceof UdpBroadcastManager)) {
return new UdpBroadcastManager(options);
}
options = options || {};
Manager.call(this, options);
debug('New UdpBroadcastManager: %j', options);
this.dgramType = options.dgramType ? String(options.dgramType).toLowerCase() : Defaults.DGRAM_TYPE;
this.port = options.port || Defaults.PORT;
this.address = options.address || null;
this.multicastAddress = options.multicastAddress || Defaults.MULTICAST_ADDRESS;
this.interval = options.interval || Defaults.INTERVAL;
this.timeout = options.timeout || this.interval * 2.5;
this._timeoutTimerIds = {};
this._announceTimerId = null;
this._initSocket();
this._startAnnouncements();
}
|
javascript
|
{
"resource": ""
}
|
q10035
|
downloadSubtitles
|
train
|
async function downloadSubtitles (file) {
const subtitles = await getSubtitles(file)
const { dir, name } = path.parse(file)
const subtitlesFile = path.format({ dir, name, ext: '.srt' })
await fs.writeFile(subtitlesFile, subtitles)
return subtitlesFile
}
|
javascript
|
{
"resource": ""
}
|
q10036
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Field)){
return new Field(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Field.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q10037
|
_resolvePromises
|
train
|
function _resolvePromises (opts, val) {
opts = opts || {}
var duplicate = opts.duplicate
if (is(Array, val)) {
return Promise.all(duplicate ? concat([], val) : val)
} else if (duplicate && is(Object, val) && !is(Function, val.then)) {
return Object.assign({}, val)
}
return val
}
|
javascript
|
{
"resource": ""
}
|
q10038
|
_curry
|
train
|
function _curry (n, fn, args) {
args = args || []
return function partial () {
var rest = arrayFrom(arguments)
var allArgs = concat(args, rest)
return n > length(allArgs)
? _curry(n, fn, allArgs)
: _call(fn, allArgs.slice(0, n))
}
}
|
javascript
|
{
"resource": ""
}
|
q10039
|
handleError
|
train
|
function handleError (task) {
return function (err) {
console.log(chalk.red(err));
notify.onError(task + ' failed, check the logs..')(err);
};
}
|
javascript
|
{
"resource": ""
}
|
q10040
|
Interpreter
|
train
|
function Interpreter(library, options, storage) {
// What lengths I've gone to to use only 7-letter properties...
this.library = new Library(CloneDeep(library || {}));
this.options = Assign({}, Interpreter.DEFAULT_OPTIONS, options);
this.balance = this.options.balance;
this.timeout = Date.now() + this.options.timeout;
this.seednum = this.options.seed || Math.random();
this.counter = this.options.count || 0;
this.storage = storage || new Storage();
var outputs = this.outputs = [];
if (this.options.doCaptureConsole) {
Console.capture(function(type, messages) {
outputs.push({ type: type, messages: messages });
});
}
}
|
javascript
|
{
"resource": ""
}
|
q10041
|
exec
|
train
|
function exec(inst, raw, argv, event, fin) {
var after = nextup(inst, raw, argv, event, fin);
return step(inst, raw, argv, event, passthrough(after));
}
|
javascript
|
{
"resource": ""
}
|
q10042
|
nextup
|
train
|
function nextup(inst, orig, argv, event, cb) {
return function nextupCallback(err, data) {
if (err) return cb(err, null);
if (_isQuoted(data)) return cb(null, _unquote(data));
if (_isValue(data)) return cb(null, _entityToValue(data, inst.library));
// Remove any nulls or undefineds from the list
var compact = _compactList(data);
// Allow the programmer to opt out for _minor_ perf gains
if (inst.options.doIrreducibleListCheck) {
// If no change, we'll keep looping forever, so just return
if (IsEqual(orig, compact)) {
Console.printWarning(inst, 'Detected irreducible list; exiting...');
return cb(null, compact);
}
}
return exec(inst, compact, argv, event, cb);
};
}
|
javascript
|
{
"resource": ""
}
|
q10043
|
step
|
train
|
function step(inst, raw, argv, event, fin) {
if (!_isPresent(raw)) return fin(_wrapError(_badInput(inst), inst, raw), null);
var flat = _denestList(raw);
preproc(inst, flat, argv, event, function postPreproc(err, data) {
if (err) return fin(err);
var list = _safeObject(data);
return branch(inst, list, argv, event, fin);
});
}
|
javascript
|
{
"resource": ""
}
|
q10044
|
preproc
|
train
|
function preproc(inst, prog, argv, event, fin) {
var info = findPreprocs(inst, prog, [], []);
function step(procs, parts, list) {
if (!procs || procs.length < 1) {
return fin(null, list);
}
var part = parts.shift();
var proc = procs.shift();
var ctx = {
id: inst.counter,
seed: inst.seednum,
store: inst.storage,
argv: argv,
event: event
};
return proc.call(ctx, part, list, function(err, _list) {
if (err) return fin(err);
return step(procs, parts, _list);
});
}
return step(info.procs, info.parts, info.list);
}
|
javascript
|
{
"resource": ""
}
|
q10045
|
findPreprocs
|
train
|
function findPreprocs(inst, list, procs, parts) {
if (Array.isArray(list)) {
while (list.length > 0) {
var part = list.shift();
// Preprocessors must be the first elements in the list;
// if we hit any non-preprocessors, immediately assume
// we're done preprocessing and can move on with execution
// This is as opposed to doing something like hoisting
if (!_isFunc(part)) {
list.unshift(part);
break;
}
var name = _getFnName(part);
var lookup = inst.library.lookupPreprocessor(name);
if (!lookup) {
list.unshift(part);
break;
}
if (lookup) {
parts.push(part);
procs.push(lookup);
}
}
}
return {
list: list,
parts: parts,
procs: procs
};
}
|
javascript
|
{
"resource": ""
}
|
q10046
|
branch
|
train
|
function branch(inst, list, argv, event, fin) {
if (argv.length > 0) {
// Append the argv for programs that return
// a list that accepts them as parameters
list = list.concat(argv.splice(0));
}
// HACK HACK HACK. OK, so, when dealing with deeply recursive
// functions in Runiq, we may hit an error where we exceed the
// available call stack size. A setTimeout will get us a fresh
// call stack, but at serious perf expense, since setTimeouts
// end up triggered 4 ms later. So what I'm doing here is
// trying to call unload, and if that gives an error, then
// falling back to setTimeout method. This technique has an
// incredible benefit, speeding up Runiq programs by 50X or so.
// However, it could prove unworkable depending on browser support
// for catching call-stack errors.
try {
return unload(inst, list, argv, event, fin);
}
catch (e) {
return setTimeout(function branchCallback() {
Console.printWarning(inst, "Caught call stack error: " + e);
return unload(inst, list, argv, event, fin);
}, 0);
}
}
|
javascript
|
{
"resource": ""
}
|
q10047
|
quote
|
train
|
function quote(inst, list, argv, event, fin) {
// Remember to charge for the 'quote' function as a transaction
if (!ok(inst, inst.options.quoteTransaction)) return exit(inst, list, fin);
var entity = list[list.length - 1];
if (_isValue(entity)) return fin(null, entity);
var quotation = {};
quotation[RUNIQ_QUOTED_ENTITY_PROP_NAME] = entity;
return fin(null, quotation);
}
|
javascript
|
{
"resource": ""
}
|
q10048
|
sequence
|
train
|
function sequence(inst, elems, argv, event, fin) {
if (elems.length < 1) return fin(null, elems);
// Running a sequence also costs some amount per element to sequence
if (!ok(inst, inst.options.sequenceTransaction * elems.length)) {
return exit(inst, list, fin);
}
return parallel(inst, elems, argv, event, fin, postSequence);
}
|
javascript
|
{
"resource": ""
}
|
q10049
|
parallel
|
train
|
function parallel(inst, elems, argv, event, fin, _postSequence) {
var total = elems.length;
var complete = 0;
function check(err, list) {
if (total === ++complete) {
if (!_isFunc(list)) return _postSequence(list, fin);
return fin(err, list);
}
}
for (var i = 0; i < total; i++) {
if (_isList(elems[i])) {
var after = edit(inst, elems, i, argv, event, check);
branch(inst, elems[i], argv, event, after);
}
else {
check(null, elems);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q10050
|
postSequence
|
train
|
function postSequence(elems, fin) {
// Treat the final value of a sequence as its return value
var toReturn = elems[elems.length - 1];
return fin(null, toReturn);
}
|
javascript
|
{
"resource": ""
}
|
q10051
|
edit
|
train
|
function edit(inst, list, index, argv, event, fin) {
return function editCallback(err, data) {
if (err) return fin(err);
list[index] = data;
return fin(null, list);
};
}
|
javascript
|
{
"resource": ""
}
|
q10052
|
_valuefyArgs
|
train
|
function _valuefyArgs(args, lib) {
for (var i = 0; i < args.length; i++) {
args[i] = _entityToValue(args[i], lib);
}
}
|
javascript
|
{
"resource": ""
}
|
q10053
|
_unquoteArgs
|
train
|
function _unquoteArgs(args) {
for (var i = 0; i < args.length; i++) {
if (_isQuoted(args[i])) args[i] = _unquote(args[i]);
}
}
|
javascript
|
{
"resource": ""
}
|
q10054
|
_entityToValue
|
train
|
function _entityToValue(item, lib) {
if (typeof item === JS_STRING_TYPE) {
// Only JSON-serializable entities may be put into a list
var constant = lib.lookupConstant(item);
if (constant !== undefined) return constant;
}
// Also unquote any item we got that also happens to be a quote
if (item && item[RUNIQ_QUOTED_ENTITY_PROP_NAME]) {
return item[RUNIQ_QUOTED_ENTITY_PROP_NAME];
}
return item;
}
|
javascript
|
{
"resource": ""
}
|
q10055
|
exec
|
train
|
function exec(query, config, done) {
if(!query || (typeof query != 'string')){
throw new Error('Node-SQL: query was not in the correct format.');
return;
}
if(!config || (typeof config != 'object')){
throw new Error('Node-SQL: config was not in the correct format.');
return;
}
if(!done || (typeof done != 'function')){
done = function(a, b){};
}
var connection = new Connection(config);
connection.on('connect', function(err) {
if(err){
done(err, null);
return;
}
var request = new Request(query, function(_err) {
if (_err) {
done(_err, null);
return;
}
connection.close();
});
var result = [];
request.on('row', function(columns) {
var row = {};
columns.forEach(function(column) {
row[column.metadata.colName] = column.value;
});
result.push(row);
});
request.on('doneProc', function(rowCount, more, returnStatus) {
if(returnStatus == 0) done(null, result);
});
connection.execSql(request);
});
}
|
javascript
|
{
"resource": ""
}
|
q10056
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Person)){
return new Person(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Person.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q10057
|
train
|
function (str, n) {
n = window.parseInt(n, 10);
return new Array(n + 1).join(str);
}
|
javascript
|
{
"resource": ""
}
|
|
q10058
|
train
|
function(callback){
ubeacon.setEddystoneURL( program.url , function(data, error){
console.log('Set URL to', data );
callback(error);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q10059
|
train
|
function () {
return new Promise((resolve, reject) => {
var startTime = Date.now();
var size = fs.statSync(dataFile).size;
var next = (readInfo, position) => {
var jobs = [readNextChunk(readInfo)];
if (position) {
jobs.push(readAndIndex(position, readInfo.readBuffer));
debug(position);
}
Q.all(jobs).then(results => {
var nextReadInfo = results[0];
var nextPosition = results[1] || {};
readInfo.readBuffer = null;
if (nextReadInfo.done && position) {
debug("indexSize size: %s", (indexSize / 1024) + "KB");
debug("index ready (took %s secs)", (Date.now() - startTime) / 1000);
meta.size = indexSize;
debug(meta);
resolve();
} else {
next(nextReadInfo, nextPosition);
}
}).catch(err => reject(err));
};
debug("creating index");
next({ size: size, fd: openDataFile() });
});
}
|
javascript
|
{
"resource": ""
}
|
|
q10060
|
train
|
function (indexName, key) {
return new Promise((resolve, reject) => {
if (index[indexName]) {
resolve(index[indexName][key] || null);
} else {
debug("opening index %s", indexName);
storage.openIndex(indexName).then(index => {
index[indexName] = index;
resolve(index[indexName][key] || null);
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q10061
|
train
|
function (id) {
return typeof id === 'number' ?
clear(id) :
void(
drop(qframe, id) ||
drop(qidle, id) ||
drop(qframex, id) ||
drop(qidlex, id)
);
}
|
javascript
|
{
"resource": ""
}
|
|
q10062
|
animationLoop
|
train
|
function animationLoop() {
var
// grab current time
t = time(),
// calculate how many millisends we have
fps = 1000 / next.minFPS,
// used to flag overtime in case we exceed milliseconds
overTime = false,
// take current frame queue length
length = getLength(qframe, qframex)
;
// if there is actually something to do
if (length) {
// reschedule upfront next animation frame
// this prevents the need for a try/catch within the while loop
requestAnimationFrame(animationLoop);
// reassign qframex cleaning current animation frame queue
qframex = qframe.splice(0, length);
while (qframex.length) {
// if some of them fails, it's OK
// next round will re-prioritize the animation frame queue
exec(qframex.shift());
// if we exceeded the frame time, get out this loop
overTime = (time() - t) >= fps;
if ((next.isOverloaded = overTime)) break;
}
// if overtime and debug is true, warn about it
if (overTime && next.debug) console.warn('overloaded frame');
} else {
// all frame callbacks have been executed
// we can actually stop asking for animation frames
frameRunning = false;
// and flag it as non busy/overloaded anymore
next.isOverloaded = frameRunning;
}
}
|
javascript
|
{
"resource": ""
}
|
q10063
|
create
|
train
|
function create(callback) {
/* jslint validthis: true */
for (var
queue = this,
args = [],
info = {
id: {},
fn: callback,
ar: args
},
i = 1; i < arguments.length; i++
) args[i - 1] = arguments[i];
return infoId(queue, info) || (queue.push(info), info.id);
}
|
javascript
|
{
"resource": ""
}
|
q10064
|
drop
|
train
|
function drop(queue, id) {
var
i = findIndex(queue, id),
found = -1 < i
;
if (found) queue.splice(i, 1);
return found;
}
|
javascript
|
{
"resource": ""
}
|
q10065
|
findIndex
|
train
|
function findIndex(queue, id) {
var i = queue.length;
while (i-- && queue[i].id !== id);
return i;
}
|
javascript
|
{
"resource": ""
}
|
q10066
|
getLength
|
train
|
function getLength(queue, queuex) {
// if previous call didn't execute all callbacks
return queuex.length ?
// reprioritize the queue putting those in front
queue.unshift.apply(queue, queuex) :
queue.length;
}
|
javascript
|
{
"resource": ""
}
|
q10067
|
idleLoop
|
train
|
function idleLoop(deadline) {
var
length = getLength(qidle, qidlex),
didTimeout = deadline.didTimeout
;
if (length) {
// reschedule upfront next idle callback
requestIdleCallback(idleLoop, {timeout: next.maxIdle});
// this prevents the need for a try/catch within the while loop
// reassign qidlex cleaning current idle queue
qidlex = qidle.splice(0, didTimeout ? 1 : length);
while (qidlex.length && (didTimeout || deadline.timeRemaining()))
exec(qidlex.shift());
} else {
// all idle callbacks have been executed
// we can actually stop asking for idle operations
idleRunning = false;
}
}
|
javascript
|
{
"resource": ""
}
|
q10068
|
infoId
|
train
|
function infoId(queue, info) {
for (var i = 0, length = queue.length, tmp; i < length; i++) {
tmp = queue[i];
if (
tmp.fn === info.fn &&
sameValues(tmp.ar, info.ar)
) return tmp.id;
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q10069
|
sameValues
|
train
|
function sameValues(a, b) {
var
i = a.length,
j = b.length,
k = i === j
;
if (k) {
while (i--) {
if (a[i] !== b[i]) {
return !k;
}
}
}
return k;
}
|
javascript
|
{
"resource": ""
}
|
q10070
|
asPath
|
train
|
function asPath({ ancestors }) {
const path = [];
for (const { key } of ancestors) {
if (key != null) {
if (typeof key === 'number') {
path.push(`[${key}]`);
} else {
path.push(`['${stringify(key).slice(1, -1)}']`);
}
}
}
return path.join('');
}
|
javascript
|
{
"resource": ""
}
|
q10071
|
Identity
|
train
|
function Identity(category, type, name) {
Element.call(this, 'identity', 'http://jabber.org/protocol/disco#info');
this.category = category;
this.type = type;
this.displayName = name;
}
|
javascript
|
{
"resource": ""
}
|
q10072
|
Exception
|
train
|
function Exception(err, options) {
if (!(this instanceof Exception)) return new Exception(err, options);
if ('string' === typeof err) err = {
stack: (new Error(err)).stack,
message: err
};
debug('generating a new exception for: %s', err.message);
options = options || {};
this.initialize(options);
this.message = err.message || 'An unknown Exception has occurred';
this.timeout = options.timeout || 10000;
this.stack = err.stack || '';
this.human = !!options.human;
this.filename = new Date().toDateString().split(' ').concat([
this.appname, // Name of the library or app that included us.
process.pid, // The current process id
this.id // Unique id for this exception.
]).filter(Boolean).join('-');
this.capture = this.toJSON();
}
|
javascript
|
{
"resource": ""
}
|
q10073
|
bytes
|
train
|
function bytes(b) {
if (!readable) return b;
var tb = ((1 << 30) * 1024)
, gb = 1 << 30
, mb = 1 << 20
, kb = 1 << 10
, abs = Math.abs(b);
if (abs >= tb) return (Math.round(b / tb * 100) / 100) + 'tb';
if (abs >= gb) return (Math.round(b / gb * 100) / 100) + 'gb';
if (abs >= mb) return (Math.round(b / mb * 100) / 100) + 'mb';
if (abs >= kb) return (Math.round(b / kb * 100) / 100) + 'kb';
return b + 'b';
}
|
javascript
|
{
"resource": ""
}
|
q10074
|
readBytes
|
train
|
async function readBytes ({ file, start, chunkSize }) {
const buffer = Buffer.alloc(chunkSize)
const fileDescriptor = await fs.open(file, 'r')
const { bytesRead } = await fs.read(
fileDescriptor,
buffer, // buffer to write to
0, // offset in the buffer to start writing at
chunkSize, // number of bytes to read
start // where to begin reading from in the file
)
// Slice the buffer in case chunkSize > fileSize - start
return buffer.slice(0, bytesRead)
}
|
javascript
|
{
"resource": ""
}
|
q10075
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof AtomGenerator)){
return new AtomGenerator(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(AtomGenerator.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q10076
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Relationship)){
return new Relationship(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Relationship.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q10077
|
LocalStorage
|
train
|
function LocalStorage (opts) {
if (!isLocalStorageSupported()) {
console.warn('localStorage not supported! (data will be stored in memory)')
}
var self = this
Storage.call(self, opts)
opts = _.extend({
keyName: 'blockchainjs_' + self.networkName
}, opts)
if (!this.compactMode) {
throw new errors.Storage.FullMode.NotSupported()
}
self._storage = getStorage()
self._keyName = opts.keyName
// load this._data
Promise.try(function () {
self._init()
self._save()
})
.then(function () { self.emit('ready') })
.catch(function (err) { self.emit('error', err) })
}
|
javascript
|
{
"resource": ""
}
|
q10078
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Links)){
return new Links(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Links.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q10079
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof PlaceDisplayProperties)){
return new PlaceDisplayProperties(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(PlaceDisplayProperties.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q10080
|
getDepartures
|
train
|
function getDepartures (fromStationId, toStationId, fromTime, toTime) {
fromTime = fromTime || '-00:30:00'
toTime = toTime || '03:00:00'
let optionalFilters = ''
if (toStationId) {
optionalFilters += '<OR>' +
`<EQ name="ViaToLocation.LocationName" value="${toStationId}"/>` +
`<EQ name="ToLocation.LocationName" value="${toStationId}"/>` +
'</OR>'
}
let xmlRequest = fs.readFileSync(xmlRequestFile)
.toString()
.replace('{apikey}', env.apiKey)
.replace('{fromStationId}', fromStationId)
.replace('{optionalFilters}', optionalFilters)
.replace('{fromTime}', fromTime)
.replace('{toTime}', toTime)
return new Promise(function (resolve, reject) {
request(
{method: 'POST', url: env.url, body: xmlRequest},
function (err, response, body) {
if (err) {
return reject(err)
}
let bodyObj = JSON.parse(body)
let departures = handleDeparturesResponse(bodyObj)
resolve(deduplicateDepartures(departures))
}
)
}).then(function (departures) {
let stationIds = getStationIdsFromDepartures(departures)
return trainStationService.getTrainStationsInfo(stationIds)
.then(function (stationsInfo) {
return replaceStationIdsForNamesInDepartures(departures, stationsInfo)
})
})
}
|
javascript
|
{
"resource": ""
}
|
q10081
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Gender)){
return new Gender(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Gender.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q10082
|
on
|
train
|
function on(first, operator, second) {
var data,
bool = this._bool();
switch (arguments.length) {
case 1:
{
if (typeof first === 'object' && typeof first.toSQL !== 'function') {
var i = -1,
keys = Object.keys(first);
var method = bool === 'or' ? 'orOn' : 'on';
while (++i < keys.length) {
this[method](keys[i], first[keys[i]]);
}
return this;
} else {
data = [bool, 'on', first];
}
break;
}
case 2:
data = [bool, 'on', first, '=', operator];
break;
default:
data = [bool, 'on', first, operator, second];
}
this.clauses.push(data);
return this;
}
|
javascript
|
{
"resource": ""
}
|
q10083
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof RecordDescriptor)){
return new RecordDescriptor(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(RecordDescriptor.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q10084
|
emitData
|
train
|
function emitData() {
for(var i=0;i<streamQueue.length;i++) {
var dataQueue = streamQueue[i].dataQueue;
if(streamQueue[i].pending) {
return;
}
for(var j=0;j<dataQueue.length;j++) {
var data = dataQueue[j];
if(!!data) {
_this.emit('data', data);
dataQueue[j] = null;
return emitData();
}
}
}
if(currentStream === streamQueue.length) {
_this.emit('end');
}
}
|
javascript
|
{
"resource": ""
}
|
q10085
|
store
|
train
|
function store (action) {
if (!action || !isPlainObject(action)) {
throw new Error('action parameter is required and must be a plain object')
}
if (!action.type || typeof action.type !== 'string') {
throw new Error('type property of action is required and must be a string')
}
if (isEmitting) {
throw new Error('modifiers may not emit actions')
}
isEmitting = true
var oldState = extend(state)
state = modifier(action, oldState)
var newState = extend(state)
emitter.emit(action.type, action, newState, oldState)
isEmitting = false
}
|
javascript
|
{
"resource": ""
}
|
q10086
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Qualifier)){
return new Qualifier(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Qualifier.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q10087
|
hasRemoteMethod
|
train
|
function hasRemoteMethod(model, methodName) {
return model.sharedClass
.methods({ includeDisabled: false })
.map(sharedMethod => sharedMethod.name)
.includes(methodName)
}
|
javascript
|
{
"resource": ""
}
|
q10088
|
addRemoteMethods
|
train
|
function addRemoteMethods(app) {
return Object.keys(app.models).forEach(modelName => {
const Model = app.models[modelName]
if (typeof Model._templates !== 'function') {
return null
}
return Object.keys(Model._templates()).forEach(templateName => {
const fnName = `_template_${templateName}`
const fnNameRemote = `_template_${templateName}_remote`
const path = `/${fnName}`
// Don't add the method if it already exists on the model
if (typeof Model[fnName] === 'function') {
debug('Method already exists: %s.%s', Model.modelName, fnName)
return null
}
// Don't add the remote method if it already exists on the model
if (hasRemoteMethod(Model, fnNameRemote)) {
debug('Remote method already exists: %s.%s', Model.modelName, fnName)
return null
}
debug('Create remote method for %s.%s', Model.modelName, fnName)
// The normal method does not need to be wrapped in a promise
Model[fnName] = (options, params) => {
// Get the random data
const template = Model._templates(params)[templateName]
// Overwrite the template with the passed in options
_.forEach(options, (value, key) => {
_.set(template, key, value)
})
return template
}
const fnSpecRemote = {
description: `Generate template ${templateName}`,
accepts: [
{ type: 'Object', arg: 'options', description: 'Overwrite values of template' },
{ type: 'Object', arg: 'params', description: 'Pass parameters into the template method' },
],
returns: [ { type: 'Object', arg: 'result', root: true } ],
http: { path, verb: 'get' },
}
// Support for loopback 2.x.
if (app.loopback.version.startsWith(2)) {
fnSpecRemote.isStatic = true
}
// Define the remote method on the model
Model.remoteMethod(fnNameRemote, fnSpecRemote)
// The remote method needs to be wrapped in a promise
Model[fnNameRemote] = (options, params) => new Promise(resolve => resolve(Model[fnName](options, params)))
// Send result as plain text if the content is a string
Model.afterRemote(fnNameRemote, (ctx, result, next) => {
if (typeof ctx.result !== 'string') {
return next()
}
ctx.res.setHeader('Content-Type', 'text/plain')
return ctx.res.end(ctx.result)
})
return true
})
})
}
|
javascript
|
{
"resource": ""
}
|
q10089
|
addAcls
|
train
|
function addAcls(app, config) {
config.acls = config.acls || []
return Promise.resolve(Object.keys(app.models)).mapSeries(modelName => {
const Model = app.models[modelName]
if (typeof Model._templates !== 'function') {
return null
}
return Promise.resolve(Object.keys(Model._templates()))
.mapSeries(templateName => {
const fnNameRemote = `_template_${templateName}_remote`
return Promise.resolve(config.acls).mapSeries(acl => {
const templateAcl = Object.assign({}, acl)
templateAcl.model = modelName
templateAcl.property = fnNameRemote
debug('Create ACL entry for %s.%s ', modelName, fnNameRemote)
return app.models.ACL.create(templateAcl)
})
})
})
}
|
javascript
|
{
"resource": ""
}
|
q10090
|
match
|
train
|
function match(routes = [], path) {
for (var i = 0; i < routes.length; i++) {
var re = pathRegexps[routes[i].path] || pathToRegexp(routes[i].path);
pathRegexps[routes[i].path] = re;
if (re && re.test(path)) {
return { re, route: routes[i] };
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q10091
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof DisplayProperties)){
return new DisplayProperties(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(DisplayProperties.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q10092
|
train
|
function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof AtomEntry)){
return new AtomEntry(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(AtomEntry.isInstance(json)){
return json;
}
this.init(json);
}
|
javascript
|
{
"resource": ""
}
|
|
q10093
|
Dispatcher
|
train
|
function Dispatcher() {
let lastId = 1;
let prefix = "ID_";
let callbacks = {};
let isPending = {};
let isHandled = {};
let isDispatching = false;
let pendingPayload = null;
function invokeCallback(id) {
isPending[id] = true;
callbacks[id](pendingPayload);
isHandled[id] = true;
}
this.register = callback => {
let id = prefix + lastId++;
callbacks[id] = callback;
return id;
};
this.unregister = id => {
if (!callbacks.hasOwnProperty(id))
return new Error("Cannot unregister unknown ID!");
delete callbacks[id];
return id;
};
this.waitFor = ids => {
for (var i = 0; i < ids.length; i++) {
var id = ids[id];
if (isPending[id]) {
return new Error("Circular dependency waiting for " + id);
}
if (!callbacks[id]) {
return new Error(`waitFor: ${id} is not a registered callback.`);
}
invokeCallback(id);
}
return undefined;
};
this.dispatch = payload => {
if (isDispatching) return new Error("Cannot dispatch while dispatching.");
// start
for (var id in callbacks) {
isPending[id] = false;
isHandled[id] = false;
}
pendingPayload = payload;
isDispatching = true;
// run each callback.
try {
for (var id in callbacks) {
if (isPending[id]) continue;
invokeCallback(id);
}
} finally {
pendingPayload = null;
isDispatching = false;
}
return payload;
};
}
|
javascript
|
{
"resource": ""
}
|
q10094
|
train
|
function () {
if (sequence) {
var localNodes = sequence.nodes;
var localIndex = (localNodes) ? localNodes.indexOf(node) : null;
if (localNodes) {
if (localIndex === (localNodes.length - 1)) {
return sequence.sequences || [];
} else {
return [];
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q10095
|
train
|
function (variation) {
variation = variation || 0;
var localNodes = sequence.nodes;
var localIndex = (localNodes) ? localNodes.indexOf(node) : null;
// If there are no additional nodes in this sequence,
// advance to the next one
if (localIndex === null || localIndex >= (localNodes.length - 1)) {
if (sequence.sequences) {
if (sequence.sequences[variation]) {
sequence = sequence.sequences[variation];
} else {
sequence = sequence.sequences[0];
}
node = sequence.nodes[0];
// Note the fork chosen for this variation in the path
this.path[this.path.m] = variation;
this.path.m += 1;
} else {
// End of sequence / game
return this;
}
} else {
node = localNodes[localIndex + 1];
this.path.m += 1;
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q10096
|
train
|
function () {
var localNodes = sequence.nodes;
var localIndex = (localNodes) ? localNodes.indexOf(node) : null;
// Delete any variation forks at this point
// TODO: Make this configurable... we should keep this if we're
// remembering chosen paths
delete this.path[this.path.m];
if (!localIndex || localIndex === 0) {
if (sequence.parent && !sequence.parent.gameTrees) {
sequence = sequence.parent;
if (sequence.nodes) {
node = sequence.nodes[sequence.nodes.length - 1];
this.path.m -= 1;
} else {
node = null;
}
} else {
// Already at the beginning
return this;
}
} else {
node = localNodes[localIndex - 1];
this.path.m -= 1;
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q10097
|
train
|
function (path) {
if (typeof path === 'string') {
path = this.pathTransform(path, 'object');
} else if (typeof path === 'number') {
path = { m: path };
}
this.reset();
var n = node;
for (var i = 0; i < path.m && n; i += 1) {
// Check for a variation in the path for the upcoming move
var variation = path[i + 1] || 0;
n = this.next(variation);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q10098
|
train
|
function () {
var localSequence = this.game;
var moves = 0;
while(localSequence) {
moves += localSequence.nodes.length;
if (localSequence.sequences) {
localSequence = localSequence.sequences[0];
} else {
localSequence = null;
}
}
// TODO: Right now we're *assuming* that the root node doesn't have a
// move in it, which is *recommended* but not required practice.
// @see http://www.red-bean.com/sgf/sgf4.html
// "Note: it's bad style to have move properties in root nodes.
// (it isn't forbidden though)"
return moves - 1;
}
|
javascript
|
{
"resource": ""
}
|
|
q10099
|
train
|
function (text) {
if (typeof text === 'undefined') {
// Unescape characters
if (node.C) {
return node.C.replace(/\\([\\:\]])/g, '$1');
} else {
return '';
}
} else {
// Escape characters
node.C = text.replace(/[\\:\]]/g, '\\$&');
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.