id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
41,800 | chip-js/observations-js | src/observable-hash.js | ObservableHash | function ObservableHash(observations) {
var enabled = true;
var _observers = [];
_observers.enabled = true;
Object.defineProperties(this, {
_context: { writable: true, value: this },
_observations: { value: observations },
_namespaces: { value: [] },
_observers: { value: _observers },
computedObservers: { value: _observers } // alias to work with the computed system
});
} | javascript | function ObservableHash(observations) {
var enabled = true;
var _observers = [];
_observers.enabled = true;
Object.defineProperties(this, {
_context: { writable: true, value: this },
_observations: { value: observations },
_namespaces: { value: [] },
_observers: { value: _observers },
computedObservers: { value: _observers } // alias to work with the computed system
});
} | [
"function",
"ObservableHash",
"(",
"observations",
")",
"{",
"var",
"enabled",
"=",
"true",
";",
"var",
"_observers",
"=",
"[",
"]",
";",
"_observers",
".",
"enabled",
"=",
"true",
";",
"Object",
".",
"defineProperties",
"(",
"this",
",",
"{",
"_context",
":",
"{",
"writable",
":",
"true",
",",
"value",
":",
"this",
"}",
",",
"_observations",
":",
"{",
"value",
":",
"observations",
"}",
",",
"_namespaces",
":",
"{",
"value",
":",
"[",
"]",
"}",
",",
"_observers",
":",
"{",
"value",
":",
"_observers",
"}",
",",
"computedObservers",
":",
"{",
"value",
":",
"_observers",
"}",
"// alias to work with the computed system",
"}",
")",
";",
"}"
]
| An object for storing data to be accessed by an application. Has methods for easily computing and watching data
changes.
@param {Observations} observations An instance of the Observations class this has is bound to | [
"An",
"object",
"for",
"storing",
"data",
"to",
"be",
"accessed",
"by",
"an",
"application",
".",
"Has",
"methods",
"for",
"easily",
"computing",
"and",
"watching",
"data",
"changes",
"."
]
| a48b32a648089bc86b502712d78cd0b3f8317d50 | https://github.com/chip-js/observations-js/blob/a48b32a648089bc86b502712d78cd0b3f8317d50/src/observable-hash.js#L10-L22 |
41,801 | chip-js/observations-js | src/observable-hash.js | function() {
this._observers.enabled = true;
this._observers.forEach(this.observersBindHelper.bind(this), this);
// Set namespaced hashes to the same value
this._namespaces.forEach(this.observersStartHelper.bind(this), this);
} | javascript | function() {
this._observers.enabled = true;
this._observers.forEach(this.observersBindHelper.bind(this), this);
// Set namespaced hashes to the same value
this._namespaces.forEach(this.observersStartHelper.bind(this), this);
} | [
"function",
"(",
")",
"{",
"this",
".",
"_observers",
".",
"enabled",
"=",
"true",
";",
"this",
".",
"_observers",
".",
"forEach",
"(",
"this",
".",
"observersBindHelper",
".",
"bind",
"(",
"this",
")",
",",
"this",
")",
";",
"// Set namespaced hashes to the same value",
"this",
".",
"_namespaces",
".",
"forEach",
"(",
"this",
".",
"observersStartHelper",
".",
"bind",
"(",
"this",
")",
",",
"this",
")",
";",
"}"
]
| Starts the observers watching their values | [
"Starts",
"the",
"observers",
"watching",
"their",
"values"
]
| a48b32a648089bc86b502712d78cd0b3f8317d50 | https://github.com/chip-js/observations-js/blob/a48b32a648089bc86b502712d78cd0b3f8317d50/src/observable-hash.js#L43-L49 |
|
41,802 | chip-js/observations-js | src/observable-hash.js | function(clearValues) {
this._observers.enabled = false;
this._observers.forEach(this.observersUnbindHelper.bind(this, clearValues));
// Set namespaced hashes to the same value
this._namespaces.forEach(this.observersStopHelper.bind(this, clearValues), this);
} | javascript | function(clearValues) {
this._observers.enabled = false;
this._observers.forEach(this.observersUnbindHelper.bind(this, clearValues));
// Set namespaced hashes to the same value
this._namespaces.forEach(this.observersStopHelper.bind(this, clearValues), this);
} | [
"function",
"(",
"clearValues",
")",
"{",
"this",
".",
"_observers",
".",
"enabled",
"=",
"false",
";",
"this",
".",
"_observers",
".",
"forEach",
"(",
"this",
".",
"observersUnbindHelper",
".",
"bind",
"(",
"this",
",",
"clearValues",
")",
")",
";",
"// Set namespaced hashes to the same value",
"this",
".",
"_namespaces",
".",
"forEach",
"(",
"this",
".",
"observersStopHelper",
".",
"bind",
"(",
"this",
",",
"clearValues",
")",
",",
"this",
")",
";",
"}"
]
| Stops the observers watching and responding to changes, optionally clearing out the values
@param {Boolean} clearValues Whether to clear the values out to `undefined` or leave them as-is | [
"Stops",
"the",
"observers",
"watching",
"and",
"responding",
"to",
"changes",
"optionally",
"clearing",
"out",
"the",
"values"
]
| a48b32a648089bc86b502712d78cd0b3f8317d50 | https://github.com/chip-js/observations-js/blob/a48b32a648089bc86b502712d78cd0b3f8317d50/src/observable-hash.js#L63-L69 |
|
41,803 | chip-js/observations-js | src/observable-hash.js | function(namespace, map) {
if (typeof namespace === 'string' && typeof map === 'object') {
if (!this[namespace]) {
this[namespace] = new ObservableHash(this._observations);
this[namespace].observersEnabled = this.observersEnabled;
this._namespaces.push(namespace);
}
this._observations.computed.extend(this[namespace], map, { context: this[namespace]._context });
return this[namespace];
} else if (namespace && typeof namespace === 'object') {
this._observations.computed.extend(this, namespace, { context: this._context });
return this;
} else {
throw new TypeError('addComputed must have a map object');
}
} | javascript | function(namespace, map) {
if (typeof namespace === 'string' && typeof map === 'object') {
if (!this[namespace]) {
this[namespace] = new ObservableHash(this._observations);
this[namespace].observersEnabled = this.observersEnabled;
this._namespaces.push(namespace);
}
this._observations.computed.extend(this[namespace], map, { context: this[namespace]._context });
return this[namespace];
} else if (namespace && typeof namespace === 'object') {
this._observations.computed.extend(this, namespace, { context: this._context });
return this;
} else {
throw new TypeError('addComputed must have a map object');
}
} | [
"function",
"(",
"namespace",
",",
"map",
")",
"{",
"if",
"(",
"typeof",
"namespace",
"===",
"'string'",
"&&",
"typeof",
"map",
"===",
"'object'",
")",
"{",
"if",
"(",
"!",
"this",
"[",
"namespace",
"]",
")",
"{",
"this",
"[",
"namespace",
"]",
"=",
"new",
"ObservableHash",
"(",
"this",
".",
"_observations",
")",
";",
"this",
"[",
"namespace",
"]",
".",
"observersEnabled",
"=",
"this",
".",
"observersEnabled",
";",
"this",
".",
"_namespaces",
".",
"push",
"(",
"namespace",
")",
";",
"}",
"this",
".",
"_observations",
".",
"computed",
".",
"extend",
"(",
"this",
"[",
"namespace",
"]",
",",
"map",
",",
"{",
"context",
":",
"this",
"[",
"namespace",
"]",
".",
"_context",
"}",
")",
";",
"return",
"this",
"[",
"namespace",
"]",
";",
"}",
"else",
"if",
"(",
"namespace",
"&&",
"typeof",
"namespace",
"===",
"'object'",
")",
"{",
"this",
".",
"_observations",
".",
"computed",
".",
"extend",
"(",
"this",
",",
"namespace",
",",
"{",
"context",
":",
"this",
".",
"_context",
"}",
")",
";",
"return",
"this",
";",
"}",
"else",
"{",
"throw",
"new",
"TypeError",
"(",
"'addComputed must have a map object'",
")",
";",
"}",
"}"
]
| Add computed properties to this hash. If `name` is provided it will add the computed properties to that namespace
on the hash. Otherwise they will be added directly to the hash.
@param {String} name [OPTIONAL] The namespace to add the computed properties under
@param {Object} map The map of computed properties that will be set on this ObservableHash | [
"Add",
"computed",
"properties",
"to",
"this",
"hash",
".",
"If",
"name",
"is",
"provided",
"it",
"will",
"add",
"the",
"computed",
"properties",
"to",
"that",
"namespace",
"on",
"the",
"hash",
".",
"Otherwise",
"they",
"will",
"be",
"added",
"directly",
"to",
"the",
"hash",
"."
]
| a48b32a648089bc86b502712d78cd0b3f8317d50 | https://github.com/chip-js/observations-js/blob/a48b32a648089bc86b502712d78cd0b3f8317d50/src/observable-hash.js#L104-L119 |
|
41,804 | chip-js/observations-js | src/observable-hash.js | function(expression, onChange, callbackContext) {
var observer = this._observations.createObserver(expression, onChange, callbackContext || this);
this._observers.push(observer);
if (this.observersEnabled) observer.bind(this._context);
return observer;
} | javascript | function(expression, onChange, callbackContext) {
var observer = this._observations.createObserver(expression, onChange, callbackContext || this);
this._observers.push(observer);
if (this.observersEnabled) observer.bind(this._context);
return observer;
} | [
"function",
"(",
"expression",
",",
"onChange",
",",
"callbackContext",
")",
"{",
"var",
"observer",
"=",
"this",
".",
"_observations",
".",
"createObserver",
"(",
"expression",
",",
"onChange",
",",
"callbackContext",
"||",
"this",
")",
";",
"this",
".",
"_observers",
".",
"push",
"(",
"observer",
")",
";",
"if",
"(",
"this",
".",
"observersEnabled",
")",
"observer",
".",
"bind",
"(",
"this",
".",
"_context",
")",
";",
"return",
"observer",
";",
"}"
]
| Watch this object for changes in the value of the expression
@param {String} expression The expression to observe
@param {Function} onChange The function which will be called when the expression value changes
@return {Observer} The observer created | [
"Watch",
"this",
"object",
"for",
"changes",
"in",
"the",
"value",
"of",
"the",
"expression"
]
| a48b32a648089bc86b502712d78cd0b3f8317d50 | https://github.com/chip-js/observations-js/blob/a48b32a648089bc86b502712d78cd0b3f8317d50/src/observable-hash.js#L127-L132 |
|
41,805 | derdesign/multi | lib/multi.js | resultsCallback | function resultsCallback() {
var args = slice.call(arguments, 0);
var err = args.shift();
if (err) {
if (config.interrupt === true) {
errors.push(err);
results.push(null);
callback.call(self, errors, results);
return;
} else {
errored = true;
args = null;
}
} else if (args.length === 0) {
args = 'OK';
} else if (args.length == 1) {
args = args[0];
}
errors.push(err);
results.push(args);
self.emit('each', err, counter, args);
if (config.parallel) {
// Parallel
if (++counter == stack.length) {
self.promise.emit('finished');
}
} else {
// Sequential
if (++counter == stack.length) {
var preparedArgs = setInitialState(true); // Reset state, then return
self.emit('post_exec');
callback.apply(self, preparedArgs);
} else {
var next = stack[counter];
context[next.caller].apply(context, next.args);
}
}
} | javascript | function resultsCallback() {
var args = slice.call(arguments, 0);
var err = args.shift();
if (err) {
if (config.interrupt === true) {
errors.push(err);
results.push(null);
callback.call(self, errors, results);
return;
} else {
errored = true;
args = null;
}
} else if (args.length === 0) {
args = 'OK';
} else if (args.length == 1) {
args = args[0];
}
errors.push(err);
results.push(args);
self.emit('each', err, counter, args);
if (config.parallel) {
// Parallel
if (++counter == stack.length) {
self.promise.emit('finished');
}
} else {
// Sequential
if (++counter == stack.length) {
var preparedArgs = setInitialState(true); // Reset state, then return
self.emit('post_exec');
callback.apply(self, preparedArgs);
} else {
var next = stack[counter];
context[next.caller].apply(context, next.args);
}
}
} | [
"function",
"resultsCallback",
"(",
")",
"{",
"var",
"args",
"=",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
";",
"var",
"err",
"=",
"args",
".",
"shift",
"(",
")",
";",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"config",
".",
"interrupt",
"===",
"true",
")",
"{",
"errors",
".",
"push",
"(",
"err",
")",
";",
"results",
".",
"push",
"(",
"null",
")",
";",
"callback",
".",
"call",
"(",
"self",
",",
"errors",
",",
"results",
")",
";",
"return",
";",
"}",
"else",
"{",
"errored",
"=",
"true",
";",
"args",
"=",
"null",
";",
"}",
"}",
"else",
"if",
"(",
"args",
".",
"length",
"===",
"0",
")",
"{",
"args",
"=",
"'OK'",
";",
"}",
"else",
"if",
"(",
"args",
".",
"length",
"==",
"1",
")",
"{",
"args",
"=",
"args",
"[",
"0",
"]",
";",
"}",
"errors",
".",
"push",
"(",
"err",
")",
";",
"results",
".",
"push",
"(",
"args",
")",
";",
"self",
".",
"emit",
"(",
"'each'",
",",
"err",
",",
"counter",
",",
"args",
")",
";",
"if",
"(",
"config",
".",
"parallel",
")",
"{",
"// Parallel",
"if",
"(",
"++",
"counter",
"==",
"stack",
".",
"length",
")",
"{",
"self",
".",
"promise",
".",
"emit",
"(",
"'finished'",
")",
";",
"}",
"}",
"else",
"{",
"// Sequential",
"if",
"(",
"++",
"counter",
"==",
"stack",
".",
"length",
")",
"{",
"var",
"preparedArgs",
"=",
"setInitialState",
"(",
"true",
")",
";",
"// Reset state, then return",
"self",
".",
"emit",
"(",
"'post_exec'",
")",
";",
"callback",
".",
"apply",
"(",
"self",
",",
"preparedArgs",
")",
";",
"}",
"else",
"{",
"var",
"next",
"=",
"stack",
"[",
"counter",
"]",
";",
"context",
"[",
"next",
".",
"caller",
"]",
".",
"apply",
"(",
"context",
",",
"next",
".",
"args",
")",
";",
"}",
"}",
"}"
]
| Handles the internal async execution loop in order | [
"Handles",
"the",
"internal",
"async",
"execution",
"loop",
"in",
"order"
]
| ea8e3b4c07eae5a65354c09a3850e60461ce4bc4 | https://github.com/derdesign/multi/blob/ea8e3b4c07eae5a65354c09a3850e60461ce4bc4/lib/multi.js#L84-L133 |
41,806 | derdesign/multi | lib/multi.js | queue | function queue(args) {
args.push(resultsCallback);
stack.push({caller: this.caller, args: args});
} | javascript | function queue(args) {
args.push(resultsCallback);
stack.push({caller: this.caller, args: args});
} | [
"function",
"queue",
"(",
"args",
")",
"{",
"args",
".",
"push",
"(",
"resultsCallback",
")",
";",
"stack",
".",
"push",
"(",
"{",
"caller",
":",
"this",
".",
"caller",
",",
"args",
":",
"args",
"}",
")",
";",
"}"
]
| Queues the callback | [
"Queues",
"the",
"callback"
]
| ea8e3b4c07eae5a65354c09a3850e60461ce4bc4 | https://github.com/derdesign/multi/blob/ea8e3b4c07eae5a65354c09a3850e60461ce4bc4/lib/multi.js#L137-L140 |
41,807 | derdesign/multi | lib/multi.js | dummy | function dummy(caller) {
return function() {
queue.call({caller: caller}, slice.call(arguments, 0));
return self;
}
} | javascript | function dummy(caller) {
return function() {
queue.call({caller: caller}, slice.call(arguments, 0));
return self;
}
} | [
"function",
"dummy",
"(",
"caller",
")",
"{",
"return",
"function",
"(",
")",
"{",
"queue",
".",
"call",
"(",
"{",
"caller",
":",
"caller",
"}",
",",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
")",
";",
"return",
"self",
";",
"}",
"}"
]
| Generates the queuing function | [
"Generates",
"the",
"queuing",
"function"
]
| ea8e3b4c07eae5a65354c09a3850e60461ce4bc4 | https://github.com/derdesign/multi/blob/ea8e3b4c07eae5a65354c09a3850e60461ce4bc4/lib/multi.js#L144-L149 |
41,808 | derdesign/multi | lib/multi.js | setInitialState | function setInitialState(ret) {
var e, r;
// Before resetting, keep a copy of args
if (ret) {
e = (errored ? errors : null);
r = results;
}
// Reset runtime vars to their default state
counter = 0;
errored = false;
errors = [];
results = [];
// Flush stack on first run or when config.flush is true
if (stack == null || config.flush) stack = [];
// Return prepared arguments
if (ret) return [e, r];
} | javascript | function setInitialState(ret) {
var e, r;
// Before resetting, keep a copy of args
if (ret) {
e = (errored ? errors : null);
r = results;
}
// Reset runtime vars to their default state
counter = 0;
errored = false;
errors = [];
results = [];
// Flush stack on first run or when config.flush is true
if (stack == null || config.flush) stack = [];
// Return prepared arguments
if (ret) return [e, r];
} | [
"function",
"setInitialState",
"(",
"ret",
")",
"{",
"var",
"e",
",",
"r",
";",
"// Before resetting, keep a copy of args",
"if",
"(",
"ret",
")",
"{",
"e",
"=",
"(",
"errored",
"?",
"errors",
":",
"null",
")",
";",
"r",
"=",
"results",
";",
"}",
"// Reset runtime vars to their default state",
"counter",
"=",
"0",
";",
"errored",
"=",
"false",
";",
"errors",
"=",
"[",
"]",
";",
"results",
"=",
"[",
"]",
";",
"// Flush stack on first run or when config.flush is true",
"if",
"(",
"stack",
"==",
"null",
"||",
"config",
".",
"flush",
")",
"stack",
"=",
"[",
"]",
";",
"// Return prepared arguments",
"if",
"(",
"ret",
")",
"return",
"[",
"e",
",",
"r",
"]",
";",
"}"
]
| Sets the initial state of multi | [
"Sets",
"the",
"initial",
"state",
"of",
"multi"
]
| ea8e3b4c07eae5a65354c09a3850e60461ce4bc4 | https://github.com/derdesign/multi/blob/ea8e3b4c07eae5a65354c09a3850e60461ce4bc4/lib/multi.js#L153-L175 |
41,809 | Mammut-FE/nejm | src/util/history/history.js | function(_href){
// locked from history back
if (!!_locked){
_locked = !1;
return;
}
var _event = {
oldValue:_location,
newValue:_getLocation()
};
// check ignore beforeurlchange event fire
if (!!location.ignored){
location.ignored = !1;
}else{
_v._$dispatchEvent(
location,'beforeurlchange',_event
);
if (_event.stopped){
if (!!_location){
_locked = !0;
_setLocation(_location.href,!0);
}
return;
};
}
// fire urlchange
_url = _ctxt.location.href;
_location = _event.newValue;
_v._$dispatchEvent(
location,'urlchange',_location
);
_h.__pushHistory(_location.href);
} | javascript | function(_href){
// locked from history back
if (!!_locked){
_locked = !1;
return;
}
var _event = {
oldValue:_location,
newValue:_getLocation()
};
// check ignore beforeurlchange event fire
if (!!location.ignored){
location.ignored = !1;
}else{
_v._$dispatchEvent(
location,'beforeurlchange',_event
);
if (_event.stopped){
if (!!_location){
_locked = !0;
_setLocation(_location.href,!0);
}
return;
};
}
// fire urlchange
_url = _ctxt.location.href;
_location = _event.newValue;
_v._$dispatchEvent(
location,'urlchange',_location
);
_h.__pushHistory(_location.href);
} | [
"function",
"(",
"_href",
")",
"{",
"// locked from history back",
"if",
"(",
"!",
"!",
"_locked",
")",
"{",
"_locked",
"=",
"!",
"1",
";",
"return",
";",
"}",
"var",
"_event",
"=",
"{",
"oldValue",
":",
"_location",
",",
"newValue",
":",
"_getLocation",
"(",
")",
"}",
";",
"// check ignore beforeurlchange event fire",
"if",
"(",
"!",
"!",
"location",
".",
"ignored",
")",
"{",
"location",
".",
"ignored",
"=",
"!",
"1",
";",
"}",
"else",
"{",
"_v",
".",
"_$dispatchEvent",
"(",
"location",
",",
"'beforeurlchange'",
",",
"_event",
")",
";",
"if",
"(",
"_event",
".",
"stopped",
")",
"{",
"if",
"(",
"!",
"!",
"_location",
")",
"{",
"_locked",
"=",
"!",
"0",
";",
"_setLocation",
"(",
"_location",
".",
"href",
",",
"!",
"0",
")",
";",
"}",
"return",
";",
"}",
";",
"}",
"// fire urlchange",
"_url",
"=",
"_ctxt",
".",
"location",
".",
"href",
";",
"_location",
"=",
"_event",
".",
"newValue",
";",
"_v",
".",
"_$dispatchEvent",
"(",
"location",
",",
"'urlchange'",
",",
"_location",
")",
";",
"_h",
".",
"__pushHistory",
"(",
"_location",
".",
"href",
")",
";",
"}"
]
| parse location change | [
"parse",
"location",
"change"
]
| dfc09ac66a8d67620a7aea65e34d8a179976b3fb | https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/util/history/history.js#L83-L115 |
|
41,810 | Mammut-FE/nejm | src/util/history/history.js | function(){
var _knl = _m._$KERNEL;
_ie7 = _knl.engine=='trident'&&_knl.release<='3.0';
return _isHack()&&('onhashchange' in window)&&!_ie7;
} | javascript | function(){
var _knl = _m._$KERNEL;
_ie7 = _knl.engine=='trident'&&_knl.release<='3.0';
return _isHack()&&('onhashchange' in window)&&!_ie7;
} | [
"function",
"(",
")",
"{",
"var",
"_knl",
"=",
"_m",
".",
"_$KERNEL",
";",
"_ie7",
"=",
"_knl",
".",
"engine",
"==",
"'trident'",
"&&",
"_knl",
".",
"release",
"<=",
"'3.0'",
";",
"return",
"_isHack",
"(",
")",
"&&",
"(",
"'onhashchange'",
"in",
"window",
")",
"&&",
"!",
"_ie7",
";",
"}"
]
| check use hashchange event on window | [
"check",
"use",
"hashchange",
"event",
"on",
"window"
]
| dfc09ac66a8d67620a7aea65e34d8a179976b3fb | https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/util/history/history.js#L122-L126 |
|
41,811 | DavidSouther/JEFRi | modeler/angular/app/scripts/lib/codemirror/mode/xquery/xquery.js | tokenString | function tokenString(quote, f) {
return function(stream, state) {
var ch;
if(isInString(state) && stream.current() == quote) {
popStateStack(state);
if(f) state.tokenize = f;
return ret("string", "string");
}
pushStateStack(state, { type: "string", name: quote, tokenize: tokenString(quote, f) });
// if we're in a string and in an XML block, allow an embedded code block
if(stream.match("{", false) && isInXmlAttributeBlock(state)) {
state.tokenize = tokenBase;
return ret("string", "string");
}
while (ch = stream.next()) {
if (ch == quote) {
popStateStack(state);
if(f) state.tokenize = f;
break;
}
else {
// if we're in a string and in an XML block, allow an embedded code block in an attribute
if(stream.match("{", false) && isInXmlAttributeBlock(state)) {
state.tokenize = tokenBase;
return ret("string", "string");
}
}
}
return ret("string", "string");
};
} | javascript | function tokenString(quote, f) {
return function(stream, state) {
var ch;
if(isInString(state) && stream.current() == quote) {
popStateStack(state);
if(f) state.tokenize = f;
return ret("string", "string");
}
pushStateStack(state, { type: "string", name: quote, tokenize: tokenString(quote, f) });
// if we're in a string and in an XML block, allow an embedded code block
if(stream.match("{", false) && isInXmlAttributeBlock(state)) {
state.tokenize = tokenBase;
return ret("string", "string");
}
while (ch = stream.next()) {
if (ch == quote) {
popStateStack(state);
if(f) state.tokenize = f;
break;
}
else {
// if we're in a string and in an XML block, allow an embedded code block in an attribute
if(stream.match("{", false) && isInXmlAttributeBlock(state)) {
state.tokenize = tokenBase;
return ret("string", "string");
}
}
}
return ret("string", "string");
};
} | [
"function",
"tokenString",
"(",
"quote",
",",
"f",
")",
"{",
"return",
"function",
"(",
"stream",
",",
"state",
")",
"{",
"var",
"ch",
";",
"if",
"(",
"isInString",
"(",
"state",
")",
"&&",
"stream",
".",
"current",
"(",
")",
"==",
"quote",
")",
"{",
"popStateStack",
"(",
"state",
")",
";",
"if",
"(",
"f",
")",
"state",
".",
"tokenize",
"=",
"f",
";",
"return",
"ret",
"(",
"\"string\"",
",",
"\"string\"",
")",
";",
"}",
"pushStateStack",
"(",
"state",
",",
"{",
"type",
":",
"\"string\"",
",",
"name",
":",
"quote",
",",
"tokenize",
":",
"tokenString",
"(",
"quote",
",",
"f",
")",
"}",
")",
";",
"// if we're in a string and in an XML block, allow an embedded code block",
"if",
"(",
"stream",
".",
"match",
"(",
"\"{\"",
",",
"false",
")",
"&&",
"isInXmlAttributeBlock",
"(",
"state",
")",
")",
"{",
"state",
".",
"tokenize",
"=",
"tokenBase",
";",
"return",
"ret",
"(",
"\"string\"",
",",
"\"string\"",
")",
";",
"}",
"while",
"(",
"ch",
"=",
"stream",
".",
"next",
"(",
")",
")",
"{",
"if",
"(",
"ch",
"==",
"quote",
")",
"{",
"popStateStack",
"(",
"state",
")",
";",
"if",
"(",
"f",
")",
"state",
".",
"tokenize",
"=",
"f",
";",
"break",
";",
"}",
"else",
"{",
"// if we're in a string and in an XML block, allow an embedded code block in an attribute",
"if",
"(",
"stream",
".",
"match",
"(",
"\"{\"",
",",
"false",
")",
"&&",
"isInXmlAttributeBlock",
"(",
"state",
")",
")",
"{",
"state",
".",
"tokenize",
"=",
"tokenBase",
";",
"return",
"ret",
"(",
"\"string\"",
",",
"\"string\"",
")",
";",
"}",
"}",
"}",
"return",
"ret",
"(",
"\"string\"",
",",
"\"string\"",
")",
";",
"}",
";",
"}"
]
| tokenizer for string literals optionally pass a tokenizer function to set state.tokenize back to when finished | [
"tokenizer",
"for",
"string",
"literals",
"optionally",
"pass",
"a",
"tokenizer",
"function",
"to",
"set",
"state",
".",
"tokenize",
"back",
"to",
"when",
"finished"
]
| 161f24e242e05b9b2114cc1123a257141a60eaf2 | https://github.com/DavidSouther/JEFRi/blob/161f24e242e05b9b2114cc1123a257141a60eaf2/modeler/angular/app/scripts/lib/codemirror/mode/xquery/xquery.js#L252-L289 |
41,812 | DavidSouther/JEFRi | modeler/angular/app/scripts/lib/codemirror/mode/xquery/xquery.js | tokenVariable | function tokenVariable(stream, state) {
var isVariableChar = /[\w\$_-]/;
// a variable may start with a quoted EQName so if the next character is quote, consume to the next quote
if(stream.eat("\"")) {
while(stream.next() !== '\"'){};
stream.eat(":");
} else {
stream.eatWhile(isVariableChar);
if(!stream.match(":=", false)) stream.eat(":");
}
stream.eatWhile(isVariableChar);
state.tokenize = tokenBase;
return ret("variable", "variable");
} | javascript | function tokenVariable(stream, state) {
var isVariableChar = /[\w\$_-]/;
// a variable may start with a quoted EQName so if the next character is quote, consume to the next quote
if(stream.eat("\"")) {
while(stream.next() !== '\"'){};
stream.eat(":");
} else {
stream.eatWhile(isVariableChar);
if(!stream.match(":=", false)) stream.eat(":");
}
stream.eatWhile(isVariableChar);
state.tokenize = tokenBase;
return ret("variable", "variable");
} | [
"function",
"tokenVariable",
"(",
"stream",
",",
"state",
")",
"{",
"var",
"isVariableChar",
"=",
"/",
"[\\w\\$_-]",
"/",
";",
"// a variable may start with a quoted EQName so if the next character is quote, consume to the next quote",
"if",
"(",
"stream",
".",
"eat",
"(",
"\"\\\"\"",
")",
")",
"{",
"while",
"(",
"stream",
".",
"next",
"(",
")",
"!==",
"'\\\"'",
")",
"{",
"}",
";",
"stream",
".",
"eat",
"(",
"\":\"",
")",
";",
"}",
"else",
"{",
"stream",
".",
"eatWhile",
"(",
"isVariableChar",
")",
";",
"if",
"(",
"!",
"stream",
".",
"match",
"(",
"\":=\"",
",",
"false",
")",
")",
"stream",
".",
"eat",
"(",
"\":\"",
")",
";",
"}",
"stream",
".",
"eatWhile",
"(",
"isVariableChar",
")",
";",
"state",
".",
"tokenize",
"=",
"tokenBase",
";",
"return",
"ret",
"(",
"\"variable\"",
",",
"\"variable\"",
")",
";",
"}"
]
| tokenizer for variables | [
"tokenizer",
"for",
"variables"
]
| 161f24e242e05b9b2114cc1123a257141a60eaf2 | https://github.com/DavidSouther/JEFRi/blob/161f24e242e05b9b2114cc1123a257141a60eaf2/modeler/angular/app/scripts/lib/codemirror/mode/xquery/xquery.js#L292-L306 |
41,813 | DavidSouther/JEFRi | modeler/angular/app/scripts/lib/codemirror/mode/xquery/xquery.js | tokenAttribute | function tokenAttribute(stream, state) {
var ch = stream.next();
if(ch == "/" && stream.eat(">")) {
if(isInXmlAttributeBlock(state)) popStateStack(state);
if(isInXmlBlock(state)) popStateStack(state);
return ret("tag", "tag");
}
if(ch == ">") {
if(isInXmlAttributeBlock(state)) popStateStack(state);
return ret("tag", "tag");
}
if(ch == "=")
return ret("", "");
// quoted string
if (ch == '"' || ch == "'")
return chain(stream, state, tokenString(ch, tokenAttribute));
if(!isInXmlAttributeBlock(state))
pushStateStack(state, { type: "attribute", name: name, tokenize: tokenAttribute});
stream.eat(/[a-zA-Z_:]/);
stream.eatWhile(/[-a-zA-Z0-9_:.]/);
stream.eatSpace();
// the case where the attribute has not value and the tag was closed
if(stream.match(">", false) || stream.match("/", false)) {
popStateStack(state);
state.tokenize = tokenBase;
}
return ret("attribute", "attribute");
} | javascript | function tokenAttribute(stream, state) {
var ch = stream.next();
if(ch == "/" && stream.eat(">")) {
if(isInXmlAttributeBlock(state)) popStateStack(state);
if(isInXmlBlock(state)) popStateStack(state);
return ret("tag", "tag");
}
if(ch == ">") {
if(isInXmlAttributeBlock(state)) popStateStack(state);
return ret("tag", "tag");
}
if(ch == "=")
return ret("", "");
// quoted string
if (ch == '"' || ch == "'")
return chain(stream, state, tokenString(ch, tokenAttribute));
if(!isInXmlAttributeBlock(state))
pushStateStack(state, { type: "attribute", name: name, tokenize: tokenAttribute});
stream.eat(/[a-zA-Z_:]/);
stream.eatWhile(/[-a-zA-Z0-9_:.]/);
stream.eatSpace();
// the case where the attribute has not value and the tag was closed
if(stream.match(">", false) || stream.match("/", false)) {
popStateStack(state);
state.tokenize = tokenBase;
}
return ret("attribute", "attribute");
} | [
"function",
"tokenAttribute",
"(",
"stream",
",",
"state",
")",
"{",
"var",
"ch",
"=",
"stream",
".",
"next",
"(",
")",
";",
"if",
"(",
"ch",
"==",
"\"/\"",
"&&",
"stream",
".",
"eat",
"(",
"\">\"",
")",
")",
"{",
"if",
"(",
"isInXmlAttributeBlock",
"(",
"state",
")",
")",
"popStateStack",
"(",
"state",
")",
";",
"if",
"(",
"isInXmlBlock",
"(",
"state",
")",
")",
"popStateStack",
"(",
"state",
")",
";",
"return",
"ret",
"(",
"\"tag\"",
",",
"\"tag\"",
")",
";",
"}",
"if",
"(",
"ch",
"==",
"\">\"",
")",
"{",
"if",
"(",
"isInXmlAttributeBlock",
"(",
"state",
")",
")",
"popStateStack",
"(",
"state",
")",
";",
"return",
"ret",
"(",
"\"tag\"",
",",
"\"tag\"",
")",
";",
"}",
"if",
"(",
"ch",
"==",
"\"=\"",
")",
"return",
"ret",
"(",
"\"\"",
",",
"\"\"",
")",
";",
"// quoted string",
"if",
"(",
"ch",
"==",
"'\"'",
"||",
"ch",
"==",
"\"'\"",
")",
"return",
"chain",
"(",
"stream",
",",
"state",
",",
"tokenString",
"(",
"ch",
",",
"tokenAttribute",
")",
")",
";",
"if",
"(",
"!",
"isInXmlAttributeBlock",
"(",
"state",
")",
")",
"pushStateStack",
"(",
"state",
",",
"{",
"type",
":",
"\"attribute\"",
",",
"name",
":",
"name",
",",
"tokenize",
":",
"tokenAttribute",
"}",
")",
";",
"stream",
".",
"eat",
"(",
"/",
"[a-zA-Z_:]",
"/",
")",
";",
"stream",
".",
"eatWhile",
"(",
"/",
"[-a-zA-Z0-9_:.]",
"/",
")",
";",
"stream",
".",
"eatSpace",
"(",
")",
";",
"// the case where the attribute has not value and the tag was closed",
"if",
"(",
"stream",
".",
"match",
"(",
"\">\"",
",",
"false",
")",
"||",
"stream",
".",
"match",
"(",
"\"/\"",
",",
"false",
")",
")",
"{",
"popStateStack",
"(",
"state",
")",
";",
"state",
".",
"tokenize",
"=",
"tokenBase",
";",
"}",
"return",
"ret",
"(",
"\"attribute\"",
",",
"\"attribute\"",
")",
";",
"}"
]
| tokenizer for XML attributes | [
"tokenizer",
"for",
"XML",
"attributes"
]
| 161f24e242e05b9b2114cc1123a257141a60eaf2 | https://github.com/DavidSouther/JEFRi/blob/161f24e242e05b9b2114cc1123a257141a60eaf2/modeler/angular/app/scripts/lib/codemirror/mode/xquery/xquery.js#L332-L364 |
41,814 | AnyFetch/anyfetch-hydrater.js | lib/helpers/Childs.js | function(tasksPerProcess) {
this.ttl = tasksPerProcess;
this.available = true;
this.process = fork(__dirname + '/child-process.js', {silent: true});
this.reset = function() {
this.process.kill('SIGKILL');
this.process = fork(__dirname + '/child-process.js', {silent: true});
this.ttl = tasksPerProcess;
this.available = true;
};
this.clean = function() {
this.process.removeAllListeners();
this.process.stdout.removeAllListeners();
this.process.stderr.removeAllListeners();
};
this.terminate = function() {
this.process.kill('SIGTERM');
};
} | javascript | function(tasksPerProcess) {
this.ttl = tasksPerProcess;
this.available = true;
this.process = fork(__dirname + '/child-process.js', {silent: true});
this.reset = function() {
this.process.kill('SIGKILL');
this.process = fork(__dirname + '/child-process.js', {silent: true});
this.ttl = tasksPerProcess;
this.available = true;
};
this.clean = function() {
this.process.removeAllListeners();
this.process.stdout.removeAllListeners();
this.process.stderr.removeAllListeners();
};
this.terminate = function() {
this.process.kill('SIGTERM');
};
} | [
"function",
"(",
"tasksPerProcess",
")",
"{",
"this",
".",
"ttl",
"=",
"tasksPerProcess",
";",
"this",
".",
"available",
"=",
"true",
";",
"this",
".",
"process",
"=",
"fork",
"(",
"__dirname",
"+",
"'/child-process.js'",
",",
"{",
"silent",
":",
"true",
"}",
")",
";",
"this",
".",
"reset",
"=",
"function",
"(",
")",
"{",
"this",
".",
"process",
".",
"kill",
"(",
"'SIGKILL'",
")",
";",
"this",
".",
"process",
"=",
"fork",
"(",
"__dirname",
"+",
"'/child-process.js'",
",",
"{",
"silent",
":",
"true",
"}",
")",
";",
"this",
".",
"ttl",
"=",
"tasksPerProcess",
";",
"this",
".",
"available",
"=",
"true",
";",
"}",
";",
"this",
".",
"clean",
"=",
"function",
"(",
")",
"{",
"this",
".",
"process",
".",
"removeAllListeners",
"(",
")",
";",
"this",
".",
"process",
".",
"stdout",
".",
"removeAllListeners",
"(",
")",
";",
"this",
".",
"process",
".",
"stderr",
".",
"removeAllListeners",
"(",
")",
";",
"}",
";",
"this",
".",
"terminate",
"=",
"function",
"(",
")",
"{",
"this",
".",
"process",
".",
"kill",
"(",
"'SIGTERM'",
")",
";",
"}",
";",
"}"
]
| Manage a child process | [
"Manage",
"a",
"child",
"process"
]
| 1e70fdb5d8dcd26382e2a16de747b91a5b3ef3ae | https://github.com/AnyFetch/anyfetch-hydrater.js/blob/1e70fdb5d8dcd26382e2a16de747b91a5b3ef3ae/lib/helpers/Childs.js#L9-L31 |
|
41,815 | AnyFetch/anyfetch-hydrater.js | lib/helpers/Childs.js | function(concurrency, tasksPerProcess) {
this.childs = [];
for(var i = 0; i < concurrency; i += 1) {
this.childs[i] = new Child(tasksPerProcess);
}
} | javascript | function(concurrency, tasksPerProcess) {
this.childs = [];
for(var i = 0; i < concurrency; i += 1) {
this.childs[i] = new Child(tasksPerProcess);
}
} | [
"function",
"(",
"concurrency",
",",
"tasksPerProcess",
")",
"{",
"this",
".",
"childs",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"concurrency",
";",
"i",
"+=",
"1",
")",
"{",
"this",
".",
"childs",
"[",
"i",
"]",
"=",
"new",
"Child",
"(",
"tasksPerProcess",
")",
";",
"}",
"}"
]
| Manage a pool of childs process | [
"Manage",
"a",
"pool",
"of",
"childs",
"process"
]
| 1e70fdb5d8dcd26382e2a16de747b91a5b3ef3ae | https://github.com/AnyFetch/anyfetch-hydrater.js/blob/1e70fdb5d8dcd26382e2a16de747b91a5b3ef3ae/lib/helpers/Childs.js#L37-L42 |
|
41,816 | unfoldingWord-dev/node-door43-client | lib/sqlite-helper.js | SQLiteHelper | function SQLiteHelper (schemaPath, dbPath) {
let dbFilePath = dbPath,
dbDirPath = path.dirname(dbFilePath),
sql;
/**
* Saves a sql database to the disk.
*
* @param sql {Database}
*/
function saveDB (sql) {
let data = sql.export();
let buffer = new Buffer(data);
mkdirp.sync(dbDirPath, '0755');
fs.writeFileSync(dbFilePath, buffer);
}
/**
* Prefixes object params with ':'.
* If something other than an object is given the will be returned without being changed.
*
* @param params {[]|{}|string}
* @returns {*} returns the updated params object
*/
function normalizeParams(params) {
if (params && params.constructor !== Array && typeof params === 'object') {
params = _.mapKeys(params, function (value, key) {
return ':' + _.trimStart(key, ':');
});
}
return params;
}
/**
* Executes a command returning the results.
*
* @param query {string} the query string
* @param params {[]|{}} the parameters to be bound to the query
* @returns {[]} an array of rows
*/
function query (query, params) {
let rows = [];
let stmt = sql.prepare(query);
params = normalizeParams(params);
stmt.bind(params);
while(stmt.step()) {
rows.push(stmt.getAsObject());
}
stmt.free();
return rows;
}
/**
* Executes a command ignoring the results.
*
* @param query {string} the run string
* @param params {[]|{}} the parameters to be bound to the query
*/
function run(query, params) {
let stmt = sql.prepare(query);
params = normalizeParams(params);
stmt.run(params);
stmt.free();
}
if (!fs.existsSync(dbFilePath)) {
let schema = fs.readFileSync(schemaPath);
sql = new SQL.Database();
sql.run(schema);
saveDB(sql);
} else {
let buffer = fs.readFileSync(dbFilePath);
sql = new SQL.Database(buffer);
}
return {query: query, save: saveDB.bind(null, sql), run: run};
} | javascript | function SQLiteHelper (schemaPath, dbPath) {
let dbFilePath = dbPath,
dbDirPath = path.dirname(dbFilePath),
sql;
/**
* Saves a sql database to the disk.
*
* @param sql {Database}
*/
function saveDB (sql) {
let data = sql.export();
let buffer = new Buffer(data);
mkdirp.sync(dbDirPath, '0755');
fs.writeFileSync(dbFilePath, buffer);
}
/**
* Prefixes object params with ':'.
* If something other than an object is given the will be returned without being changed.
*
* @param params {[]|{}|string}
* @returns {*} returns the updated params object
*/
function normalizeParams(params) {
if (params && params.constructor !== Array && typeof params === 'object') {
params = _.mapKeys(params, function (value, key) {
return ':' + _.trimStart(key, ':');
});
}
return params;
}
/**
* Executes a command returning the results.
*
* @param query {string} the query string
* @param params {[]|{}} the parameters to be bound to the query
* @returns {[]} an array of rows
*/
function query (query, params) {
let rows = [];
let stmt = sql.prepare(query);
params = normalizeParams(params);
stmt.bind(params);
while(stmt.step()) {
rows.push(stmt.getAsObject());
}
stmt.free();
return rows;
}
/**
* Executes a command ignoring the results.
*
* @param query {string} the run string
* @param params {[]|{}} the parameters to be bound to the query
*/
function run(query, params) {
let stmt = sql.prepare(query);
params = normalizeParams(params);
stmt.run(params);
stmt.free();
}
if (!fs.existsSync(dbFilePath)) {
let schema = fs.readFileSync(schemaPath);
sql = new SQL.Database();
sql.run(schema);
saveDB(sql);
} else {
let buffer = fs.readFileSync(dbFilePath);
sql = new SQL.Database(buffer);
}
return {query: query, save: saveDB.bind(null, sql), run: run};
} | [
"function",
"SQLiteHelper",
"(",
"schemaPath",
",",
"dbPath",
")",
"{",
"let",
"dbFilePath",
"=",
"dbPath",
",",
"dbDirPath",
"=",
"path",
".",
"dirname",
"(",
"dbFilePath",
")",
",",
"sql",
";",
"/**\n * Saves a sql database to the disk.\n *\n * @param sql {Database}\n */",
"function",
"saveDB",
"(",
"sql",
")",
"{",
"let",
"data",
"=",
"sql",
".",
"export",
"(",
")",
";",
"let",
"buffer",
"=",
"new",
"Buffer",
"(",
"data",
")",
";",
"mkdirp",
".",
"sync",
"(",
"dbDirPath",
",",
"'0755'",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"dbFilePath",
",",
"buffer",
")",
";",
"}",
"/**\n * Prefixes object params with ':'.\n * If something other than an object is given the will be returned without being changed.\n *\n * @param params {[]|{}|string}\n * @returns {*} returns the updated params object\n */",
"function",
"normalizeParams",
"(",
"params",
")",
"{",
"if",
"(",
"params",
"&&",
"params",
".",
"constructor",
"!==",
"Array",
"&&",
"typeof",
"params",
"===",
"'object'",
")",
"{",
"params",
"=",
"_",
".",
"mapKeys",
"(",
"params",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"return",
"':'",
"+",
"_",
".",
"trimStart",
"(",
"key",
",",
"':'",
")",
";",
"}",
")",
";",
"}",
"return",
"params",
";",
"}",
"/**\n * Executes a command returning the results.\n *\n * @param query {string} the query string\n * @param params {[]|{}} the parameters to be bound to the query\n * @returns {[]} an array of rows\n */",
"function",
"query",
"(",
"query",
",",
"params",
")",
"{",
"let",
"rows",
"=",
"[",
"]",
";",
"let",
"stmt",
"=",
"sql",
".",
"prepare",
"(",
"query",
")",
";",
"params",
"=",
"normalizeParams",
"(",
"params",
")",
";",
"stmt",
".",
"bind",
"(",
"params",
")",
";",
"while",
"(",
"stmt",
".",
"step",
"(",
")",
")",
"{",
"rows",
".",
"push",
"(",
"stmt",
".",
"getAsObject",
"(",
")",
")",
";",
"}",
"stmt",
".",
"free",
"(",
")",
";",
"return",
"rows",
";",
"}",
"/**\n * Executes a command ignoring the results.\n *\n * @param query {string} the run string\n * @param params {[]|{}} the parameters to be bound to the query\n */",
"function",
"run",
"(",
"query",
",",
"params",
")",
"{",
"let",
"stmt",
"=",
"sql",
".",
"prepare",
"(",
"query",
")",
";",
"params",
"=",
"normalizeParams",
"(",
"params",
")",
";",
"stmt",
".",
"run",
"(",
"params",
")",
";",
"stmt",
".",
"free",
"(",
")",
";",
"}",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"dbFilePath",
")",
")",
"{",
"let",
"schema",
"=",
"fs",
".",
"readFileSync",
"(",
"schemaPath",
")",
";",
"sql",
"=",
"new",
"SQL",
".",
"Database",
"(",
")",
";",
"sql",
".",
"run",
"(",
"schema",
")",
";",
"saveDB",
"(",
"sql",
")",
";",
"}",
"else",
"{",
"let",
"buffer",
"=",
"fs",
".",
"readFileSync",
"(",
"dbFilePath",
")",
";",
"sql",
"=",
"new",
"SQL",
".",
"Database",
"(",
"buffer",
")",
";",
"}",
"return",
"{",
"query",
":",
"query",
",",
"save",
":",
"saveDB",
".",
"bind",
"(",
"null",
",",
"sql",
")",
",",
"run",
":",
"run",
"}",
";",
"}"
]
| A SQLite database helper.
@param schemaPath {string}
@param dbPath {string}
@constructor | [
"A",
"SQLite",
"database",
"helper",
"."
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/lib/sqlite-helper.js#L16-L97 |
41,817 | unfoldingWord-dev/node-door43-client | lib/sqlite-helper.js | saveDB | function saveDB (sql) {
let data = sql.export();
let buffer = new Buffer(data);
mkdirp.sync(dbDirPath, '0755');
fs.writeFileSync(dbFilePath, buffer);
} | javascript | function saveDB (sql) {
let data = sql.export();
let buffer = new Buffer(data);
mkdirp.sync(dbDirPath, '0755');
fs.writeFileSync(dbFilePath, buffer);
} | [
"function",
"saveDB",
"(",
"sql",
")",
"{",
"let",
"data",
"=",
"sql",
".",
"export",
"(",
")",
";",
"let",
"buffer",
"=",
"new",
"Buffer",
"(",
"data",
")",
";",
"mkdirp",
".",
"sync",
"(",
"dbDirPath",
",",
"'0755'",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"dbFilePath",
",",
"buffer",
")",
";",
"}"
]
| Saves a sql database to the disk.
@param sql {Database} | [
"Saves",
"a",
"sql",
"database",
"to",
"the",
"disk",
"."
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/lib/sqlite-helper.js#L27-L33 |
41,818 | unfoldingWord-dev/node-door43-client | lib/sqlite-helper.js | query | function query (query, params) {
let rows = [];
let stmt = sql.prepare(query);
params = normalizeParams(params);
stmt.bind(params);
while(stmt.step()) {
rows.push(stmt.getAsObject());
}
stmt.free();
return rows;
} | javascript | function query (query, params) {
let rows = [];
let stmt = sql.prepare(query);
params = normalizeParams(params);
stmt.bind(params);
while(stmt.step()) {
rows.push(stmt.getAsObject());
}
stmt.free();
return rows;
} | [
"function",
"query",
"(",
"query",
",",
"params",
")",
"{",
"let",
"rows",
"=",
"[",
"]",
";",
"let",
"stmt",
"=",
"sql",
".",
"prepare",
"(",
"query",
")",
";",
"params",
"=",
"normalizeParams",
"(",
"params",
")",
";",
"stmt",
".",
"bind",
"(",
"params",
")",
";",
"while",
"(",
"stmt",
".",
"step",
"(",
")",
")",
"{",
"rows",
".",
"push",
"(",
"stmt",
".",
"getAsObject",
"(",
")",
")",
";",
"}",
"stmt",
".",
"free",
"(",
")",
";",
"return",
"rows",
";",
"}"
]
| Executes a command returning the results.
@param query {string} the query string
@param params {[]|{}} the parameters to be bound to the query
@returns {[]} an array of rows | [
"Executes",
"a",
"command",
"returning",
"the",
"results",
"."
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/lib/sqlite-helper.js#L58-L68 |
41,819 | unfoldingWord-dev/node-door43-client | lib/sqlite-helper.js | run | function run(query, params) {
let stmt = sql.prepare(query);
params = normalizeParams(params);
stmt.run(params);
stmt.free();
} | javascript | function run(query, params) {
let stmt = sql.prepare(query);
params = normalizeParams(params);
stmt.run(params);
stmt.free();
} | [
"function",
"run",
"(",
"query",
",",
"params",
")",
"{",
"let",
"stmt",
"=",
"sql",
".",
"prepare",
"(",
"query",
")",
";",
"params",
"=",
"normalizeParams",
"(",
"params",
")",
";",
"stmt",
".",
"run",
"(",
"params",
")",
";",
"stmt",
".",
"free",
"(",
")",
";",
"}"
]
| Executes a command ignoring the results.
@param query {string} the run string
@param params {[]|{}} the parameters to be bound to the query | [
"Executes",
"a",
"command",
"ignoring",
"the",
"results",
"."
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/lib/sqlite-helper.js#L76-L81 |
41,820 | Runnable/api-client | lib/models/user.js | validateAndCbBackend | function validateAndCbBackend (instance, urlPort, cb) {
var backendUrl = instance.dockerUrlForPort(urlPort);
var err = validateContainer(instance.attrs.container);
if (err) {
return cb(err); }
if (!backendUrl) {
err = Boom.create(400, 'port not exposed', urlPort);
return cb(err);
}
cb(null, backendUrl);
} | javascript | function validateAndCbBackend (instance, urlPort, cb) {
var backendUrl = instance.dockerUrlForPort(urlPort);
var err = validateContainer(instance.attrs.container);
if (err) {
return cb(err); }
if (!backendUrl) {
err = Boom.create(400, 'port not exposed', urlPort);
return cb(err);
}
cb(null, backendUrl);
} | [
"function",
"validateAndCbBackend",
"(",
"instance",
",",
"urlPort",
",",
"cb",
")",
"{",
"var",
"backendUrl",
"=",
"instance",
".",
"dockerUrlForPort",
"(",
"urlPort",
")",
";",
"var",
"err",
"=",
"validateContainer",
"(",
"instance",
".",
"attrs",
".",
"container",
")",
";",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"if",
"(",
"!",
"backendUrl",
")",
"{",
"err",
"=",
"Boom",
".",
"create",
"(",
"400",
",",
"'port not exposed'",
",",
"urlPort",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"cb",
"(",
"null",
",",
"backendUrl",
")",
";",
"}"
]
| private function that gets the backend url of an instance and verifies the port is exposed
@param {Object} instance instance model
@param {Function} cb callback | [
"private",
"function",
"that",
"gets",
"the",
"backend",
"url",
"of",
"an",
"instance",
"and",
"verifies",
"the",
"port",
"is",
"exposed"
]
| e6089c4ed0b8c6ed383a82cbd50514e1e720f154 | https://github.com/Runnable/api-client/blob/e6089c4ed0b8c6ed383a82cbd50514e1e720f154/lib/models/user.js#L327-L338 |
41,821 | studybreak/casio | lib/connection-pool.js | function () {
if (!self.connections.length) {
self.removeListener('remove', remove);
self.closing = false;
return callback();
}
} | javascript | function () {
if (!self.connections.length) {
self.removeListener('remove', remove);
self.closing = false;
return callback();
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"self",
".",
"connections",
".",
"length",
")",
"{",
"self",
".",
"removeListener",
"(",
"'remove'",
",",
"remove",
")",
";",
"self",
".",
"closing",
"=",
"false",
";",
"return",
"callback",
"(",
")",
";",
"}",
"}"
]
| When all of the connections have been removed, call the callback. | [
"When",
"all",
"of",
"the",
"connections",
"have",
"been",
"removed",
"call",
"the",
"callback",
"."
]
| 814546bdd4c861cc363d5398762035598f6dbc09 | https://github.com/studybreak/casio/blob/814546bdd4c861cc363d5398762035598f6dbc09/lib/connection-pool.js#L353-L359 |
|
41,822 | cogswell-io/cogs-pubsub-dialect | index.js | identifySchema | function identifySchema(obj) {
if (obj) {
const code = obj.code;
const action = obj.action;
const category = Dialect[action];
if (category) {
if (action === 'msg' || action == 'invalid-request') {
// First handle the schemas which are a category unto themselves.
return category;
} else if (code) {
// Then handle codes. Fall through if there is a code,
// but it doesn't exist for the identified category.
const categoryCode = category[code];
if (categoryCode) {
return categoryCode;
}
} else {
// If there is no code, attempted to fetch the request sub-object.
return category.request;
}
}
if (code) {
// If there is a code, but it wasn't associated with the identified
// category (if any), then attempt to locate it in the general responses.
let category = Dialect.general;
if (category) {
return category[code];
}
}
}
} | javascript | function identifySchema(obj) {
if (obj) {
const code = obj.code;
const action = obj.action;
const category = Dialect[action];
if (category) {
if (action === 'msg' || action == 'invalid-request') {
// First handle the schemas which are a category unto themselves.
return category;
} else if (code) {
// Then handle codes. Fall through if there is a code,
// but it doesn't exist for the identified category.
const categoryCode = category[code];
if (categoryCode) {
return categoryCode;
}
} else {
// If there is no code, attempted to fetch the request sub-object.
return category.request;
}
}
if (code) {
// If there is a code, but it wasn't associated with the identified
// category (if any), then attempt to locate it in the general responses.
let category = Dialect.general;
if (category) {
return category[code];
}
}
}
} | [
"function",
"identifySchema",
"(",
"obj",
")",
"{",
"if",
"(",
"obj",
")",
"{",
"const",
"code",
"=",
"obj",
".",
"code",
";",
"const",
"action",
"=",
"obj",
".",
"action",
";",
"const",
"category",
"=",
"Dialect",
"[",
"action",
"]",
";",
"if",
"(",
"category",
")",
"{",
"if",
"(",
"action",
"===",
"'msg'",
"||",
"action",
"==",
"'invalid-request'",
")",
"{",
"// First handle the schemas which are a category unto themselves.",
"return",
"category",
";",
"}",
"else",
"if",
"(",
"code",
")",
"{",
"// Then handle codes. Fall through if there is a code,",
"// but it doesn't exist for the identified category.",
"const",
"categoryCode",
"=",
"category",
"[",
"code",
"]",
";",
"if",
"(",
"categoryCode",
")",
"{",
"return",
"categoryCode",
";",
"}",
"}",
"else",
"{",
"// If there is no code, attempted to fetch the request sub-object.",
"return",
"category",
".",
"request",
";",
"}",
"}",
"if",
"(",
"code",
")",
"{",
"// If there is a code, but it wasn't associated with the identified",
"// category (if any), then attempt to locate it in the general responses.",
"let",
"category",
"=",
"Dialect",
".",
"general",
";",
"if",
"(",
"category",
")",
"{",
"return",
"category",
"[",
"code",
"]",
";",
"}",
"}",
"}",
"}"
]
| Identifies the schema to use in order to validate the supplied object. | [
"Identifies",
"the",
"schema",
"to",
"use",
"in",
"order",
"to",
"validate",
"the",
"supplied",
"object",
"."
]
| f265434b5af17a45fc4f84b202bd7cf73c7da655 | https://github.com/cogswell-io/cogs-pubsub-dialect/blob/f265434b5af17a45fc4f84b202bd7cf73c7da655/index.js#L214-L248 |
41,823 | cogswell-io/cogs-pubsub-dialect | index.js | validate | function validate(object, validator, callback) {
if (typeof callback === 'function') {
return Joi.validate(object, validator, callback);
} else {
return Joi.validate(object, validator);
}
} | javascript | function validate(object, validator, callback) {
if (typeof callback === 'function') {
return Joi.validate(object, validator, callback);
} else {
return Joi.validate(object, validator);
}
} | [
"function",
"validate",
"(",
"object",
",",
"validator",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"return",
"Joi",
".",
"validate",
"(",
"object",
",",
"validator",
",",
"callback",
")",
";",
"}",
"else",
"{",
"return",
"Joi",
".",
"validate",
"(",
"object",
",",
"validator",
")",
";",
"}",
"}"
]
| The Joi validator function. | [
"The",
"Joi",
"validator",
"function",
"."
]
| f265434b5af17a45fc4f84b202bd7cf73c7da655 | https://github.com/cogswell-io/cogs-pubsub-dialect/blob/f265434b5af17a45fc4f84b202bd7cf73c7da655/index.js#L251-L257 |
41,824 | cogswell-io/cogs-pubsub-dialect | index.js | autoValidate | function autoValidate(object) {
const seq = (object) ? object.seq : undefined;
const action = (object) ? object.action : undefined;
const schema = identifySchema(object)
if (schema) {
const {error, value} = validate(object, schema);
if (error) {
return { isValid: false, seq, action, error };
} else {
return { isValid: true, seq, action, value };
}
} else {
return { isValid: false, seq, action,
error: new Error('No matching schema found.') };
}
} | javascript | function autoValidate(object) {
const seq = (object) ? object.seq : undefined;
const action = (object) ? object.action : undefined;
const schema = identifySchema(object)
if (schema) {
const {error, value} = validate(object, schema);
if (error) {
return { isValid: false, seq, action, error };
} else {
return { isValid: true, seq, action, value };
}
} else {
return { isValid: false, seq, action,
error: new Error('No matching schema found.') };
}
} | [
"function",
"autoValidate",
"(",
"object",
")",
"{",
"const",
"seq",
"=",
"(",
"object",
")",
"?",
"object",
".",
"seq",
":",
"undefined",
";",
"const",
"action",
"=",
"(",
"object",
")",
"?",
"object",
".",
"action",
":",
"undefined",
";",
"const",
"schema",
"=",
"identifySchema",
"(",
"object",
")",
"if",
"(",
"schema",
")",
"{",
"const",
"{",
"error",
",",
"value",
"}",
"=",
"validate",
"(",
"object",
",",
"schema",
")",
";",
"if",
"(",
"error",
")",
"{",
"return",
"{",
"isValid",
":",
"false",
",",
"seq",
",",
"action",
",",
"error",
"}",
";",
"}",
"else",
"{",
"return",
"{",
"isValid",
":",
"true",
",",
"seq",
",",
"action",
",",
"value",
"}",
";",
"}",
"}",
"else",
"{",
"return",
"{",
"isValid",
":",
"false",
",",
"seq",
",",
"action",
",",
"error",
":",
"new",
"Error",
"(",
"'No matching schema found.'",
")",
"}",
";",
"}",
"}"
]
| Validate the object, auto-detecting its schema. | [
"Validate",
"the",
"object",
"auto",
"-",
"detecting",
"its",
"schema",
"."
]
| f265434b5af17a45fc4f84b202bd7cf73c7da655 | https://github.com/cogswell-io/cogs-pubsub-dialect/blob/f265434b5af17a45fc4f84b202bd7cf73c7da655/index.js#L260-L278 |
41,825 | cogswell-io/cogs-pubsub-dialect | index.js | parseAndAutoValidate | function parseAndAutoValidate(json) {
try {
const obj = JSON.parse(json);
return autoValidate(obj);
} catch (error) {
return { isValid: false, error: error };
}
} | javascript | function parseAndAutoValidate(json) {
try {
const obj = JSON.parse(json);
return autoValidate(obj);
} catch (error) {
return { isValid: false, error: error };
}
} | [
"function",
"parseAndAutoValidate",
"(",
"json",
")",
"{",
"try",
"{",
"const",
"obj",
"=",
"JSON",
".",
"parse",
"(",
"json",
")",
";",
"return",
"autoValidate",
"(",
"obj",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"return",
"{",
"isValid",
":",
"false",
",",
"error",
":",
"error",
"}",
";",
"}",
"}"
]
| Parse and validate JSON, auto-detecting its schema. | [
"Parse",
"and",
"validate",
"JSON",
"auto",
"-",
"detecting",
"its",
"schema",
"."
]
| f265434b5af17a45fc4f84b202bd7cf73c7da655 | https://github.com/cogswell-io/cogs-pubsub-dialect/blob/f265434b5af17a45fc4f84b202bd7cf73c7da655/index.js#L281-L288 |
41,826 | WaiChungWong/jw-mouse | lib/index.js | getDirection | function getDirection(position1, position2) {
var _getDistanceVector2 = getDistanceVector(position1, position2),
x = _getDistanceVector2.x,
y = _getDistanceVector2.y;
return atan2(y, x);
} | javascript | function getDirection(position1, position2) {
var _getDistanceVector2 = getDistanceVector(position1, position2),
x = _getDistanceVector2.x,
y = _getDistanceVector2.y;
return atan2(y, x);
} | [
"function",
"getDirection",
"(",
"position1",
",",
"position2",
")",
"{",
"var",
"_getDistanceVector2",
"=",
"getDistanceVector",
"(",
"position1",
",",
"position2",
")",
",",
"x",
"=",
"_getDistanceVector2",
".",
"x",
",",
"y",
"=",
"_getDistanceVector2",
".",
"y",
";",
"return",
"atan2",
"(",
"y",
",",
"x",
")",
";",
"}"
]
| Calculate the directional angle to the destination position
in terms of the angle oriented to the East. | [
"Calculate",
"the",
"directional",
"angle",
"to",
"the",
"destination",
"position",
"in",
"terms",
"of",
"the",
"angle",
"oriented",
"to",
"the",
"East",
"."
]
| 7c17e333405206065c657ef9bba6d5dfbc3ee7f8 | https://github.com/WaiChungWong/jw-mouse/blob/7c17e333405206065c657ef9bba6d5dfbc3ee7f8/lib/index.js#L43-L49 |
41,827 | DavidSouther/JEFRi | modeler/angular/app/scripts/lib/codemirror/keymap/vim.js | findWord | function findWord(cm, lineNum, pos, dir, regexps) {
var line = cm.getLine(lineNum);
while (true) {
var stop = (dir > 0) ? line.length : -1;
var wordStart = stop, wordEnd = stop;
// Find bounds of next word.
for (; pos != stop; pos += dir) {
for (var i = 0; i < regexps.length; ++i) {
if (regexps[i].test(line.charAt(pos))) {
wordStart = pos;
// Advance to end of word.
for (; pos != stop && regexps[i].test(line.charAt(pos)); pos += dir) {}
wordEnd = (dir > 0) ? pos : pos + 1;
return {
from: Math.min(wordStart, wordEnd),
to: Math.max(wordStart, wordEnd),
line: lineNum};
}
}
}
// Advance to next/prev line.
lineNum += dir;
if (!isLine(cm, lineNum)) return null;
line = cm.getLine(lineNum);
pos = (dir > 0) ? 0 : line.length;
}
} | javascript | function findWord(cm, lineNum, pos, dir, regexps) {
var line = cm.getLine(lineNum);
while (true) {
var stop = (dir > 0) ? line.length : -1;
var wordStart = stop, wordEnd = stop;
// Find bounds of next word.
for (; pos != stop; pos += dir) {
for (var i = 0; i < regexps.length; ++i) {
if (regexps[i].test(line.charAt(pos))) {
wordStart = pos;
// Advance to end of word.
for (; pos != stop && regexps[i].test(line.charAt(pos)); pos += dir) {}
wordEnd = (dir > 0) ? pos : pos + 1;
return {
from: Math.min(wordStart, wordEnd),
to: Math.max(wordStart, wordEnd),
line: lineNum};
}
}
}
// Advance to next/prev line.
lineNum += dir;
if (!isLine(cm, lineNum)) return null;
line = cm.getLine(lineNum);
pos = (dir > 0) ? 0 : line.length;
}
} | [
"function",
"findWord",
"(",
"cm",
",",
"lineNum",
",",
"pos",
",",
"dir",
",",
"regexps",
")",
"{",
"var",
"line",
"=",
"cm",
".",
"getLine",
"(",
"lineNum",
")",
";",
"while",
"(",
"true",
")",
"{",
"var",
"stop",
"=",
"(",
"dir",
">",
"0",
")",
"?",
"line",
".",
"length",
":",
"-",
"1",
";",
"var",
"wordStart",
"=",
"stop",
",",
"wordEnd",
"=",
"stop",
";",
"// Find bounds of next word.",
"for",
"(",
";",
"pos",
"!=",
"stop",
";",
"pos",
"+=",
"dir",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"regexps",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"regexps",
"[",
"i",
"]",
".",
"test",
"(",
"line",
".",
"charAt",
"(",
"pos",
")",
")",
")",
"{",
"wordStart",
"=",
"pos",
";",
"// Advance to end of word.",
"for",
"(",
";",
"pos",
"!=",
"stop",
"&&",
"regexps",
"[",
"i",
"]",
".",
"test",
"(",
"line",
".",
"charAt",
"(",
"pos",
")",
")",
";",
"pos",
"+=",
"dir",
")",
"{",
"}",
"wordEnd",
"=",
"(",
"dir",
">",
"0",
")",
"?",
"pos",
":",
"pos",
"+",
"1",
";",
"return",
"{",
"from",
":",
"Math",
".",
"min",
"(",
"wordStart",
",",
"wordEnd",
")",
",",
"to",
":",
"Math",
".",
"max",
"(",
"wordStart",
",",
"wordEnd",
")",
",",
"line",
":",
"lineNum",
"}",
";",
"}",
"}",
"}",
"// Advance to next/prev line.",
"lineNum",
"+=",
"dir",
";",
"if",
"(",
"!",
"isLine",
"(",
"cm",
",",
"lineNum",
")",
")",
"return",
"null",
";",
"line",
"=",
"cm",
".",
"getLine",
"(",
"lineNum",
")",
";",
"pos",
"=",
"(",
"dir",
">",
"0",
")",
"?",
"0",
":",
"line",
".",
"length",
";",
"}",
"}"
]
| Finds a word on the given line, and continue searching the next line if it can't find one. | [
"Finds",
"a",
"word",
"on",
"the",
"given",
"line",
"and",
"continue",
"searching",
"the",
"next",
"line",
"if",
"it",
"can",
"t",
"find",
"one",
"."
]
| 161f24e242e05b9b2114cc1123a257141a60eaf2 | https://github.com/DavidSouther/JEFRi/blob/161f24e242e05b9b2114cc1123a257141a60eaf2/modeler/angular/app/scripts/lib/codemirror/keymap/vim.js#L103-L129 |
41,828 | DavidSouther/JEFRi | modeler/angular/app/scripts/lib/codemirror/keymap/vim.js | textObjectManipulation | function textObjectManipulation(cm, object, remove, insert, inclusive) {
// Object is the text object, delete object if remove is true, enter insert
// mode if insert is true, inclusive is the difference between a and i
var tmp = textObjects[object](cm, inclusive);
var start = tmp.start;
var end = tmp.end;
if ((start.line > end.line) || (start.line == end.line && start.ch > end.ch)) var swap = true ;
pushInBuffer(cm.getRange(swap ? end : start, swap ? start : end));
if (remove) cm.replaceRange("", swap ? end : start, swap ? start : end);
if (insert) cm.setOption('keyMap', 'vim-insert');
} | javascript | function textObjectManipulation(cm, object, remove, insert, inclusive) {
// Object is the text object, delete object if remove is true, enter insert
// mode if insert is true, inclusive is the difference between a and i
var tmp = textObjects[object](cm, inclusive);
var start = tmp.start;
var end = tmp.end;
if ((start.line > end.line) || (start.line == end.line && start.ch > end.ch)) var swap = true ;
pushInBuffer(cm.getRange(swap ? end : start, swap ? start : end));
if (remove) cm.replaceRange("", swap ? end : start, swap ? start : end);
if (insert) cm.setOption('keyMap', 'vim-insert');
} | [
"function",
"textObjectManipulation",
"(",
"cm",
",",
"object",
",",
"remove",
",",
"insert",
",",
"inclusive",
")",
"{",
"// Object is the text object, delete object if remove is true, enter insert",
"// mode if insert is true, inclusive is the difference between a and i",
"var",
"tmp",
"=",
"textObjects",
"[",
"object",
"]",
"(",
"cm",
",",
"inclusive",
")",
";",
"var",
"start",
"=",
"tmp",
".",
"start",
";",
"var",
"end",
"=",
"tmp",
".",
"end",
";",
"if",
"(",
"(",
"start",
".",
"line",
">",
"end",
".",
"line",
")",
"||",
"(",
"start",
".",
"line",
"==",
"end",
".",
"line",
"&&",
"start",
".",
"ch",
">",
"end",
".",
"ch",
")",
")",
"var",
"swap",
"=",
"true",
";",
"pushInBuffer",
"(",
"cm",
".",
"getRange",
"(",
"swap",
"?",
"end",
":",
"start",
",",
"swap",
"?",
"start",
":",
"end",
")",
")",
";",
"if",
"(",
"remove",
")",
"cm",
".",
"replaceRange",
"(",
"\"\"",
",",
"swap",
"?",
"end",
":",
"start",
",",
"swap",
"?",
"start",
":",
"end",
")",
";",
"if",
"(",
"insert",
")",
"cm",
".",
"setOption",
"(",
"'keyMap'",
",",
"'vim-insert'",
")",
";",
"}"
]
| One function to handle all operation upon text objects. Kinda funky but it works better than rewriting this code six times | [
"One",
"function",
"to",
"handle",
"all",
"operation",
"upon",
"text",
"objects",
".",
"Kinda",
"funky",
"but",
"it",
"works",
"better",
"than",
"rewriting",
"this",
"code",
"six",
"times"
]
| 161f24e242e05b9b2114cc1123a257141a60eaf2 | https://github.com/DavidSouther/JEFRi/blob/161f24e242e05b9b2114cc1123a257141a60eaf2/modeler/angular/app/scripts/lib/codemirror/keymap/vim.js#L871-L883 |
41,829 | Mammut-FE/nejm | src/util/audio/audio.js | function(_key,_event){
if (_event.state==0){
_doClearAction(_key);
}
_doStateChangeCallback(_key,_event.state);
} | javascript | function(_key,_event){
if (_event.state==0){
_doClearAction(_key);
}
_doStateChangeCallback(_key,_event.state);
} | [
"function",
"(",
"_key",
",",
"_event",
")",
"{",
"if",
"(",
"_event",
".",
"state",
"==",
"0",
")",
"{",
"_doClearAction",
"(",
"_key",
")",
";",
"}",
"_doStateChangeCallback",
"(",
"_key",
",",
"_event",
".",
"state",
")",
";",
"}"
]
| state change action | [
"state",
"change",
"action"
]
| dfc09ac66a8d67620a7aea65e34d8a179976b3fb | https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/util/audio/audio.js#L139-L144 |
|
41,830 | LeisureLink/magicbus | lib/exchange-machine.js | function() {
this.handlers.push(topology.on('bindings-completed', () => {
this.handle('bindings-completed');
}));
this.handlers.push(connection.on('reconnected', () => {
this.transition('reconnecting');
}));
this.handlers.push(this.on('failed', (err) => {
_.each(this.deferred, function(x) {
x(err);
});
this.deferred = [];
}));
} | javascript | function() {
this.handlers.push(topology.on('bindings-completed', () => {
this.handle('bindings-completed');
}));
this.handlers.push(connection.on('reconnected', () => {
this.transition('reconnecting');
}));
this.handlers.push(this.on('failed', (err) => {
_.each(this.deferred, function(x) {
x(err);
});
this.deferred = [];
}));
} | [
"function",
"(",
")",
"{",
"this",
".",
"handlers",
".",
"push",
"(",
"topology",
".",
"on",
"(",
"'bindings-completed'",
",",
"(",
")",
"=>",
"{",
"this",
".",
"handle",
"(",
"'bindings-completed'",
")",
";",
"}",
")",
")",
";",
"this",
".",
"handlers",
".",
"push",
"(",
"connection",
".",
"on",
"(",
"'reconnected'",
",",
"(",
")",
"=>",
"{",
"this",
".",
"transition",
"(",
"'reconnecting'",
")",
";",
"}",
")",
")",
";",
"this",
".",
"handlers",
".",
"push",
"(",
"this",
".",
"on",
"(",
"'failed'",
",",
"(",
"err",
")",
"=>",
"{",
"_",
".",
"each",
"(",
"this",
".",
"deferred",
",",
"function",
"(",
"x",
")",
"{",
"x",
"(",
"err",
")",
";",
"}",
")",
";",
"this",
".",
"deferred",
"=",
"[",
"]",
";",
"}",
")",
")",
";",
"}"
]
| Listens for events around bindings and reconnecting
@private
@memberOf ExchangeMachine.prototype | [
"Listens",
"for",
"events",
"around",
"bindings",
"and",
"reconnecting"
]
| 0370c38ebb8c7917cfd3894263d734aefc2d3d29 | https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/exchange-machine.js#L69-L82 |
|
41,831 | LeisureLink/magicbus | lib/exchange-machine.js | function(reject) {
let index = _.indexOf(this.deferred, reject);
if (index >= 0) {
this.deferred.splice(index, 1);
}
} | javascript | function(reject) {
let index = _.indexOf(this.deferred, reject);
if (index >= 0) {
this.deferred.splice(index, 1);
}
} | [
"function",
"(",
"reject",
")",
"{",
"let",
"index",
"=",
"_",
".",
"indexOf",
"(",
"this",
".",
"deferred",
",",
"reject",
")",
";",
"if",
"(",
"index",
">=",
"0",
")",
"{",
"this",
".",
"deferred",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"}",
"}"
]
| Removes DeferredPromise from the tracked list
@private
@memberOf ExchangeMachine.prototype | [
"Removes",
"DeferredPromise",
"from",
"the",
"tracked",
"list"
]
| 0370c38ebb8c7917cfd3894263d734aefc2d3d29 | https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/exchange-machine.js#L90-L95 |
|
41,832 | LeisureLink/magicbus | lib/exchange-machine.js | function() {
let deferred = DeferredPromise();
logger.debug(`Destroy called on exchange ${this.name} - ${connection.name} (${this.published.count()} messages pending)`);
this.handle('destroy', deferred);
return deferred.promise;
} | javascript | function() {
let deferred = DeferredPromise();
logger.debug(`Destroy called on exchange ${this.name} - ${connection.name} (${this.published.count()} messages pending)`);
this.handle('destroy', deferred);
return deferred.promise;
} | [
"function",
"(",
")",
"{",
"let",
"deferred",
"=",
"DeferredPromise",
"(",
")",
";",
"logger",
".",
"debug",
"(",
"`",
"${",
"this",
".",
"name",
"}",
"${",
"connection",
".",
"name",
"}",
"${",
"this",
".",
"published",
".",
"count",
"(",
")",
"}",
"`",
")",
";",
"this",
".",
"handle",
"(",
"'destroy'",
",",
"deferred",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
]
| Destroy the exchange
@public
@memberOf ExchangeMachine.prototype
@returns {Promise} a promise that is fulfilled when destruction is complete | [
"Destroy",
"the",
"exchange"
]
| 0370c38ebb8c7917cfd3894263d734aefc2d3d29 | https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/exchange-machine.js#L117-L122 |
|
41,833 | LeisureLink/magicbus | lib/exchange-machine.js | function(message) {
let publishTimeout = message.timeout || options.publishTimeout || message.connectionPublishTimeout || 0;
logger.silly(`Publish called in state ${this.state}`);
return new Promise((resolve, reject) => {
let timeout;
let timedOut;
if(publishTimeout > 0) {
timeout = setTimeout(() => {
timedOut = true;
reject(new Error('Publish took longer than configured timeout'));
this.removeDeferred(reject);
}, publishTimeout);
}
const onPublished = () => {
resolve();
this.removeDeferred(reject);
};
const onRejected = (err) => {
reject(err);
this.removeDeferred(reject);
};
let op = () => {
if(timeout) {
clearTimeout(timeout);
timeout = null;
}
if(!timedOut) {
return this.channel.publish(message)
.then(onPublished, onRejected);
}
return Promise.resolve();
};
this.deferred.push(reject);
this.handle('publish', op);
});
} | javascript | function(message) {
let publishTimeout = message.timeout || options.publishTimeout || message.connectionPublishTimeout || 0;
logger.silly(`Publish called in state ${this.state}`);
return new Promise((resolve, reject) => {
let timeout;
let timedOut;
if(publishTimeout > 0) {
timeout = setTimeout(() => {
timedOut = true;
reject(new Error('Publish took longer than configured timeout'));
this.removeDeferred(reject);
}, publishTimeout);
}
const onPublished = () => {
resolve();
this.removeDeferred(reject);
};
const onRejected = (err) => {
reject(err);
this.removeDeferred(reject);
};
let op = () => {
if(timeout) {
clearTimeout(timeout);
timeout = null;
}
if(!timedOut) {
return this.channel.publish(message)
.then(onPublished, onRejected);
}
return Promise.resolve();
};
this.deferred.push(reject);
this.handle('publish', op);
});
} | [
"function",
"(",
"message",
")",
"{",
"let",
"publishTimeout",
"=",
"message",
".",
"timeout",
"||",
"options",
".",
"publishTimeout",
"||",
"message",
".",
"connectionPublishTimeout",
"||",
"0",
";",
"logger",
".",
"silly",
"(",
"`",
"${",
"this",
".",
"state",
"}",
"`",
")",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"let",
"timeout",
";",
"let",
"timedOut",
";",
"if",
"(",
"publishTimeout",
">",
"0",
")",
"{",
"timeout",
"=",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"timedOut",
"=",
"true",
";",
"reject",
"(",
"new",
"Error",
"(",
"'Publish took longer than configured timeout'",
")",
")",
";",
"this",
".",
"removeDeferred",
"(",
"reject",
")",
";",
"}",
",",
"publishTimeout",
")",
";",
"}",
"const",
"onPublished",
"=",
"(",
")",
"=>",
"{",
"resolve",
"(",
")",
";",
"this",
".",
"removeDeferred",
"(",
"reject",
")",
";",
"}",
";",
"const",
"onRejected",
"=",
"(",
"err",
")",
"=>",
"{",
"reject",
"(",
"err",
")",
";",
"this",
".",
"removeDeferred",
"(",
"reject",
")",
";",
"}",
";",
"let",
"op",
"=",
"(",
")",
"=>",
"{",
"if",
"(",
"timeout",
")",
"{",
"clearTimeout",
"(",
"timeout",
")",
";",
"timeout",
"=",
"null",
";",
"}",
"if",
"(",
"!",
"timedOut",
")",
"{",
"return",
"this",
".",
"channel",
".",
"publish",
"(",
"message",
")",
".",
"then",
"(",
"onPublished",
",",
"onRejected",
")",
";",
"}",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"}",
";",
"this",
".",
"deferred",
".",
"push",
"(",
"reject",
")",
";",
"this",
".",
"handle",
"(",
"'publish'",
",",
"op",
")",
";",
"}",
")",
";",
"}"
]
| Publish a message to the exchange
@public
@memberOf ExchangeMachine.prototype
@param {Object} message - the message to publish, passed to Exchange.publish
@param {Number} message.timeout - the time to wait before abandoning the publish
@returns {Promise} a promise that is fulfilled when publication is complete | [
"Publish",
"a",
"message",
"to",
"the",
"exchange"
]
| 0370c38ebb8c7917cfd3894263d734aefc2d3d29 | https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/exchange-machine.js#L133-L168 |
|
41,834 | unfoldingWord-dev/node-door43-client | bin/util.js | writeProgress | function writeProgress(id, total, completed) {
var percent = Math.round(10 * (100 * completed) / total) / 10;
if(id == lastProgressId) {
readline.cursorTo(process.stdout, 0);
readline.clearLine(process.stdout, 0);
} else {
lastProgressId = id;
process.stdout.write('\n');
}
var progressTitles = {
projects: 'Indexing Projects',
chunks: 'Indexing Chunks',
ta: 'Indexing translationAcademy',
resources: 'Indexing Resources',
container: 'Downloading Containers',
catalog: 'Indexing Catalogs',
langnames: 'Indexing Target Languages',
'temp-langnames': 'Indexing Temporary Target Languages',
'approved-temp-langnames': 'Indexing Approved Temporary Target Languages',
'new-language-questions': 'Indexing Questionnaire'
};
process.stdout.write((progressTitles[id] || id) + ' [' + total + '] ' + percent + '%');
} | javascript | function writeProgress(id, total, completed) {
var percent = Math.round(10 * (100 * completed) / total) / 10;
if(id == lastProgressId) {
readline.cursorTo(process.stdout, 0);
readline.clearLine(process.stdout, 0);
} else {
lastProgressId = id;
process.stdout.write('\n');
}
var progressTitles = {
projects: 'Indexing Projects',
chunks: 'Indexing Chunks',
ta: 'Indexing translationAcademy',
resources: 'Indexing Resources',
container: 'Downloading Containers',
catalog: 'Indexing Catalogs',
langnames: 'Indexing Target Languages',
'temp-langnames': 'Indexing Temporary Target Languages',
'approved-temp-langnames': 'Indexing Approved Temporary Target Languages',
'new-language-questions': 'Indexing Questionnaire'
};
process.stdout.write((progressTitles[id] || id) + ' [' + total + '] ' + percent + '%');
} | [
"function",
"writeProgress",
"(",
"id",
",",
"total",
",",
"completed",
")",
"{",
"var",
"percent",
"=",
"Math",
".",
"round",
"(",
"10",
"*",
"(",
"100",
"*",
"completed",
")",
"/",
"total",
")",
"/",
"10",
";",
"if",
"(",
"id",
"==",
"lastProgressId",
")",
"{",
"readline",
".",
"cursorTo",
"(",
"process",
".",
"stdout",
",",
"0",
")",
";",
"readline",
".",
"clearLine",
"(",
"process",
".",
"stdout",
",",
"0",
")",
";",
"}",
"else",
"{",
"lastProgressId",
"=",
"id",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")",
";",
"}",
"var",
"progressTitles",
"=",
"{",
"projects",
":",
"'Indexing Projects'",
",",
"chunks",
":",
"'Indexing Chunks'",
",",
"ta",
":",
"'Indexing translationAcademy'",
",",
"resources",
":",
"'Indexing Resources'",
",",
"container",
":",
"'Downloading Containers'",
",",
"catalog",
":",
"'Indexing Catalogs'",
",",
"langnames",
":",
"'Indexing Target Languages'",
",",
"'temp-langnames'",
":",
"'Indexing Temporary Target Languages'",
",",
"'approved-temp-langnames'",
":",
"'Indexing Approved Temporary Target Languages'",
",",
"'new-language-questions'",
":",
"'Indexing Questionnaire'",
"}",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"(",
"progressTitles",
"[",
"id",
"]",
"||",
"id",
")",
"+",
"' ['",
"+",
"total",
"+",
"'] '",
"+",
"percent",
"+",
"'%'",
")",
";",
"}"
]
| Displays a progress indicator in the console.
@param id
@param total
@param completed | [
"Displays",
"a",
"progress",
"indicator",
"in",
"the",
"console",
"."
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/bin/util.js#L11-L33 |
41,835 | backand/backand-hosting-s3 | backand_sync_s3.js | condition | function condition(file){
var suffix = file.path.substr(file.base.length);
var re = new RegExp(specialChars);
var flag = service === "hosting" && re.test(suffix);
var warning = "Warning: Cannot sync files with characters: " + specialChars + " in the file name: ";
if (flag){
var message = warning + suffix;
console.log(message.red);
}
return flag;
} | javascript | function condition(file){
var suffix = file.path.substr(file.base.length);
var re = new RegExp(specialChars);
var flag = service === "hosting" && re.test(suffix);
var warning = "Warning: Cannot sync files with characters: " + specialChars + " in the file name: ";
if (flag){
var message = warning + suffix;
console.log(message.red);
}
return flag;
} | [
"function",
"condition",
"(",
"file",
")",
"{",
"var",
"suffix",
"=",
"file",
".",
"path",
".",
"substr",
"(",
"file",
".",
"base",
".",
"length",
")",
";",
"var",
"re",
"=",
"new",
"RegExp",
"(",
"specialChars",
")",
";",
"var",
"flag",
"=",
"service",
"===",
"\"hosting\"",
"&&",
"re",
".",
"test",
"(",
"suffix",
")",
";",
"var",
"warning",
"=",
"\"Warning: Cannot sync files with characters: \"",
"+",
"specialChars",
"+",
"\" in the file name: \"",
";",
"if",
"(",
"flag",
")",
"{",
"var",
"message",
"=",
"warning",
"+",
"suffix",
";",
"console",
".",
"log",
"(",
"message",
".",
"red",
")",
";",
"}",
"return",
"flag",
";",
"}"
]
| exclude files with special characters in name | [
"exclude",
"files",
"with",
"special",
"characters",
"in",
"name"
]
| 25f802b969fcda285f83c53da8f83a2e17925bc3 | https://github.com/backand/backand-hosting-s3/blob/25f802b969fcda285f83c53da8f83a2e17925bc3/backand_sync_s3.js#L81-L91 |
41,836 | hairyhenderson/node-fellowshipone | lib/person_communications.js | PersonCommunications | function PersonCommunications (f1, personID) {
if (!personID) {
throw new Error('PersonCommunications requires a person ID!')
}
Communications.call(this, f1, {
path: '/People/' + personID + '/Communications'
})
} | javascript | function PersonCommunications (f1, personID) {
if (!personID) {
throw new Error('PersonCommunications requires a person ID!')
}
Communications.call(this, f1, {
path: '/People/' + personID + '/Communications'
})
} | [
"function",
"PersonCommunications",
"(",
"f1",
",",
"personID",
")",
"{",
"if",
"(",
"!",
"personID",
")",
"{",
"throw",
"new",
"Error",
"(",
"'PersonCommunications requires a person ID!'",
")",
"}",
"Communications",
".",
"call",
"(",
"this",
",",
"f1",
",",
"{",
"path",
":",
"'/People/'",
"+",
"personID",
"+",
"'/Communications'",
"}",
")",
"}"
]
| The Communications object, in a Person context.
@param {Object} f1 - the F1 object
@param {Number} personID - the Person ID, for context | [
"The",
"Communications",
"object",
"in",
"a",
"Person",
"context",
"."
]
| 5e80eb9ec31fb6dceee1e8c211e7b6e0e373b08b | https://github.com/hairyhenderson/node-fellowshipone/blob/5e80eb9ec31fb6dceee1e8c211e7b6e0e373b08b/lib/person_communications.js#L10-L17 |
41,837 | zazuko/trifid-core | plugins/error-handler.js | init | function init (router) {
router.use((err, req, res, next) => {
console.error(err.stack || err.message)
res.statusCode = err.statusCode || 500
res.end()
})
} | javascript | function init (router) {
router.use((err, req, res, next) => {
console.error(err.stack || err.message)
res.statusCode = err.statusCode || 500
res.end()
})
} | [
"function",
"init",
"(",
"router",
")",
"{",
"router",
".",
"use",
"(",
"(",
"err",
",",
"req",
",",
"res",
",",
"next",
")",
"=>",
"{",
"console",
".",
"error",
"(",
"err",
".",
"stack",
"||",
"err",
".",
"message",
")",
"res",
".",
"statusCode",
"=",
"err",
".",
"statusCode",
"||",
"500",
"res",
".",
"end",
"(",
")",
"}",
")",
"}"
]
| default error handler -> send no content
@param router | [
"default",
"error",
"handler",
"-",
">",
"send",
"no",
"content"
]
| 47068ef508971f562e35768d829e15699ce3e19c | https://github.com/zazuko/trifid-core/blob/47068ef508971f562e35768d829e15699ce3e19c/plugins/error-handler.js#L5-L12 |
41,838 | unfoldingWord-dev/node-door43-client | lib/library.js | function(table, params, unique) {
unique = unique || [];
let columns = _.keys(params);
let whereStatements = _.map(unique, function(c) { return c + '=:' + c});
let updatedColumns = _.map(_.filter(columns, function(c) { return unique.indexOf(c) }), function(c) { return c + '=:' + c });
let insertHolders = _.map(columns, function(k) { return ':' + k; });
run('insert or ignore into ' + table + ' (' + columns.join(', ') + ') values (' + insertHolders.join(', ') + ')', params);
run('update or fail ' + table + ' set ' + updatedColumns.join(', ') + ' where ' + whereStatements.join(' and '), params);
save();
// TRICKY: in this module we are strictly dealing with inserts or *full* updates.
// Therefore we can rely on the existence of the unique columns to retrieve the id
let result = query('select id from ' + table + ' where ' + whereStatements.join(' and ') + ' order by id asc limit 1', params);
return firstId(result);
} | javascript | function(table, params, unique) {
unique = unique || [];
let columns = _.keys(params);
let whereStatements = _.map(unique, function(c) { return c + '=:' + c});
let updatedColumns = _.map(_.filter(columns, function(c) { return unique.indexOf(c) }), function(c) { return c + '=:' + c });
let insertHolders = _.map(columns, function(k) { return ':' + k; });
run('insert or ignore into ' + table + ' (' + columns.join(', ') + ') values (' + insertHolders.join(', ') + ')', params);
run('update or fail ' + table + ' set ' + updatedColumns.join(', ') + ' where ' + whereStatements.join(' and '), params);
save();
// TRICKY: in this module we are strictly dealing with inserts or *full* updates.
// Therefore we can rely on the existence of the unique columns to retrieve the id
let result = query('select id from ' + table + ' where ' + whereStatements.join(' and ') + ' order by id asc limit 1', params);
return firstId(result);
} | [
"function",
"(",
"table",
",",
"params",
",",
"unique",
")",
"{",
"unique",
"=",
"unique",
"||",
"[",
"]",
";",
"let",
"columns",
"=",
"_",
".",
"keys",
"(",
"params",
")",
";",
"let",
"whereStatements",
"=",
"_",
".",
"map",
"(",
"unique",
",",
"function",
"(",
"c",
")",
"{",
"return",
"c",
"+",
"'=:'",
"+",
"c",
"}",
")",
";",
"let",
"updatedColumns",
"=",
"_",
".",
"map",
"(",
"_",
".",
"filter",
"(",
"columns",
",",
"function",
"(",
"c",
")",
"{",
"return",
"unique",
".",
"indexOf",
"(",
"c",
")",
"}",
")",
",",
"function",
"(",
"c",
")",
"{",
"return",
"c",
"+",
"'=:'",
"+",
"c",
"}",
")",
";",
"let",
"insertHolders",
"=",
"_",
".",
"map",
"(",
"columns",
",",
"function",
"(",
"k",
")",
"{",
"return",
"':'",
"+",
"k",
";",
"}",
")",
";",
"run",
"(",
"'insert or ignore into '",
"+",
"table",
"+",
"' ('",
"+",
"columns",
".",
"join",
"(",
"', '",
")",
"+",
"') values ('",
"+",
"insertHolders",
".",
"join",
"(",
"', '",
")",
"+",
"')'",
",",
"params",
")",
";",
"run",
"(",
"'update or fail '",
"+",
"table",
"+",
"' set '",
"+",
"updatedColumns",
".",
"join",
"(",
"', '",
")",
"+",
"' where '",
"+",
"whereStatements",
".",
"join",
"(",
"' and '",
")",
",",
"params",
")",
";",
"save",
"(",
")",
";",
"// TRICKY: in this module we are strictly dealing with inserts or *full* updates.",
"// Therefore we can rely on the existence of the unique columns to retrieve the id",
"let",
"result",
"=",
"query",
"(",
"'select id from '",
"+",
"table",
"+",
"' where '",
"+",
"whereStatements",
".",
"join",
"(",
"' and '",
")",
"+",
"' order by id asc limit 1'",
",",
"params",
")",
";",
"return",
"firstId",
"(",
"result",
")",
";",
"}"
]
| A utility to perform insert+update operations.
Insert failures are ignored.
Update failures are thrown.
@param table {string}
@param params {{}} keys must be valid column names
@param unique {[]} a list of unique columns on this table. This should be a subset of params
@returns {int} the id of the inserted/updated row or -1 | [
"A",
"utility",
"to",
"perform",
"insert",
"+",
"update",
"operations",
".",
"Insert",
"failures",
"are",
"ignored",
".",
"Update",
"failures",
"are",
"thrown",
"."
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/lib/library.js#L65-L82 |
|
41,839 | unfoldingWord-dev/node-door43-client | lib/library.js | function(obj, required_props) {
if(typeof obj === 'object') {
required_props = required_props || Object.keys(obj);
for (let prop of required_props) {
if (obj[prop] === undefined || obj[prop] === null || obj[prop] === '') {
throw new Error('Missing required property "' + prop + '"');
}
}
} else if(required_props && required_props.length > 0) {
throw new Error('Missing required property "' + required_props + '"');
} else if(obj === undefined || obj === null || obj === '') {
throw new Error('The value cannot be empty');
}
} | javascript | function(obj, required_props) {
if(typeof obj === 'object') {
required_props = required_props || Object.keys(obj);
for (let prop of required_props) {
if (obj[prop] === undefined || obj[prop] === null || obj[prop] === '') {
throw new Error('Missing required property "' + prop + '"');
}
}
} else if(required_props && required_props.length > 0) {
throw new Error('Missing required property "' + required_props + '"');
} else if(obj === undefined || obj === null || obj === '') {
throw new Error('The value cannot be empty');
}
} | [
"function",
"(",
"obj",
",",
"required_props",
")",
"{",
"if",
"(",
"typeof",
"obj",
"===",
"'object'",
")",
"{",
"required_props",
"=",
"required_props",
"||",
"Object",
".",
"keys",
"(",
"obj",
")",
";",
"for",
"(",
"let",
"prop",
"of",
"required_props",
")",
"{",
"if",
"(",
"obj",
"[",
"prop",
"]",
"===",
"undefined",
"||",
"obj",
"[",
"prop",
"]",
"===",
"null",
"||",
"obj",
"[",
"prop",
"]",
"===",
"''",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing required property \"'",
"+",
"prop",
"+",
"'\"'",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"required_props",
"&&",
"required_props",
".",
"length",
">",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing required property \"'",
"+",
"required_props",
"+",
"'\"'",
")",
";",
"}",
"else",
"if",
"(",
"obj",
"===",
"undefined",
"||",
"obj",
"===",
"null",
"||",
"obj",
"===",
"''",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The value cannot be empty'",
")",
";",
"}",
"}"
]
| Performs an empty validation check on an object or scalar.
This should only be used to validate string properties
since invalid integers values are handled by the db schema.
@param obj {{}|string} the object or string to be validated
@param required_props {[string]} an array of required properties. default is all properties in obj. If obj is a scalar this should be the name of the property for reporting purposes. | [
"Performs",
"an",
"empty",
"validation",
"check",
"on",
"an",
"object",
"or",
"scalar",
".",
"This",
"should",
"only",
"be",
"used",
"to",
"validate",
"string",
"properties",
"since",
"invalid",
"integers",
"values",
"are",
"handled",
"by",
"the",
"db",
"schema",
"."
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/lib/library.js#L92-L105 |
|
41,840 | unfoldingWord-dev/node-door43-client | lib/library.js | function() {
let resultLangCount = query('select count(*) as count from target_language');
let resultResLvl3Count = query('select count(*) as count from resource where checking_level >= 3');
let resultResCount = query('select count(*) as count from resource');
let resultProjCount = query('select count(*) as count from (select id from project group by slug)');
return {
resource_count_level3:resultResLvl3Count[0]['count'],
resource_count:resultResCount[0]['count'],
target_language_count:resultLangCount[0]['count'],
project_count:resultProjCount[0]['count']
};
} | javascript | function() {
let resultLangCount = query('select count(*) as count from target_language');
let resultResLvl3Count = query('select count(*) as count from resource where checking_level >= 3');
let resultResCount = query('select count(*) as count from resource');
let resultProjCount = query('select count(*) as count from (select id from project group by slug)');
return {
resource_count_level3:resultResLvl3Count[0]['count'],
resource_count:resultResCount[0]['count'],
target_language_count:resultLangCount[0]['count'],
project_count:resultProjCount[0]['count']
};
} | [
"function",
"(",
")",
"{",
"let",
"resultLangCount",
"=",
"query",
"(",
"'select count(*) as count from target_language'",
")",
";",
"let",
"resultResLvl3Count",
"=",
"query",
"(",
"'select count(*) as count from resource where checking_level >= 3'",
")",
";",
"let",
"resultResCount",
"=",
"query",
"(",
"'select count(*) as count from resource'",
")",
";",
"let",
"resultProjCount",
"=",
"query",
"(",
"'select count(*) as count from (select id from project group by slug)'",
")",
";",
"return",
"{",
"resource_count_level3",
":",
"resultResLvl3Count",
"[",
"0",
"]",
"[",
"'count'",
"]",
",",
"resource_count",
":",
"resultResCount",
"[",
"0",
"]",
"[",
"'count'",
"]",
",",
"target_language_count",
":",
"resultLangCount",
"[",
"0",
"]",
"[",
"'count'",
"]",
",",
"project_count",
":",
"resultProjCount",
"[",
"0",
"]",
"[",
"'count'",
"]",
"}",
";",
"}"
]
| Returns a map of metrics about content in the index | [
"Returns",
"a",
"map",
"of",
"metrics",
"about",
"content",
"in",
"the",
"index"
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/lib/library.js#L525-L536 |
|
41,841 | unfoldingWord-dev/node-door43-client | lib/library.js | function(temp_target_language_slug) {
let result = query('select tl.* from target_language as tl' +
' left join temp_target_language as ttl on ttl.approved_target_language_slug=tl.slug' +
' where ttl.slug=?', [temp_target_language_slug]);
if(result.length > 0) {
delete result[0].id;
return result[0];
}
return null;
} | javascript | function(temp_target_language_slug) {
let result = query('select tl.* from target_language as tl' +
' left join temp_target_language as ttl on ttl.approved_target_language_slug=tl.slug' +
' where ttl.slug=?', [temp_target_language_slug]);
if(result.length > 0) {
delete result[0].id;
return result[0];
}
return null;
} | [
"function",
"(",
"temp_target_language_slug",
")",
"{",
"let",
"result",
"=",
"query",
"(",
"'select tl.* from target_language as tl'",
"+",
"' left join temp_target_language as ttl on ttl.approved_target_language_slug=tl.slug'",
"+",
"' where ttl.slug=?'",
",",
"[",
"temp_target_language_slug",
"]",
")",
";",
"if",
"(",
"result",
".",
"length",
">",
"0",
")",
"{",
"delete",
"result",
"[",
"0",
"]",
".",
"id",
";",
"return",
"result",
"[",
"0",
"]",
";",
"}",
"return",
"null",
";",
"}"
]
| Returns the target language that has been assigned to a temporary target language.
Note: does not include the row id. You don't need it
@param temp_target_language_slug {string} the temporary target language with the assignment
@returns {{}|null} the language object or null if it does not exist | [
"Returns",
"the",
"target",
"language",
"that",
"has",
"been",
"assigned",
"to",
"a",
"temporary",
"target",
"language",
"."
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/lib/library.js#L608-L617 |
|
41,842 | unfoldingWord-dev/node-door43-client | lib/library.js | function(languageSlug, projectSlug) {
// support passing args as an object
if(languageSlug != null && typeof languageSlug == 'object') {
projectSlug = languageSlug.projectSlug;
languageSlug = languageSlug.languageSlug;
}
let result = query('select p.*, c.slug as category_slug from project as p' +
' left join category as c on c.id=p.category_id' +
' where p.slug=? and p.source_language_id in (' +
' select id from source_language where slug=?)' +
' limit 1', [projectSlug, languageSlug]);
if(result.length > 0) {
// store the language slug for convenience
result[0].source_language_slug = languageSlug;
return result[0];
}
return null;
} | javascript | function(languageSlug, projectSlug) {
// support passing args as an object
if(languageSlug != null && typeof languageSlug == 'object') {
projectSlug = languageSlug.projectSlug;
languageSlug = languageSlug.languageSlug;
}
let result = query('select p.*, c.slug as category_slug from project as p' +
' left join category as c on c.id=p.category_id' +
' where p.slug=? and p.source_language_id in (' +
' select id from source_language where slug=?)' +
' limit 1', [projectSlug, languageSlug]);
if(result.length > 0) {
// store the language slug for convenience
result[0].source_language_slug = languageSlug;
return result[0];
}
return null;
} | [
"function",
"(",
"languageSlug",
",",
"projectSlug",
")",
"{",
"// support passing args as an object",
"if",
"(",
"languageSlug",
"!=",
"null",
"&&",
"typeof",
"languageSlug",
"==",
"'object'",
")",
"{",
"projectSlug",
"=",
"languageSlug",
".",
"projectSlug",
";",
"languageSlug",
"=",
"languageSlug",
".",
"languageSlug",
";",
"}",
"let",
"result",
"=",
"query",
"(",
"'select p.*, c.slug as category_slug from project as p'",
"+",
"' left join category as c on c.id=p.category_id'",
"+",
"' where p.slug=? and p.source_language_id in ('",
"+",
"' select id from source_language where slug=?)'",
"+",
"' limit 1'",
",",
"[",
"projectSlug",
",",
"languageSlug",
"]",
")",
";",
"if",
"(",
"result",
".",
"length",
">",
"0",
")",
"{",
"// store the language slug for convenience",
"result",
"[",
"0",
"]",
".",
"source_language_slug",
"=",
"languageSlug",
";",
"return",
"result",
"[",
"0",
"]",
";",
"}",
"return",
"null",
";",
"}"
]
| Returns a project.
@param languageSlug {string|{languageSlug, projectSlug}}
@param projectSlug {string}
@returns {{}|null} the project object or null if it does not exist | [
"Returns",
"a",
"project",
"."
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/lib/library.js#L626-L643 |
|
41,843 | unfoldingWord-dev/node-door43-client | lib/library.js | function(languageSlug) {
let result;
if(languageSlug) {
result = query('select p.*, c.slug as category_slug from project as p' +
' left join category as c on c.id=p.category_id' +
' where p.source_language_id in (select id from source_language where slug=?)' +
' order by p.sort asc', [languageSlug]);
} else {
result = query('select * from project' +
' group by slug order by sort asc');
}
for(let project of result) {
// store the language slug for convenience
project.source_language_slug = languageSlug;
}
return result;
} | javascript | function(languageSlug) {
let result;
if(languageSlug) {
result = query('select p.*, c.slug as category_slug from project as p' +
' left join category as c on c.id=p.category_id' +
' where p.source_language_id in (select id from source_language where slug=?)' +
' order by p.sort asc', [languageSlug]);
} else {
result = query('select * from project' +
' group by slug order by sort asc');
}
for(let project of result) {
// store the language slug for convenience
project.source_language_slug = languageSlug;
}
return result;
} | [
"function",
"(",
"languageSlug",
")",
"{",
"let",
"result",
";",
"if",
"(",
"languageSlug",
")",
"{",
"result",
"=",
"query",
"(",
"'select p.*, c.slug as category_slug from project as p'",
"+",
"' left join category as c on c.id=p.category_id'",
"+",
"' where p.source_language_id in (select id from source_language where slug=?)'",
"+",
"' order by p.sort asc'",
",",
"[",
"languageSlug",
"]",
")",
";",
"}",
"else",
"{",
"result",
"=",
"query",
"(",
"'select * from project'",
"+",
"' group by slug order by sort asc'",
")",
";",
"}",
"for",
"(",
"let",
"project",
"of",
"result",
")",
"{",
"// store the language slug for convenience",
"project",
".",
"source_language_slug",
"=",
"languageSlug",
";",
"}",
"return",
"result",
";",
"}"
]
| Returns a list of projects available in the given language.
@param languageSlug {string} if left null an array of all unique projects will be returned
@returns {[{}]} an array of projects | [
"Returns",
"a",
"list",
"of",
"projects",
"available",
"in",
"the",
"given",
"language",
"."
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/lib/library.js#L651-L667 |
|
41,844 | unfoldingWord-dev/node-door43-client | lib/library.js | function(parentCategoryId, languageSlug, translateMode) {
let preferredSlug = [languageSlug, 'en', '%'];
let categories = [];
if(translateMode) {
categories = query('select \'category\' as type, c.slug as name, \'\' as source_language_slug,' +
' c.id, c.slug, c.parent_id, count(p.id) as num from category as c' +
' left join (' +
' select p.id, p.category_id, count(r.id) as num from project as p' +
' left join resource as r on r.project_id=p.id and r.translate_mode like(?)' +
' group by p.slug' +
' ) p on p.category_id=c.id and p.num > 0' +
' where parent_id=? and num > 0 group by c.slug', [translateMode, parentCategoryId]);
} else {
categories = query('select \'category\' as type, category.slug as name, \'\' as source_language_slug, * from category where parent_id=?', [parentCategoryId]);
}
// find best name
let catNameQuery = 'select sl.slug as source_language_slug, cn.name as name' +
' from category_name as cn' +
' left join source_language as sl on sl.id=cn.source_language_id' +
' where sl.slug like(?) and cn.category_id=?';
for(let cat of categories) {
for(let slug of preferredSlug) {
let result = query(catNameQuery, [slug, cat.id]);
if(result.length > 0) {
cat.name = result[0]['name'];
cat.source_language_slug = result[0]['source_language_slug'];
break;
}
}
}
let projects = query('select * from (' +
' select \'project\' as type, \'\' as source_language_slug,' +
' p.id, p.slug, p.sort, p.name, count(r.id) as num from project as p' +
' left join resource as r on r.project_id=p.id and r.translate_mode like (?)' +
' where p.category_id=? group by p.slug' +
')' + (translateMode ? ' where num > 0' : ''), [translateMode || '%', parentCategoryId]);
// find best name
let projNameQuery = 'select sl.slug as source_language_slug, p.name as name' +
' from project as p' +
' left join source_language as sl on sl.id=p.source_language_id' +
' where sl.slug like(?) and p.slug=? order by sl.slug asc';
for(let proj of projects) {
for(let slug of preferredSlug) {
let result = query(projNameQuery, [slug, proj.slug]);
if(result.length > 0) {
proj.name = result[0]['name'];
proj.source_language_slug = result[0]['source_language_slug'];
break;
}
}
}
return categories.concat(projects);
} | javascript | function(parentCategoryId, languageSlug, translateMode) {
let preferredSlug = [languageSlug, 'en', '%'];
let categories = [];
if(translateMode) {
categories = query('select \'category\' as type, c.slug as name, \'\' as source_language_slug,' +
' c.id, c.slug, c.parent_id, count(p.id) as num from category as c' +
' left join (' +
' select p.id, p.category_id, count(r.id) as num from project as p' +
' left join resource as r on r.project_id=p.id and r.translate_mode like(?)' +
' group by p.slug' +
' ) p on p.category_id=c.id and p.num > 0' +
' where parent_id=? and num > 0 group by c.slug', [translateMode, parentCategoryId]);
} else {
categories = query('select \'category\' as type, category.slug as name, \'\' as source_language_slug, * from category where parent_id=?', [parentCategoryId]);
}
// find best name
let catNameQuery = 'select sl.slug as source_language_slug, cn.name as name' +
' from category_name as cn' +
' left join source_language as sl on sl.id=cn.source_language_id' +
' where sl.slug like(?) and cn.category_id=?';
for(let cat of categories) {
for(let slug of preferredSlug) {
let result = query(catNameQuery, [slug, cat.id]);
if(result.length > 0) {
cat.name = result[0]['name'];
cat.source_language_slug = result[0]['source_language_slug'];
break;
}
}
}
let projects = query('select * from (' +
' select \'project\' as type, \'\' as source_language_slug,' +
' p.id, p.slug, p.sort, p.name, count(r.id) as num from project as p' +
' left join resource as r on r.project_id=p.id and r.translate_mode like (?)' +
' where p.category_id=? group by p.slug' +
')' + (translateMode ? ' where num > 0' : ''), [translateMode || '%', parentCategoryId]);
// find best name
let projNameQuery = 'select sl.slug as source_language_slug, p.name as name' +
' from project as p' +
' left join source_language as sl on sl.id=p.source_language_id' +
' where sl.slug like(?) and p.slug=? order by sl.slug asc';
for(let proj of projects) {
for(let slug of preferredSlug) {
let result = query(projNameQuery, [slug, proj.slug]);
if(result.length > 0) {
proj.name = result[0]['name'];
proj.source_language_slug = result[0]['source_language_slug'];
break;
}
}
}
return categories.concat(projects);
} | [
"function",
"(",
"parentCategoryId",
",",
"languageSlug",
",",
"translateMode",
")",
"{",
"let",
"preferredSlug",
"=",
"[",
"languageSlug",
",",
"'en'",
",",
"'%'",
"]",
";",
"let",
"categories",
"=",
"[",
"]",
";",
"if",
"(",
"translateMode",
")",
"{",
"categories",
"=",
"query",
"(",
"'select \\'category\\' as type, c.slug as name, \\'\\' as source_language_slug,'",
"+",
"' c.id, c.slug, c.parent_id, count(p.id) as num from category as c'",
"+",
"' left join ('",
"+",
"' select p.id, p.category_id, count(r.id) as num from project as p'",
"+",
"' left join resource as r on r.project_id=p.id and r.translate_mode like(?)'",
"+",
"' group by p.slug'",
"+",
"' ) p on p.category_id=c.id and p.num > 0'",
"+",
"' where parent_id=? and num > 0 group by c.slug'",
",",
"[",
"translateMode",
",",
"parentCategoryId",
"]",
")",
";",
"}",
"else",
"{",
"categories",
"=",
"query",
"(",
"'select \\'category\\' as type, category.slug as name, \\'\\' as source_language_slug, * from category where parent_id=?'",
",",
"[",
"parentCategoryId",
"]",
")",
";",
"}",
"// find best name",
"let",
"catNameQuery",
"=",
"'select sl.slug as source_language_slug, cn.name as name'",
"+",
"' from category_name as cn'",
"+",
"' left join source_language as sl on sl.id=cn.source_language_id'",
"+",
"' where sl.slug like(?) and cn.category_id=?'",
";",
"for",
"(",
"let",
"cat",
"of",
"categories",
")",
"{",
"for",
"(",
"let",
"slug",
"of",
"preferredSlug",
")",
"{",
"let",
"result",
"=",
"query",
"(",
"catNameQuery",
",",
"[",
"slug",
",",
"cat",
".",
"id",
"]",
")",
";",
"if",
"(",
"result",
".",
"length",
">",
"0",
")",
"{",
"cat",
".",
"name",
"=",
"result",
"[",
"0",
"]",
"[",
"'name'",
"]",
";",
"cat",
".",
"source_language_slug",
"=",
"result",
"[",
"0",
"]",
"[",
"'source_language_slug'",
"]",
";",
"break",
";",
"}",
"}",
"}",
"let",
"projects",
"=",
"query",
"(",
"'select * from ('",
"+",
"' select \\'project\\' as type, \\'\\' as source_language_slug,'",
"+",
"' p.id, p.slug, p.sort, p.name, count(r.id) as num from project as p'",
"+",
"' left join resource as r on r.project_id=p.id and r.translate_mode like (?)'",
"+",
"' where p.category_id=? group by p.slug'",
"+",
"')'",
"+",
"(",
"translateMode",
"?",
"' where num > 0'",
":",
"''",
")",
",",
"[",
"translateMode",
"||",
"'%'",
",",
"parentCategoryId",
"]",
")",
";",
"// find best name",
"let",
"projNameQuery",
"=",
"'select sl.slug as source_language_slug, p.name as name'",
"+",
"' from project as p'",
"+",
"' left join source_language as sl on sl.id=p.source_language_id'",
"+",
"' where sl.slug like(?) and p.slug=? order by sl.slug asc'",
";",
"for",
"(",
"let",
"proj",
"of",
"projects",
")",
"{",
"for",
"(",
"let",
"slug",
"of",
"preferredSlug",
")",
"{",
"let",
"result",
"=",
"query",
"(",
"projNameQuery",
",",
"[",
"slug",
",",
"proj",
".",
"slug",
"]",
")",
";",
"if",
"(",
"result",
".",
"length",
">",
"0",
")",
"{",
"proj",
".",
"name",
"=",
"result",
"[",
"0",
"]",
"[",
"'name'",
"]",
";",
"proj",
".",
"source_language_slug",
"=",
"result",
"[",
"0",
"]",
"[",
"'source_language_slug'",
"]",
";",
"break",
";",
"}",
"}",
"}",
"return",
"categories",
".",
"concat",
"(",
"projects",
")",
";",
"}"
]
| Returns an array of categories that exist underneath the parent category.
The results of this method are a combination of categories and projects.
@param parentCategoryId {int} the category who's children will be returned. If 0 then all top level categories will be returned.
@param languageSlug {string} the language in which the category titles will be displayed
@param translateMode {string} limit the results to just those with the given translate mode. Leave this falsy to not filter
@returns {[{}]} an array of project categories | [
"Returns",
"an",
"array",
"of",
"categories",
"that",
"exist",
"underneath",
"the",
"parent",
"category",
".",
"The",
"results",
"of",
"this",
"method",
"are",
"a",
"combination",
"of",
"categories",
"and",
"projects",
"."
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/lib/library.js#L678-L732 |
|
41,845 | unfoldingWord-dev/node-door43-client | lib/library.js | function(languageSlug, projectSlug, resourceSlug) {
let result = query('select r.*, lri.translation_words_assignments_url from resource as r' +
' left join legacy_resource_info as lri on lri.resource_id=r.id' +
' where r.slug=? and r.project_id in (' +
' select id from project where slug=? and source_language_id in (' +
' select id from source_language where slug=?)' +
' )' +
' limit 1', [resourceSlug, projectSlug, languageSlug]);
if(result.length > 0) {
let res = result[0];
// organize the status
res.status = {
translate_mode: res.translate_mode,
checking_level: res.checking_level,
comments: res.comments,
pub_date: res.pub_date,
license: res.license,
version: res.version
};
delete res.translate_mode;
delete res.checking_level;
delete res.comments;
delete res.pub_date;
delete res.license;
delete res.version;
// store language and project slug for convenience
res.source_language_slug = languageSlug;
res.project_slug = projectSlug;
// get formats
res.formats = [];
let formatResults = query('select * from resource_format' +
' where resource_id=?', [res.id]);
res.imported = false;
for(let format of formatResults) {
delete format.id;
delete format.resource_id;
format.imported = !!format.imported;
res.formats.push(format);
// TRICKY: this is not technically correct, but for convenience we attach the import status to the resource directly
if(format.imported) res.imported = true;
}
return res;
}
return null;
} | javascript | function(languageSlug, projectSlug, resourceSlug) {
let result = query('select r.*, lri.translation_words_assignments_url from resource as r' +
' left join legacy_resource_info as lri on lri.resource_id=r.id' +
' where r.slug=? and r.project_id in (' +
' select id from project where slug=? and source_language_id in (' +
' select id from source_language where slug=?)' +
' )' +
' limit 1', [resourceSlug, projectSlug, languageSlug]);
if(result.length > 0) {
let res = result[0];
// organize the status
res.status = {
translate_mode: res.translate_mode,
checking_level: res.checking_level,
comments: res.comments,
pub_date: res.pub_date,
license: res.license,
version: res.version
};
delete res.translate_mode;
delete res.checking_level;
delete res.comments;
delete res.pub_date;
delete res.license;
delete res.version;
// store language and project slug for convenience
res.source_language_slug = languageSlug;
res.project_slug = projectSlug;
// get formats
res.formats = [];
let formatResults = query('select * from resource_format' +
' where resource_id=?', [res.id]);
res.imported = false;
for(let format of formatResults) {
delete format.id;
delete format.resource_id;
format.imported = !!format.imported;
res.formats.push(format);
// TRICKY: this is not technically correct, but for convenience we attach the import status to the resource directly
if(format.imported) res.imported = true;
}
return res;
}
return null;
} | [
"function",
"(",
"languageSlug",
",",
"projectSlug",
",",
"resourceSlug",
")",
"{",
"let",
"result",
"=",
"query",
"(",
"'select r.*, lri.translation_words_assignments_url from resource as r'",
"+",
"' left join legacy_resource_info as lri on lri.resource_id=r.id'",
"+",
"' where r.slug=? and r.project_id in ('",
"+",
"' select id from project where slug=? and source_language_id in ('",
"+",
"' select id from source_language where slug=?)'",
"+",
"' )'",
"+",
"' limit 1'",
",",
"[",
"resourceSlug",
",",
"projectSlug",
",",
"languageSlug",
"]",
")",
";",
"if",
"(",
"result",
".",
"length",
">",
"0",
")",
"{",
"let",
"res",
"=",
"result",
"[",
"0",
"]",
";",
"// organize the status",
"res",
".",
"status",
"=",
"{",
"translate_mode",
":",
"res",
".",
"translate_mode",
",",
"checking_level",
":",
"res",
".",
"checking_level",
",",
"comments",
":",
"res",
".",
"comments",
",",
"pub_date",
":",
"res",
".",
"pub_date",
",",
"license",
":",
"res",
".",
"license",
",",
"version",
":",
"res",
".",
"version",
"}",
";",
"delete",
"res",
".",
"translate_mode",
";",
"delete",
"res",
".",
"checking_level",
";",
"delete",
"res",
".",
"comments",
";",
"delete",
"res",
".",
"pub_date",
";",
"delete",
"res",
".",
"license",
";",
"delete",
"res",
".",
"version",
";",
"// store language and project slug for convenience",
"res",
".",
"source_language_slug",
"=",
"languageSlug",
";",
"res",
".",
"project_slug",
"=",
"projectSlug",
";",
"// get formats",
"res",
".",
"formats",
"=",
"[",
"]",
";",
"let",
"formatResults",
"=",
"query",
"(",
"'select * from resource_format'",
"+",
"' where resource_id=?'",
",",
"[",
"res",
".",
"id",
"]",
")",
";",
"res",
".",
"imported",
"=",
"false",
";",
"for",
"(",
"let",
"format",
"of",
"formatResults",
")",
"{",
"delete",
"format",
".",
"id",
";",
"delete",
"format",
".",
"resource_id",
";",
"format",
".",
"imported",
"=",
"!",
"!",
"format",
".",
"imported",
";",
"res",
".",
"formats",
".",
"push",
"(",
"format",
")",
";",
"// TRICKY: this is not technically correct, but for convenience we attach the import status to the resource directly",
"if",
"(",
"format",
".",
"imported",
")",
"res",
".",
"imported",
"=",
"true",
";",
"}",
"return",
"res",
";",
"}",
"return",
"null",
";",
"}"
]
| Returns a resource.
@param languageSlug {string}
@param projectSlug {string}
@param resourceSlug {string}
@returns {{}|null} the resource object or null if it does not exist | [
"Returns",
"a",
"resource",
"."
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/lib/library.js#L742-L789 |
|
41,846 | unfoldingWord-dev/node-door43-client | lib/library.js | function(languageSlug, versificationSlug) {
let result = query('' +
'select vn.name, v.slug, v.id from versification_name as vn' +
' left join versification as v on v.id=vn.versification_id' +
' left join source_language as sl on sl.id=vn.source_language_id' +
' where sl.slug=? and v.slug=?', [languageSlug, versificationSlug]);
if(result.length > 0) {
return result[0];
}
return null;
} | javascript | function(languageSlug, versificationSlug) {
let result = query('' +
'select vn.name, v.slug, v.id from versification_name as vn' +
' left join versification as v on v.id=vn.versification_id' +
' left join source_language as sl on sl.id=vn.source_language_id' +
' where sl.slug=? and v.slug=?', [languageSlug, versificationSlug]);
if(result.length > 0) {
return result[0];
}
return null;
} | [
"function",
"(",
"languageSlug",
",",
"versificationSlug",
")",
"{",
"let",
"result",
"=",
"query",
"(",
"''",
"+",
"'select vn.name, v.slug, v.id from versification_name as vn'",
"+",
"' left join versification as v on v.id=vn.versification_id'",
"+",
"' left join source_language as sl on sl.id=vn.source_language_id'",
"+",
"' where sl.slug=? and v.slug=?'",
",",
"[",
"languageSlug",
",",
"versificationSlug",
"]",
")",
";",
"if",
"(",
"result",
".",
"length",
">",
"0",
")",
"{",
"return",
"result",
"[",
"0",
"]",
";",
"}",
"return",
"null",
";",
"}"
]
| Returns a versification.
@param languageSlug {string}
@param versificationSlug {string}
@returns {{}|null} | [
"Returns",
"a",
"versification",
"."
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/lib/library.js#L946-L956 |
|
41,847 | unfoldingWord-dev/node-door43-client | lib/library.js | function(tdId) {
let result = query('select * from questionnaire where td_id=?', [tdId]);
if(result.length > 0) {
let questionnaire = result[0];
questionnaire.language_data = {};
// load data fields
let dataResults = query('select field, question_td_id from questionnaire_data_field where questionnaire_id=?',
[questionnaire.id]);
for(let data of dataResults) {
questionnaire.language_data[data.field] = data.question_td_id;
}
return questionnaire;
}
return null;
} | javascript | function(tdId) {
let result = query('select * from questionnaire where td_id=?', [tdId]);
if(result.length > 0) {
let questionnaire = result[0];
questionnaire.language_data = {};
// load data fields
let dataResults = query('select field, question_td_id from questionnaire_data_field where questionnaire_id=?',
[questionnaire.id]);
for(let data of dataResults) {
questionnaire.language_data[data.field] = data.question_td_id;
}
return questionnaire;
}
return null;
} | [
"function",
"(",
"tdId",
")",
"{",
"let",
"result",
"=",
"query",
"(",
"'select * from questionnaire where td_id=?'",
",",
"[",
"tdId",
"]",
")",
";",
"if",
"(",
"result",
".",
"length",
">",
"0",
")",
"{",
"let",
"questionnaire",
"=",
"result",
"[",
"0",
"]",
";",
"questionnaire",
".",
"language_data",
"=",
"{",
"}",
";",
"// load data fields",
"let",
"dataResults",
"=",
"query",
"(",
"'select field, question_td_id from questionnaire_data_field where questionnaire_id=?'",
",",
"[",
"questionnaire",
".",
"id",
"]",
")",
";",
"for",
"(",
"let",
"data",
"of",
"dataResults",
")",
"{",
"questionnaire",
".",
"language_data",
"[",
"data",
".",
"field",
"]",
"=",
"data",
".",
"question_td_id",
";",
"}",
"return",
"questionnaire",
";",
"}",
"return",
"null",
";",
"}"
]
| Returns a single questionnaire
@param tdId {string} the translation database id of the questionnaire | [
"Returns",
"a",
"single",
"questionnaire"
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/lib/library.js#L990-L1005 |
|
41,848 | unfoldingWord-dev/node-door43-client | lib/library.js | function() {
let results = query('select * from questionnaire');
for(let questionnaire of results) {
// load data fields
questionnaire.language_data = {};
let dataResults = query('select field, question_td_id from questionnaire_data_field where questionnaire_id=?',
[questionnaire.id]);
for(let data of dataResults) {
questionnaire.language_data[data.field] = data.question_td_id;
}
}
return results;
} | javascript | function() {
let results = query('select * from questionnaire');
for(let questionnaire of results) {
// load data fields
questionnaire.language_data = {};
let dataResults = query('select field, question_td_id from questionnaire_data_field where questionnaire_id=?',
[questionnaire.id]);
for(let data of dataResults) {
questionnaire.language_data[data.field] = data.question_td_id;
}
}
return results;
} | [
"function",
"(",
")",
"{",
"let",
"results",
"=",
"query",
"(",
"'select * from questionnaire'",
")",
";",
"for",
"(",
"let",
"questionnaire",
"of",
"results",
")",
"{",
"// load data fields",
"questionnaire",
".",
"language_data",
"=",
"{",
"}",
";",
"let",
"dataResults",
"=",
"query",
"(",
"'select field, question_td_id from questionnaire_data_field where questionnaire_id=?'",
",",
"[",
"questionnaire",
".",
"id",
"]",
")",
";",
"for",
"(",
"let",
"data",
"of",
"dataResults",
")",
"{",
"questionnaire",
".",
"language_data",
"[",
"data",
".",
"field",
"]",
"=",
"data",
".",
"question_td_id",
";",
"}",
"}",
"return",
"results",
";",
"}"
]
| Returns a list of questionnaires.
@returns {[{}]} a list of questionnaires | [
"Returns",
"a",
"list",
"of",
"questionnaires",
"."
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/lib/library.js#L1012-L1025 |
|
41,849 | unfoldingWord-dev/node-door43-client | lib/library.js | function(language_slug, project_slug, resource_slug, resource_type, translate_mode, min_checking_level, max_checking_level) {
let condition_max_checking = '';
language_slug = language_slug || '%';
project_slug = project_slug || '%';
resource_slug = resource_slug || '%';
resource_type = resource_type || '%';
translate_mode = translate_mode || '%';
min_checking_level = min_checking_level || 0;
max_checking_level = max_checking_level || -1;
if(max_checking_level >= 0) condition_max_checking = ' and r.checking_level <= ' + max_checking_level;
let translations = [];
let results = query("select l.slug as language_slug, l.name as language_name, l.direction," +
" p.slug as project_slug, p.category_id, p.name as project_name, p.desc, p.icon, p.sort, p.chunks_url," +
" r.id as resource_id, r.slug as resource_slug, r.name as resource_name, r.type, r.translate_mode, r.checking_level, r.comments, r.pub_date, r.license, r.version," +
" lri.translation_words_assignments_url," +
" c.slug as category_slug " +
" from source_language as l" +
" left join project as p on p.source_language_id=l.id" +
" left join resource as r on r.project_id=p.id" +
" left join legacy_resource_info as lri on lri.resource_id=r.id" +
" left join category as c on c.id=p.category_id" +
" where l.slug like(?) and p.slug like(?) and r.slug like(?)" +
" and r.checking_level >= ?" +
condition_max_checking +
" and r.type like(?) and r.translate_mode like(?)", [language_slug, project_slug, resource_slug, min_checking_level, resource_type, translate_mode]);
for(let r of results) {
let trans = {
language: {
slug: r.language_slug,
name: r.language_name,
direction: r.direction
},
project: {
slug: r.project_slug,
name: r.project_name,
desc: r.desc,
sort: r.sort,
icon: r.icon,
chunks_url: r.chunks_url,
source_language_slug: r.language_slug,
category_id: r.category_id,
category_slug: r.category_slug
},
resource: {
slug: r.resource_slug,
name: r.resource_name,
type: r.type,
status: {
translate_mode: r.translate_mode,
checking_level: r.checking_level,
comments: r.comments,
pub_date: r.pub_date,
license: r.license,
version: r.version
},
project_slug: r.project_slug,
source_language_slug: r.language_slug
}
};
// load formats and add to resource
let formats = [];
let formatResults = query('select * from resource_format' +
' where resource_id=?', [r.resource_id]);
let imported = false;
for(let f of formatResults) {
delete f.id;
delete f.resource_id;
f.imported = !!f.imported;
formats.push(f);
// TRICKY: this is not technically correct, but for convenience we attach the import status to the resource directly
if(f.imported) imported = true;
}
trans.resource.formats = formats;
trans.resource.imported = imported;
translations.push(trans);
}
return translations;
} | javascript | function(language_slug, project_slug, resource_slug, resource_type, translate_mode, min_checking_level, max_checking_level) {
let condition_max_checking = '';
language_slug = language_slug || '%';
project_slug = project_slug || '%';
resource_slug = resource_slug || '%';
resource_type = resource_type || '%';
translate_mode = translate_mode || '%';
min_checking_level = min_checking_level || 0;
max_checking_level = max_checking_level || -1;
if(max_checking_level >= 0) condition_max_checking = ' and r.checking_level <= ' + max_checking_level;
let translations = [];
let results = query("select l.slug as language_slug, l.name as language_name, l.direction," +
" p.slug as project_slug, p.category_id, p.name as project_name, p.desc, p.icon, p.sort, p.chunks_url," +
" r.id as resource_id, r.slug as resource_slug, r.name as resource_name, r.type, r.translate_mode, r.checking_level, r.comments, r.pub_date, r.license, r.version," +
" lri.translation_words_assignments_url," +
" c.slug as category_slug " +
" from source_language as l" +
" left join project as p on p.source_language_id=l.id" +
" left join resource as r on r.project_id=p.id" +
" left join legacy_resource_info as lri on lri.resource_id=r.id" +
" left join category as c on c.id=p.category_id" +
" where l.slug like(?) and p.slug like(?) and r.slug like(?)" +
" and r.checking_level >= ?" +
condition_max_checking +
" and r.type like(?) and r.translate_mode like(?)", [language_slug, project_slug, resource_slug, min_checking_level, resource_type, translate_mode]);
for(let r of results) {
let trans = {
language: {
slug: r.language_slug,
name: r.language_name,
direction: r.direction
},
project: {
slug: r.project_slug,
name: r.project_name,
desc: r.desc,
sort: r.sort,
icon: r.icon,
chunks_url: r.chunks_url,
source_language_slug: r.language_slug,
category_id: r.category_id,
category_slug: r.category_slug
},
resource: {
slug: r.resource_slug,
name: r.resource_name,
type: r.type,
status: {
translate_mode: r.translate_mode,
checking_level: r.checking_level,
comments: r.comments,
pub_date: r.pub_date,
license: r.license,
version: r.version
},
project_slug: r.project_slug,
source_language_slug: r.language_slug
}
};
// load formats and add to resource
let formats = [];
let formatResults = query('select * from resource_format' +
' where resource_id=?', [r.resource_id]);
let imported = false;
for(let f of formatResults) {
delete f.id;
delete f.resource_id;
f.imported = !!f.imported;
formats.push(f);
// TRICKY: this is not technically correct, but for convenience we attach the import status to the resource directly
if(f.imported) imported = true;
}
trans.resource.formats = formats;
trans.resource.imported = imported;
translations.push(trans);
}
return translations;
} | [
"function",
"(",
"language_slug",
",",
"project_slug",
",",
"resource_slug",
",",
"resource_type",
",",
"translate_mode",
",",
"min_checking_level",
",",
"max_checking_level",
")",
"{",
"let",
"condition_max_checking",
"=",
"''",
";",
"language_slug",
"=",
"language_slug",
"||",
"'%'",
";",
"project_slug",
"=",
"project_slug",
"||",
"'%'",
";",
"resource_slug",
"=",
"resource_slug",
"||",
"'%'",
";",
"resource_type",
"=",
"resource_type",
"||",
"'%'",
";",
"translate_mode",
"=",
"translate_mode",
"||",
"'%'",
";",
"min_checking_level",
"=",
"min_checking_level",
"||",
"0",
";",
"max_checking_level",
"=",
"max_checking_level",
"||",
"-",
"1",
";",
"if",
"(",
"max_checking_level",
">=",
"0",
")",
"condition_max_checking",
"=",
"' and r.checking_level <= '",
"+",
"max_checking_level",
";",
"let",
"translations",
"=",
"[",
"]",
";",
"let",
"results",
"=",
"query",
"(",
"\"select l.slug as language_slug, l.name as language_name, l.direction,\"",
"+",
"\" p.slug as project_slug, p.category_id, p.name as project_name, p.desc, p.icon, p.sort, p.chunks_url,\"",
"+",
"\" r.id as resource_id, r.slug as resource_slug, r.name as resource_name, r.type, r.translate_mode, r.checking_level, r.comments, r.pub_date, r.license, r.version,\"",
"+",
"\" lri.translation_words_assignments_url,\"",
"+",
"\" c.slug as category_slug \"",
"+",
"\" from source_language as l\"",
"+",
"\" left join project as p on p.source_language_id=l.id\"",
"+",
"\" left join resource as r on r.project_id=p.id\"",
"+",
"\" left join legacy_resource_info as lri on lri.resource_id=r.id\"",
"+",
"\" left join category as c on c.id=p.category_id\"",
"+",
"\" where l.slug like(?) and p.slug like(?) and r.slug like(?)\"",
"+",
"\" and r.checking_level >= ?\"",
"+",
"condition_max_checking",
"+",
"\" and r.type like(?) and r.translate_mode like(?)\"",
",",
"[",
"language_slug",
",",
"project_slug",
",",
"resource_slug",
",",
"min_checking_level",
",",
"resource_type",
",",
"translate_mode",
"]",
")",
";",
"for",
"(",
"let",
"r",
"of",
"results",
")",
"{",
"let",
"trans",
"=",
"{",
"language",
":",
"{",
"slug",
":",
"r",
".",
"language_slug",
",",
"name",
":",
"r",
".",
"language_name",
",",
"direction",
":",
"r",
".",
"direction",
"}",
",",
"project",
":",
"{",
"slug",
":",
"r",
".",
"project_slug",
",",
"name",
":",
"r",
".",
"project_name",
",",
"desc",
":",
"r",
".",
"desc",
",",
"sort",
":",
"r",
".",
"sort",
",",
"icon",
":",
"r",
".",
"icon",
",",
"chunks_url",
":",
"r",
".",
"chunks_url",
",",
"source_language_slug",
":",
"r",
".",
"language_slug",
",",
"category_id",
":",
"r",
".",
"category_id",
",",
"category_slug",
":",
"r",
".",
"category_slug",
"}",
",",
"resource",
":",
"{",
"slug",
":",
"r",
".",
"resource_slug",
",",
"name",
":",
"r",
".",
"resource_name",
",",
"type",
":",
"r",
".",
"type",
",",
"status",
":",
"{",
"translate_mode",
":",
"r",
".",
"translate_mode",
",",
"checking_level",
":",
"r",
".",
"checking_level",
",",
"comments",
":",
"r",
".",
"comments",
",",
"pub_date",
":",
"r",
".",
"pub_date",
",",
"license",
":",
"r",
".",
"license",
",",
"version",
":",
"r",
".",
"version",
"}",
",",
"project_slug",
":",
"r",
".",
"project_slug",
",",
"source_language_slug",
":",
"r",
".",
"language_slug",
"}",
"}",
";",
"// load formats and add to resource",
"let",
"formats",
"=",
"[",
"]",
";",
"let",
"formatResults",
"=",
"query",
"(",
"'select * from resource_format'",
"+",
"' where resource_id=?'",
",",
"[",
"r",
".",
"resource_id",
"]",
")",
";",
"let",
"imported",
"=",
"false",
";",
"for",
"(",
"let",
"f",
"of",
"formatResults",
")",
"{",
"delete",
"f",
".",
"id",
";",
"delete",
"f",
".",
"resource_id",
";",
"f",
".",
"imported",
"=",
"!",
"!",
"f",
".",
"imported",
";",
"formats",
".",
"push",
"(",
"f",
")",
";",
"// TRICKY: this is not technically correct, but for convenience we attach the import status to the resource directly",
"if",
"(",
"f",
".",
"imported",
")",
"imported",
"=",
"true",
";",
"}",
"trans",
".",
"resource",
".",
"formats",
"=",
"formats",
";",
"trans",
".",
"resource",
".",
"imported",
"=",
"imported",
";",
"translations",
".",
"push",
"(",
"trans",
")",
";",
"}",
"return",
"translations",
";",
"}"
]
| Return sa list of translations.
@param language_slug string the language these translations are available in. Leave null for all.
@param project_slug string the project for whom these translations are available. Leave null for all.
@param resource_slug string the resource for whom these translations are available. Leave null for all.
@param resource_type string the resource type allowed for returned translations. Leave null for all.
@param translate_mode string limit results to just those with the given translate mode. Leave null for all.
@param min_checking_level int the minimum checking level allowed for returned translations. Use 0 for no minimum.
@param max_checking_level int the maximum checking level allowed for returned translations. Use -1 for no maximum. | [
"Return",
"sa",
"list",
"of",
"translations",
"."
]
| 18f518368ee89f4baf8943500a1c53ef5efcfb3e | https://github.com/unfoldingWord-dev/node-door43-client/blob/18f518368ee89f4baf8943500a1c53ef5efcfb3e/lib/library.js#L1048-L1131 |
|
41,850 | DavidSouther/JEFRi | modeler/angular/app/scripts/lib/$/select2/dev.js | equal | function equal(a, b) {
if (a === b) return true;
if (a === undefined || b === undefined) return false;
if (a === null || b === null) return false;
if (a.constructor === String) return a.localeCompare(b) === 0;
if (b.constructor === String) return b.localeCompare(a) === 0;
return false;
} | javascript | function equal(a, b) {
if (a === b) return true;
if (a === undefined || b === undefined) return false;
if (a === null || b === null) return false;
if (a.constructor === String) return a.localeCompare(b) === 0;
if (b.constructor === String) return b.localeCompare(a) === 0;
return false;
} | [
"function",
"equal",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"a",
"===",
"b",
")",
"return",
"true",
";",
"if",
"(",
"a",
"===",
"undefined",
"||",
"b",
"===",
"undefined",
")",
"return",
"false",
";",
"if",
"(",
"a",
"===",
"null",
"||",
"b",
"===",
"null",
")",
"return",
"false",
";",
"if",
"(",
"a",
".",
"constructor",
"===",
"String",
")",
"return",
"a",
".",
"localeCompare",
"(",
"b",
")",
"===",
"0",
";",
"if",
"(",
"b",
".",
"constructor",
"===",
"String",
")",
"return",
"b",
".",
"localeCompare",
"(",
"a",
")",
"===",
"0",
";",
"return",
"false",
";",
"}"
]
| Compares equality of a and b taking into account that a and b may be strings, in which case localeCompare is used
@param a
@param b | [
"Compares",
"equality",
"of",
"a",
"and",
"b",
"taking",
"into",
"account",
"that",
"a",
"and",
"b",
"may",
"be",
"strings",
"in",
"which",
"case",
"localeCompare",
"is",
"used"
]
| 161f24e242e05b9b2114cc1123a257141a60eaf2 | https://github.com/DavidSouther/JEFRi/blob/161f24e242e05b9b2114cc1123a257141a60eaf2/modeler/angular/app/scripts/lib/$/select2/dev.js#L122-L129 |
41,851 | DavidSouther/JEFRi | modeler/angular/app/scripts/lib/$/select2/dev.js | installFilteredMouseMove | function installFilteredMouseMove(element) {
element.bind("mousemove", function (e) {
var lastpos = $.data(document, "select2-lastpos");
if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
$(e.target).trigger("mousemove-filtered", e);
}
});
} | javascript | function installFilteredMouseMove(element) {
element.bind("mousemove", function (e) {
var lastpos = $.data(document, "select2-lastpos");
if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
$(e.target).trigger("mousemove-filtered", e);
}
});
} | [
"function",
"installFilteredMouseMove",
"(",
"element",
")",
"{",
"element",
".",
"bind",
"(",
"\"mousemove\"",
",",
"function",
"(",
"e",
")",
"{",
"var",
"lastpos",
"=",
"$",
".",
"data",
"(",
"document",
",",
"\"select2-lastpos\"",
")",
";",
"if",
"(",
"lastpos",
"===",
"undefined",
"||",
"lastpos",
".",
"x",
"!==",
"e",
".",
"pageX",
"||",
"lastpos",
".",
"y",
"!==",
"e",
".",
"pageY",
")",
"{",
"$",
"(",
"e",
".",
"target",
")",
".",
"trigger",
"(",
"\"mousemove-filtered\"",
",",
"e",
")",
";",
"}",
"}",
")",
";",
"}"
]
| filters mouse events so an event is fired only if the mouse moved.
filters out mouse events that occur when mouse is stationary but
the elements under the pointer are scrolled. | [
"filters",
"mouse",
"events",
"so",
"an",
"event",
"is",
"fired",
"only",
"if",
"the",
"mouse",
"moved",
"."
]
| 161f24e242e05b9b2114cc1123a257141a60eaf2 | https://github.com/DavidSouther/JEFRi/blob/161f24e242e05b9b2114cc1123a257141a60eaf2/modeler/angular/app/scripts/lib/$/select2/dev.js#L175-L182 |
41,852 | DavidSouther/JEFRi | modeler/angular/app/scripts/lib/$/select2/dev.js | ajax | function ajax(options) {
var timeout, // current scheduled but not yet executed request
requestSequence = 0, // sequence used to drop out-of-order responses
handler = null,
quietMillis = options.quietMillis || 100;
return function (query) {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
requestSequence += 1; // increment the sequence
var requestNumber = requestSequence, // this request's sequence number
data = options.data, // ajax data function
transport = options.transport || $.ajax,
traditional = options.traditional || false,
type = options.type || 'GET'; // set type of request (GET or POST)
data = data.call(this, query.term, query.page, query.context);
if( null !== handler) { handler.abort(); }
handler = transport.call(null, {
url: options.url,
dataType: options.dataType,
data: data,
type: type,
traditional: traditional,
success: function (data) {
if (requestNumber < requestSequence) {
return;
}
// TODO 3.0 - replace query.page with query so users have access to term, page, etc.
var results = options.results(data, query.page);
query.callback(results);
}
});
}, quietMillis);
};
} | javascript | function ajax(options) {
var timeout, // current scheduled but not yet executed request
requestSequence = 0, // sequence used to drop out-of-order responses
handler = null,
quietMillis = options.quietMillis || 100;
return function (query) {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
requestSequence += 1; // increment the sequence
var requestNumber = requestSequence, // this request's sequence number
data = options.data, // ajax data function
transport = options.transport || $.ajax,
traditional = options.traditional || false,
type = options.type || 'GET'; // set type of request (GET or POST)
data = data.call(this, query.term, query.page, query.context);
if( null !== handler) { handler.abort(); }
handler = transport.call(null, {
url: options.url,
dataType: options.dataType,
data: data,
type: type,
traditional: traditional,
success: function (data) {
if (requestNumber < requestSequence) {
return;
}
// TODO 3.0 - replace query.page with query so users have access to term, page, etc.
var results = options.results(data, query.page);
query.callback(results);
}
});
}, quietMillis);
};
} | [
"function",
"ajax",
"(",
"options",
")",
"{",
"var",
"timeout",
",",
"// current scheduled but not yet executed request",
"requestSequence",
"=",
"0",
",",
"// sequence used to drop out-of-order responses",
"handler",
"=",
"null",
",",
"quietMillis",
"=",
"options",
".",
"quietMillis",
"||",
"100",
";",
"return",
"function",
"(",
"query",
")",
"{",
"window",
".",
"clearTimeout",
"(",
"timeout",
")",
";",
"timeout",
"=",
"window",
".",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"requestSequence",
"+=",
"1",
";",
"// increment the sequence",
"var",
"requestNumber",
"=",
"requestSequence",
",",
"// this request's sequence number",
"data",
"=",
"options",
".",
"data",
",",
"// ajax data function",
"transport",
"=",
"options",
".",
"transport",
"||",
"$",
".",
"ajax",
",",
"traditional",
"=",
"options",
".",
"traditional",
"||",
"false",
",",
"type",
"=",
"options",
".",
"type",
"||",
"'GET'",
";",
"// set type of request (GET or POST)",
"data",
"=",
"data",
".",
"call",
"(",
"this",
",",
"query",
".",
"term",
",",
"query",
".",
"page",
",",
"query",
".",
"context",
")",
";",
"if",
"(",
"null",
"!==",
"handler",
")",
"{",
"handler",
".",
"abort",
"(",
")",
";",
"}",
"handler",
"=",
"transport",
".",
"call",
"(",
"null",
",",
"{",
"url",
":",
"options",
".",
"url",
",",
"dataType",
":",
"options",
".",
"dataType",
",",
"data",
":",
"data",
",",
"type",
":",
"type",
",",
"traditional",
":",
"traditional",
",",
"success",
":",
"function",
"(",
"data",
")",
"{",
"if",
"(",
"requestNumber",
"<",
"requestSequence",
")",
"{",
"return",
";",
"}",
"// TODO 3.0 - replace query.page with query so users have access to term, page, etc.",
"var",
"results",
"=",
"options",
".",
"results",
"(",
"data",
",",
"query",
".",
"page",
")",
";",
"query",
".",
"callback",
"(",
"results",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"quietMillis",
")",
";",
"}",
";",
"}"
]
| Produces an ajax-based query function
@param options object containing configuration paramters
@param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
@param options.url url for the data
@param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
@param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified
@param options.traditional a boolean flag that should be true if you wish to use the traditional style of param serialization for the ajax request
@param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
@param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
The expected format is an object containing the following keys:
results array of objects that will be used as choices
more (optional) boolean indicating whether there are more results available
Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true} | [
"Produces",
"an",
"ajax",
"-",
"based",
"query",
"function"
]
| 161f24e242e05b9b2114cc1123a257141a60eaf2 | https://github.com/DavidSouther/JEFRi/blob/161f24e242e05b9b2114cc1123a257141a60eaf2/modeler/angular/app/scripts/lib/$/select2/dev.js#L285-L322 |
41,853 | DavidSouther/JEFRi | modeler/angular/app/scripts/lib/$/select2/dev.js | local | function local(options) {
var data = options, // data elements
dataText,
text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
if (!$.isArray(data)) {
text = data.text;
// if text is not a function we assume it to be a key name
if (!$.isFunction(text)) {
dataText = data.text; // we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available
text = function (item) { return item[dataText]; };
}
data = data.results;
}
return function (query) {
var t = query.term, filtered = { results: [] }, process;
if (t === "") {
query.callback({results: data});
return;
}
process = function(datum, collection) {
var group, attr;
datum = datum[0];
if (datum.children) {
group = {};
for (attr in datum) {
if (datum.hasOwnProperty(attr)) group[attr]=datum[attr];
}
group.children=[];
$(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
if (group.children.length) {
collection.push(group);
}
} else {
if (query.matcher(t, text(datum))) {
collection.push(datum);
}
}
};
$(data).each2(function(i, datum) { process(datum, filtered.results); });
query.callback(filtered);
};
} | javascript | function local(options) {
var data = options, // data elements
dataText,
text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
if (!$.isArray(data)) {
text = data.text;
// if text is not a function we assume it to be a key name
if (!$.isFunction(text)) {
dataText = data.text; // we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available
text = function (item) { return item[dataText]; };
}
data = data.results;
}
return function (query) {
var t = query.term, filtered = { results: [] }, process;
if (t === "") {
query.callback({results: data});
return;
}
process = function(datum, collection) {
var group, attr;
datum = datum[0];
if (datum.children) {
group = {};
for (attr in datum) {
if (datum.hasOwnProperty(attr)) group[attr]=datum[attr];
}
group.children=[];
$(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
if (group.children.length) {
collection.push(group);
}
} else {
if (query.matcher(t, text(datum))) {
collection.push(datum);
}
}
};
$(data).each2(function(i, datum) { process(datum, filtered.results); });
query.callback(filtered);
};
} | [
"function",
"local",
"(",
"options",
")",
"{",
"var",
"data",
"=",
"options",
",",
"// data elements",
"dataText",
",",
"text",
"=",
"function",
"(",
"item",
")",
"{",
"return",
"\"\"",
"+",
"item",
".",
"text",
";",
"}",
";",
"// function used to retrieve the text portion of a data item that is matched against the search",
"if",
"(",
"!",
"$",
".",
"isArray",
"(",
"data",
")",
")",
"{",
"text",
"=",
"data",
".",
"text",
";",
"// if text is not a function we assume it to be a key name",
"if",
"(",
"!",
"$",
".",
"isFunction",
"(",
"text",
")",
")",
"{",
"dataText",
"=",
"data",
".",
"text",
";",
"// we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available",
"text",
"=",
"function",
"(",
"item",
")",
"{",
"return",
"item",
"[",
"dataText",
"]",
";",
"}",
";",
"}",
"data",
"=",
"data",
".",
"results",
";",
"}",
"return",
"function",
"(",
"query",
")",
"{",
"var",
"t",
"=",
"query",
".",
"term",
",",
"filtered",
"=",
"{",
"results",
":",
"[",
"]",
"}",
",",
"process",
";",
"if",
"(",
"t",
"===",
"\"\"",
")",
"{",
"query",
".",
"callback",
"(",
"{",
"results",
":",
"data",
"}",
")",
";",
"return",
";",
"}",
"process",
"=",
"function",
"(",
"datum",
",",
"collection",
")",
"{",
"var",
"group",
",",
"attr",
";",
"datum",
"=",
"datum",
"[",
"0",
"]",
";",
"if",
"(",
"datum",
".",
"children",
")",
"{",
"group",
"=",
"{",
"}",
";",
"for",
"(",
"attr",
"in",
"datum",
")",
"{",
"if",
"(",
"datum",
".",
"hasOwnProperty",
"(",
"attr",
")",
")",
"group",
"[",
"attr",
"]",
"=",
"datum",
"[",
"attr",
"]",
";",
"}",
"group",
".",
"children",
"=",
"[",
"]",
";",
"$",
"(",
"datum",
".",
"children",
")",
".",
"each2",
"(",
"function",
"(",
"i",
",",
"childDatum",
")",
"{",
"process",
"(",
"childDatum",
",",
"group",
".",
"children",
")",
";",
"}",
")",
";",
"if",
"(",
"group",
".",
"children",
".",
"length",
")",
"{",
"collection",
".",
"push",
"(",
"group",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"query",
".",
"matcher",
"(",
"t",
",",
"text",
"(",
"datum",
")",
")",
")",
"{",
"collection",
".",
"push",
"(",
"datum",
")",
";",
"}",
"}",
"}",
";",
"$",
"(",
"data",
")",
".",
"each2",
"(",
"function",
"(",
"i",
",",
"datum",
")",
"{",
"process",
"(",
"datum",
",",
"filtered",
".",
"results",
")",
";",
"}",
")",
";",
"query",
".",
"callback",
"(",
"filtered",
")",
";",
"}",
";",
"}"
]
| Produces a query function that works with a local array
@param options object containing configuration parameters. The options parameter can either be an array or an
object.
If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
key can either be a String in which case it is expected that each element in the 'data' array has a key with the
value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
the text. | [
"Produces",
"a",
"query",
"function",
"that",
"works",
"with",
"a",
"local",
"array"
]
| 161f24e242e05b9b2114cc1123a257141a60eaf2 | https://github.com/DavidSouther/JEFRi/blob/161f24e242e05b9b2114cc1123a257141a60eaf2/modeler/angular/app/scripts/lib/$/select2/dev.js#L338-L383 |
41,854 | DavidSouther/JEFRi | modeler/angular/app/scripts/lib/$/select2/dev.js | function () {
function resolveContainerWidth() {
var style, attrs, matches, i, l;
if (this.opts.width === "off") {
return null;
} else if (this.opts.width === "element"){
return this.opts.element.outerWidth() === 0 ? 'auto' : this.opts.element.outerWidth() + 'px';
} else if (this.opts.width === "copy" || this.opts.width === "resolve") {
// check if there is inline style on the element that contains width
style = this.opts.element.attr('style');
if (style !== undefined) {
attrs = style.split(';');
for (i = 0, l = attrs.length; i < l; i = i + 1) {
matches = attrs[i].replace(/\s/g, '')
.match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
if (matches !== null && matches.length >= 1)
return matches[1];
}
}
if (this.opts.width === "resolve") {
// next check if css('width') can resolve a width that is percent based, this is sometimes possible
// when attached to input type=hidden or elements hidden via css
style = this.opts.element.css('width');
if (style.indexOf("%") > 0) return style;
// finally, fallback on the calculated width of the element
return (this.opts.element.outerWidth() === 0 ? 'auto' : this.opts.element.outerWidth() + 'px');
}
return null;
} else if ($.isFunction(this.opts.width)) {
return this.opts.width();
} else {
return this.opts.width;
}
};
var width = resolveContainerWidth.call(this);
if (width !== null) {
this.container.attr("style", "width: "+width);
}
} | javascript | function () {
function resolveContainerWidth() {
var style, attrs, matches, i, l;
if (this.opts.width === "off") {
return null;
} else if (this.opts.width === "element"){
return this.opts.element.outerWidth() === 0 ? 'auto' : this.opts.element.outerWidth() + 'px';
} else if (this.opts.width === "copy" || this.opts.width === "resolve") {
// check if there is inline style on the element that contains width
style = this.opts.element.attr('style');
if (style !== undefined) {
attrs = style.split(';');
for (i = 0, l = attrs.length; i < l; i = i + 1) {
matches = attrs[i].replace(/\s/g, '')
.match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
if (matches !== null && matches.length >= 1)
return matches[1];
}
}
if (this.opts.width === "resolve") {
// next check if css('width') can resolve a width that is percent based, this is sometimes possible
// when attached to input type=hidden or elements hidden via css
style = this.opts.element.css('width');
if (style.indexOf("%") > 0) return style;
// finally, fallback on the calculated width of the element
return (this.opts.element.outerWidth() === 0 ? 'auto' : this.opts.element.outerWidth() + 'px');
}
return null;
} else if ($.isFunction(this.opts.width)) {
return this.opts.width();
} else {
return this.opts.width;
}
};
var width = resolveContainerWidth.call(this);
if (width !== null) {
this.container.attr("style", "width: "+width);
}
} | [
"function",
"(",
")",
"{",
"function",
"resolveContainerWidth",
"(",
")",
"{",
"var",
"style",
",",
"attrs",
",",
"matches",
",",
"i",
",",
"l",
";",
"if",
"(",
"this",
".",
"opts",
".",
"width",
"===",
"\"off\"",
")",
"{",
"return",
"null",
";",
"}",
"else",
"if",
"(",
"this",
".",
"opts",
".",
"width",
"===",
"\"element\"",
")",
"{",
"return",
"this",
".",
"opts",
".",
"element",
".",
"outerWidth",
"(",
")",
"===",
"0",
"?",
"'auto'",
":",
"this",
".",
"opts",
".",
"element",
".",
"outerWidth",
"(",
")",
"+",
"'px'",
";",
"}",
"else",
"if",
"(",
"this",
".",
"opts",
".",
"width",
"===",
"\"copy\"",
"||",
"this",
".",
"opts",
".",
"width",
"===",
"\"resolve\"",
")",
"{",
"// check if there is inline style on the element that contains width",
"style",
"=",
"this",
".",
"opts",
".",
"element",
".",
"attr",
"(",
"'style'",
")",
";",
"if",
"(",
"style",
"!==",
"undefined",
")",
"{",
"attrs",
"=",
"style",
".",
"split",
"(",
"';'",
")",
";",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"attrs",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"=",
"i",
"+",
"1",
")",
"{",
"matches",
"=",
"attrs",
"[",
"i",
"]",
".",
"replace",
"(",
"/",
"\\s",
"/",
"g",
",",
"''",
")",
".",
"match",
"(",
"/",
"width:(([-+]?([0-9]*\\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))",
"/",
")",
";",
"if",
"(",
"matches",
"!==",
"null",
"&&",
"matches",
".",
"length",
">=",
"1",
")",
"return",
"matches",
"[",
"1",
"]",
";",
"}",
"}",
"if",
"(",
"this",
".",
"opts",
".",
"width",
"===",
"\"resolve\"",
")",
"{",
"// next check if css('width') can resolve a width that is percent based, this is sometimes possible",
"// when attached to input type=hidden or elements hidden via css",
"style",
"=",
"this",
".",
"opts",
".",
"element",
".",
"css",
"(",
"'width'",
")",
";",
"if",
"(",
"style",
".",
"indexOf",
"(",
"\"%\"",
")",
">",
"0",
")",
"return",
"style",
";",
"// finally, fallback on the calculated width of the element",
"return",
"(",
"this",
".",
"opts",
".",
"element",
".",
"outerWidth",
"(",
")",
"===",
"0",
"?",
"'auto'",
":",
"this",
".",
"opts",
".",
"element",
".",
"outerWidth",
"(",
")",
"+",
"'px'",
")",
";",
"}",
"return",
"null",
";",
"}",
"else",
"if",
"(",
"$",
".",
"isFunction",
"(",
"this",
".",
"opts",
".",
"width",
")",
")",
"{",
"return",
"this",
".",
"opts",
".",
"width",
"(",
")",
";",
"}",
"else",
"{",
"return",
"this",
".",
"opts",
".",
"width",
";",
"}",
"}",
";",
"var",
"width",
"=",
"resolveContainerWidth",
".",
"call",
"(",
"this",
")",
";",
"if",
"(",
"width",
"!==",
"null",
")",
"{",
"this",
".",
"container",
".",
"attr",
"(",
"\"style\"",
",",
"\"width: \"",
"+",
"width",
")",
";",
"}",
"}"
]
| Get the desired width for the container element. This is
derived first from option `width` passed to select2, then
the inline 'style' on the original element, and finally
falls back to the jQuery calculated element width.
abstract | [
"Get",
"the",
"desired",
"width",
"for",
"the",
"container",
"element",
".",
"This",
"is",
"derived",
"first",
"from",
"option",
"width",
"passed",
"to",
"select2",
"then",
"the",
"inline",
"style",
"on",
"the",
"original",
"element",
"and",
"finally",
"falls",
"back",
"to",
"the",
"jQuery",
"calculated",
"element",
"width",
".",
"abstract"
]
| 161f24e242e05b9b2114cc1123a257141a60eaf2 | https://github.com/DavidSouther/JEFRi/blob/161f24e242e05b9b2114cc1123a257141a60eaf2/modeler/angular/app/scripts/lib/$/select2/dev.js#L1326-L1369 |
|
41,855 | Runnable/monitor-dog | lib/interval-monitor.js | IntervalMonitor | function IntervalMonitor(monitor, prefix, interval) {
this.monitor = monitor;
this.prefix = prefix || this.monitor.prefix;
this.interval = interval || this.monitor.interval;
} | javascript | function IntervalMonitor(monitor, prefix, interval) {
this.monitor = monitor;
this.prefix = prefix || this.monitor.prefix;
this.interval = interval || this.monitor.interval;
} | [
"function",
"IntervalMonitor",
"(",
"monitor",
",",
"prefix",
",",
"interval",
")",
"{",
"this",
".",
"monitor",
"=",
"monitor",
";",
"this",
".",
"prefix",
"=",
"prefix",
"||",
"this",
".",
"monitor",
".",
"prefix",
";",
"this",
".",
"interval",
"=",
"interval",
"||",
"this",
".",
"monitor",
".",
"interval",
";",
"}"
]
| Abstract base class for all types of specialized monitors that report
information periodically over a given interval.
@param {monitor-dog.Monitor} Base monitor class for the interval monitor.
@param {string} prefix Prefix to use for the interval monitor.
@param {number} interval Amount of time between reports, in milliseconds. | [
"Abstract",
"base",
"class",
"for",
"all",
"types",
"of",
"specialized",
"monitors",
"that",
"report",
"information",
"periodically",
"over",
"a",
"given",
"interval",
"."
]
| 040b259dfc8c6b5d934dc235f76028e5ab9094cc | https://github.com/Runnable/monitor-dog/blob/040b259dfc8c6b5d934dc235f76028e5ab9094cc/lib/interval-monitor.js#L18-L22 |
41,856 | vesln/hydro | lib/interface.js | each | function each(key, interface, fn) {
var stack = interface.stack;
for (var i = 0, len = stack.length; i < len; i++) {
stack[i][key].forEach(fn);
}
} | javascript | function each(key, interface, fn) {
var stack = interface.stack;
for (var i = 0, len = stack.length; i < len; i++) {
stack[i][key].forEach(fn);
}
} | [
"function",
"each",
"(",
"key",
",",
"interface",
",",
"fn",
")",
"{",
"var",
"stack",
"=",
"interface",
".",
"stack",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"stack",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"stack",
"[",
"i",
"]",
"[",
"key",
"]",
".",
"forEach",
"(",
"fn",
")",
";",
"}",
"}"
]
| Interate through all functions in the stack.
@param {String} key
@param {Interface} interface
@param {Function} fn
@api private | [
"Interate",
"through",
"all",
"functions",
"in",
"the",
"stack",
"."
]
| 3f4d2e4926f913976187376e82f1496514c39890 | https://github.com/vesln/hydro/blob/3f4d2e4926f913976187376e82f1496514c39890/lib/interface.js#L203-L209 |
41,857 | hrgdavor/babel-plugin-jsx-mi2 | index.js | buildOpeningElementAttributes | function buildOpeningElementAttributes (attribs, state) {
var _props = []
while (attribs.length) {
var prop = attribs.shift()
if (t.isJSXSpreadAttribute(prop)) {
prop.argument._isSpread = true
_props.push(t.spreadProperty(prop.argument))
} else {
_props.push(convertAttribute(prop, state))
}
}
attribs = t.objectExpression(_props)
return attribs
} | javascript | function buildOpeningElementAttributes (attribs, state) {
var _props = []
while (attribs.length) {
var prop = attribs.shift()
if (t.isJSXSpreadAttribute(prop)) {
prop.argument._isSpread = true
_props.push(t.spreadProperty(prop.argument))
} else {
_props.push(convertAttribute(prop, state))
}
}
attribs = t.objectExpression(_props)
return attribs
} | [
"function",
"buildOpeningElementAttributes",
"(",
"attribs",
",",
"state",
")",
"{",
"var",
"_props",
"=",
"[",
"]",
"while",
"(",
"attribs",
".",
"length",
")",
"{",
"var",
"prop",
"=",
"attribs",
".",
"shift",
"(",
")",
"if",
"(",
"t",
".",
"isJSXSpreadAttribute",
"(",
"prop",
")",
")",
"{",
"prop",
".",
"argument",
".",
"_isSpread",
"=",
"true",
"_props",
".",
"push",
"(",
"t",
".",
"spreadProperty",
"(",
"prop",
".",
"argument",
")",
")",
"}",
"else",
"{",
"_props",
".",
"push",
"(",
"convertAttribute",
"(",
"prop",
",",
"state",
")",
")",
"}",
"}",
"attribs",
"=",
"t",
".",
"objectExpression",
"(",
"_props",
")",
"return",
"attribs",
"}"
]
| Convert to object declaration by adding all
props and spreads as they are found. | [
"Convert",
"to",
"object",
"declaration",
"by",
"adding",
"all",
"props",
"and",
"spreads",
"as",
"they",
"are",
"found",
"."
]
| a5f1be9d7994cf72b5c740c2970bab5dab57d207 | https://github.com/hrgdavor/babel-plugin-jsx-mi2/blob/a5f1be9d7994cf72b5c740c2970bab5dab57d207/index.js#L124-L140 |
41,858 | Mammut-FE/nejm | src/util/ajax/proxy/xhr.js | function(_form){
var _result = [];
_u._$reverseEach(
_form.getElementsByTagName('input'),
function(_input){
if (_input.type!='file'){
return;
}
// remove file without name
if (!_input.name){
_input.parentNode.removeChild(_input);
return;
}
// for multiple file per-input
if (_input.files.length>1){
_u._$forEach(_input.files,function(_file){
_result.push({name:_input.name,file:_file});
});
_input.parentNode.removeChild(_input);
}
}
);
return _result.length>0?_result:null;
} | javascript | function(_form){
var _result = [];
_u._$reverseEach(
_form.getElementsByTagName('input'),
function(_input){
if (_input.type!='file'){
return;
}
// remove file without name
if (!_input.name){
_input.parentNode.removeChild(_input);
return;
}
// for multiple file per-input
if (_input.files.length>1){
_u._$forEach(_input.files,function(_file){
_result.push({name:_input.name,file:_file});
});
_input.parentNode.removeChild(_input);
}
}
);
return _result.length>0?_result:null;
} | [
"function",
"(",
"_form",
")",
"{",
"var",
"_result",
"=",
"[",
"]",
";",
"_u",
".",
"_$reverseEach",
"(",
"_form",
".",
"getElementsByTagName",
"(",
"'input'",
")",
",",
"function",
"(",
"_input",
")",
"{",
"if",
"(",
"_input",
".",
"type",
"!=",
"'file'",
")",
"{",
"return",
";",
"}",
"// remove file without name",
"if",
"(",
"!",
"_input",
".",
"name",
")",
"{",
"_input",
".",
"parentNode",
".",
"removeChild",
"(",
"_input",
")",
";",
"return",
";",
"}",
"// for multiple file per-input",
"if",
"(",
"_input",
".",
"files",
".",
"length",
">",
"1",
")",
"{",
"_u",
".",
"_$forEach",
"(",
"_input",
".",
"files",
",",
"function",
"(",
"_file",
")",
"{",
"_result",
".",
"push",
"(",
"{",
"name",
":",
"_input",
".",
"name",
",",
"file",
":",
"_file",
"}",
")",
";",
"}",
")",
";",
"_input",
".",
"parentNode",
".",
"removeChild",
"(",
"_input",
")",
";",
"}",
"}",
")",
";",
"return",
"_result",
".",
"length",
">",
"0",
"?",
"_result",
":",
"null",
";",
"}"
]
| split input.file for multiple files | [
"split",
"input",
".",
"file",
"for",
"multiple",
"files"
]
| dfc09ac66a8d67620a7aea65e34d8a179976b3fb | https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/util/ajax/proxy/xhr.js#L62-L85 |
|
41,859 | Mammut-FE/nejm | src/base/platform/element.patch.js | function(_element){
var _id = _element.id;
if (!!_dataset[_id]) return;
var _map = {};
_u._$forEach(
_element.attributes,
function(_node){
var _key = _node.nodeName;
if (_key.indexOf(_tag)!=0) return;
_key = _key.replace(_tag,'')
.replace(_reg,function($1,$2){
return $2.toUpperCase();
});
_map[_key] = _node.nodeValue||'';
}
);
_dataset[_id] = _map;
} | javascript | function(_element){
var _id = _element.id;
if (!!_dataset[_id]) return;
var _map = {};
_u._$forEach(
_element.attributes,
function(_node){
var _key = _node.nodeName;
if (_key.indexOf(_tag)!=0) return;
_key = _key.replace(_tag,'')
.replace(_reg,function($1,$2){
return $2.toUpperCase();
});
_map[_key] = _node.nodeValue||'';
}
);
_dataset[_id] = _map;
} | [
"function",
"(",
"_element",
")",
"{",
"var",
"_id",
"=",
"_element",
".",
"id",
";",
"if",
"(",
"!",
"!",
"_dataset",
"[",
"_id",
"]",
")",
"return",
";",
"var",
"_map",
"=",
"{",
"}",
";",
"_u",
".",
"_$forEach",
"(",
"_element",
".",
"attributes",
",",
"function",
"(",
"_node",
")",
"{",
"var",
"_key",
"=",
"_node",
".",
"nodeName",
";",
"if",
"(",
"_key",
".",
"indexOf",
"(",
"_tag",
")",
"!=",
"0",
")",
"return",
";",
"_key",
"=",
"_key",
".",
"replace",
"(",
"_tag",
",",
"''",
")",
".",
"replace",
"(",
"_reg",
",",
"function",
"(",
"$1",
",",
"$2",
")",
"{",
"return",
"$2",
".",
"toUpperCase",
"(",
")",
";",
"}",
")",
";",
"_map",
"[",
"_key",
"]",
"=",
"_node",
".",
"nodeValue",
"||",
"''",
";",
"}",
")",
";",
"_dataset",
"[",
"_id",
"]",
"=",
"_map",
";",
"}"
]
| init element dataset | [
"init",
"element",
"dataset"
]
| dfc09ac66a8d67620a7aea65e34d8a179976b3fb | https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/base/platform/element.patch.js#L52-L69 |
|
41,860 | Runnable/api-client | lib/external/primus-client.js | defaults | function defaults(name, selfie, opts) {
return millisecond(
name in opts ? opts[name] : (name in selfie ? selfie[name] : Recovery[name])
);
} | javascript | function defaults(name, selfie, opts) {
return millisecond(
name in opts ? opts[name] : (name in selfie ? selfie[name] : Recovery[name])
);
} | [
"function",
"defaults",
"(",
"name",
",",
"selfie",
",",
"opts",
")",
"{",
"return",
"millisecond",
"(",
"name",
"in",
"opts",
"?",
"opts",
"[",
"name",
"]",
":",
"(",
"name",
"in",
"selfie",
"?",
"selfie",
"[",
"name",
"]",
":",
"Recovery",
"[",
"name",
"]",
")",
")",
";",
"}"
]
| Returns sane defaults about a given value.
@param {String} name Name of property we want.
@param {Recovery} selfie Recovery instance that got created.
@param {Object} opts User supplied options we want to check.
@returns {Number} Some default value.
@api private | [
"Returns",
"sane",
"defaults",
"about",
"a",
"given",
"value",
"."
]
| e6089c4ed0b8c6ed383a82cbd50514e1e720f154 | https://github.com/Runnable/api-client/blob/e6089c4ed0b8c6ed383a82cbd50514e1e720f154/lib/external/primus-client.js#L493-L497 |
41,861 | Runnable/api-client | lib/external/primus-client.js | Recovery | function Recovery(options) {
var recovery = this;
if (!(recovery instanceof Recovery)) return new Recovery(options);
options = options || {};
recovery.attempt = null; // Stores the current reconnect attempt.
recovery._fn = null; // Stores the callback.
recovery['reconnect timeout'] = defaults('reconnect timeout', recovery, options);
recovery.retries = defaults('retries', recovery, options);
recovery.factor = defaults('factor', recovery, options);
recovery.max = defaults('max', recovery, options);
recovery.min = defaults('min', recovery, options);
recovery.timers = new Tick(recovery);
} | javascript | function Recovery(options) {
var recovery = this;
if (!(recovery instanceof Recovery)) return new Recovery(options);
options = options || {};
recovery.attempt = null; // Stores the current reconnect attempt.
recovery._fn = null; // Stores the callback.
recovery['reconnect timeout'] = defaults('reconnect timeout', recovery, options);
recovery.retries = defaults('retries', recovery, options);
recovery.factor = defaults('factor', recovery, options);
recovery.max = defaults('max', recovery, options);
recovery.min = defaults('min', recovery, options);
recovery.timers = new Tick(recovery);
} | [
"function",
"Recovery",
"(",
"options",
")",
"{",
"var",
"recovery",
"=",
"this",
";",
"if",
"(",
"!",
"(",
"recovery",
"instanceof",
"Recovery",
")",
")",
"return",
"new",
"Recovery",
"(",
"options",
")",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"recovery",
".",
"attempt",
"=",
"null",
";",
"// Stores the current reconnect attempt.",
"recovery",
".",
"_fn",
"=",
"null",
";",
"// Stores the callback.",
"recovery",
"[",
"'reconnect timeout'",
"]",
"=",
"defaults",
"(",
"'reconnect timeout'",
",",
"recovery",
",",
"options",
")",
";",
"recovery",
".",
"retries",
"=",
"defaults",
"(",
"'retries'",
",",
"recovery",
",",
"options",
")",
";",
"recovery",
".",
"factor",
"=",
"defaults",
"(",
"'factor'",
",",
"recovery",
",",
"options",
")",
";",
"recovery",
".",
"max",
"=",
"defaults",
"(",
"'max'",
",",
"recovery",
",",
"options",
")",
";",
"recovery",
".",
"min",
"=",
"defaults",
"(",
"'min'",
",",
"recovery",
",",
"options",
")",
";",
"recovery",
".",
"timers",
"=",
"new",
"Tick",
"(",
"recovery",
")",
";",
"}"
]
| Attempt to recover your connection with reconnection attempt.
@constructor
@param {Object} options Configuration
@api public | [
"Attempt",
"to",
"recover",
"your",
"connection",
"with",
"reconnection",
"attempt",
"."
]
| e6089c4ed0b8c6ed383a82cbd50514e1e720f154 | https://github.com/Runnable/api-client/blob/e6089c4ed0b8c6ed383a82cbd50514e1e720f154/lib/external/primus-client.js#L506-L522 |
41,862 | Runnable/api-client | lib/external/primus-client.js | URL | function URL(address, location, parser) {
if (!(this instanceof URL)) {
return new URL(address, location, parser);
}
var relative = relativere.test(address)
, parse, instruction, index, key
, type = typeof location
, url = this
, i = 0;
//
// The following if statements allows this module two have compatibility with
// 2 different API:
//
// 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
// where the boolean indicates that the query string should also be parsed.
//
// 2. The `URL` interface of the browser which accepts a URL, object as
// arguments. The supplied object will be used as default values / fall-back
// for relative paths.
//
if ('object' !== type && 'string' !== type) {
parser = location;
location = null;
}
if (parser && 'function' !== typeof parser) {
parser = qs.parse;
}
location = lolcation(location);
for (; i < instructions.length; i++) {
instruction = instructions[i];
parse = instruction[0];
key = instruction[1];
if (parse !== parse) {
url[key] = address;
} else if ('string' === typeof parse) {
if (~(index = address.indexOf(parse))) {
if ('number' === typeof instruction[2]) {
url[key] = address.slice(0, index);
address = address.slice(index + instruction[2]);
} else {
url[key] = address.slice(index);
address = address.slice(0, index);
}
}
} else if (index = parse.exec(address)) {
url[key] = index[1];
address = address.slice(0, address.length - index[0].length);
}
url[key] = url[key] || (instruction[3] || ('port' === key && relative) ? location[key] || '' : '');
//
// Hostname, host and protocol should be lowercased so they can be used to
// create a proper `origin`.
//
if (instruction[4]) {
url[key] = url[key].toLowerCase();
}
}
//
// Also parse the supplied query string in to an object. If we're supplied
// with a custom parser as function use that instead of the default build-in
// parser.
//
if (parser) url.query = parser(url.query);
//
// We should not add port numbers if they are already the default port number
// for a given protocol. As the host also contains the port number we're going
// override it with the hostname which contains no port number.
//
if (!required(url.port, url.protocol)) {
url.host = url.hostname;
url.port = '';
}
//
// Parse down the `auth` for the username and password.
//
url.username = url.password = '';
if (url.auth) {
instruction = url.auth.split(':');
url.username = instruction[0] || '';
url.password = instruction[1] || '';
}
//
// The href is just the compiled result.
//
url.href = url.toString();
} | javascript | function URL(address, location, parser) {
if (!(this instanceof URL)) {
return new URL(address, location, parser);
}
var relative = relativere.test(address)
, parse, instruction, index, key
, type = typeof location
, url = this
, i = 0;
//
// The following if statements allows this module two have compatibility with
// 2 different API:
//
// 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
// where the boolean indicates that the query string should also be parsed.
//
// 2. The `URL` interface of the browser which accepts a URL, object as
// arguments. The supplied object will be used as default values / fall-back
// for relative paths.
//
if ('object' !== type && 'string' !== type) {
parser = location;
location = null;
}
if (parser && 'function' !== typeof parser) {
parser = qs.parse;
}
location = lolcation(location);
for (; i < instructions.length; i++) {
instruction = instructions[i];
parse = instruction[0];
key = instruction[1];
if (parse !== parse) {
url[key] = address;
} else if ('string' === typeof parse) {
if (~(index = address.indexOf(parse))) {
if ('number' === typeof instruction[2]) {
url[key] = address.slice(0, index);
address = address.slice(index + instruction[2]);
} else {
url[key] = address.slice(index);
address = address.slice(0, index);
}
}
} else if (index = parse.exec(address)) {
url[key] = index[1];
address = address.slice(0, address.length - index[0].length);
}
url[key] = url[key] || (instruction[3] || ('port' === key && relative) ? location[key] || '' : '');
//
// Hostname, host and protocol should be lowercased so they can be used to
// create a proper `origin`.
//
if (instruction[4]) {
url[key] = url[key].toLowerCase();
}
}
//
// Also parse the supplied query string in to an object. If we're supplied
// with a custom parser as function use that instead of the default build-in
// parser.
//
if (parser) url.query = parser(url.query);
//
// We should not add port numbers if they are already the default port number
// for a given protocol. As the host also contains the port number we're going
// override it with the hostname which contains no port number.
//
if (!required(url.port, url.protocol)) {
url.host = url.hostname;
url.port = '';
}
//
// Parse down the `auth` for the username and password.
//
url.username = url.password = '';
if (url.auth) {
instruction = url.auth.split(':');
url.username = instruction[0] || '';
url.password = instruction[1] || '';
}
//
// The href is just the compiled result.
//
url.href = url.toString();
} | [
"function",
"URL",
"(",
"address",
",",
"location",
",",
"parser",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"URL",
")",
")",
"{",
"return",
"new",
"URL",
"(",
"address",
",",
"location",
",",
"parser",
")",
";",
"}",
"var",
"relative",
"=",
"relativere",
".",
"test",
"(",
"address",
")",
",",
"parse",
",",
"instruction",
",",
"index",
",",
"key",
",",
"type",
"=",
"typeof",
"location",
",",
"url",
"=",
"this",
",",
"i",
"=",
"0",
";",
"//",
"// The following if statements allows this module two have compatibility with",
"// 2 different API:",
"//",
"// 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments",
"// where the boolean indicates that the query string should also be parsed.",
"//",
"// 2. The `URL` interface of the browser which accepts a URL, object as",
"// arguments. The supplied object will be used as default values / fall-back",
"// for relative paths.",
"//",
"if",
"(",
"'object'",
"!==",
"type",
"&&",
"'string'",
"!==",
"type",
")",
"{",
"parser",
"=",
"location",
";",
"location",
"=",
"null",
";",
"}",
"if",
"(",
"parser",
"&&",
"'function'",
"!==",
"typeof",
"parser",
")",
"{",
"parser",
"=",
"qs",
".",
"parse",
";",
"}",
"location",
"=",
"lolcation",
"(",
"location",
")",
";",
"for",
"(",
";",
"i",
"<",
"instructions",
".",
"length",
";",
"i",
"++",
")",
"{",
"instruction",
"=",
"instructions",
"[",
"i",
"]",
";",
"parse",
"=",
"instruction",
"[",
"0",
"]",
";",
"key",
"=",
"instruction",
"[",
"1",
"]",
";",
"if",
"(",
"parse",
"!==",
"parse",
")",
"{",
"url",
"[",
"key",
"]",
"=",
"address",
";",
"}",
"else",
"if",
"(",
"'string'",
"===",
"typeof",
"parse",
")",
"{",
"if",
"(",
"~",
"(",
"index",
"=",
"address",
".",
"indexOf",
"(",
"parse",
")",
")",
")",
"{",
"if",
"(",
"'number'",
"===",
"typeof",
"instruction",
"[",
"2",
"]",
")",
"{",
"url",
"[",
"key",
"]",
"=",
"address",
".",
"slice",
"(",
"0",
",",
"index",
")",
";",
"address",
"=",
"address",
".",
"slice",
"(",
"index",
"+",
"instruction",
"[",
"2",
"]",
")",
";",
"}",
"else",
"{",
"url",
"[",
"key",
"]",
"=",
"address",
".",
"slice",
"(",
"index",
")",
";",
"address",
"=",
"address",
".",
"slice",
"(",
"0",
",",
"index",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"index",
"=",
"parse",
".",
"exec",
"(",
"address",
")",
")",
"{",
"url",
"[",
"key",
"]",
"=",
"index",
"[",
"1",
"]",
";",
"address",
"=",
"address",
".",
"slice",
"(",
"0",
",",
"address",
".",
"length",
"-",
"index",
"[",
"0",
"]",
".",
"length",
")",
";",
"}",
"url",
"[",
"key",
"]",
"=",
"url",
"[",
"key",
"]",
"||",
"(",
"instruction",
"[",
"3",
"]",
"||",
"(",
"'port'",
"===",
"key",
"&&",
"relative",
")",
"?",
"location",
"[",
"key",
"]",
"||",
"''",
":",
"''",
")",
";",
"//",
"// Hostname, host and protocol should be lowercased so they can be used to",
"// create a proper `origin`.",
"//",
"if",
"(",
"instruction",
"[",
"4",
"]",
")",
"{",
"url",
"[",
"key",
"]",
"=",
"url",
"[",
"key",
"]",
".",
"toLowerCase",
"(",
")",
";",
"}",
"}",
"//",
"// Also parse the supplied query string in to an object. If we're supplied",
"// with a custom parser as function use that instead of the default build-in",
"// parser.",
"//",
"if",
"(",
"parser",
")",
"url",
".",
"query",
"=",
"parser",
"(",
"url",
".",
"query",
")",
";",
"//",
"// We should not add port numbers if they are already the default port number",
"// for a given protocol. As the host also contains the port number we're going",
"// override it with the hostname which contains no port number.",
"//",
"if",
"(",
"!",
"required",
"(",
"url",
".",
"port",
",",
"url",
".",
"protocol",
")",
")",
"{",
"url",
".",
"host",
"=",
"url",
".",
"hostname",
";",
"url",
".",
"port",
"=",
"''",
";",
"}",
"//",
"// Parse down the `auth` for the username and password.",
"//",
"url",
".",
"username",
"=",
"url",
".",
"password",
"=",
"''",
";",
"if",
"(",
"url",
".",
"auth",
")",
"{",
"instruction",
"=",
"url",
".",
"auth",
".",
"split",
"(",
"':'",
")",
";",
"url",
".",
"username",
"=",
"instruction",
"[",
"0",
"]",
"||",
"''",
";",
"url",
".",
"password",
"=",
"instruction",
"[",
"1",
"]",
"||",
"''",
";",
"}",
"//",
"// The href is just the compiled result.",
"//",
"url",
".",
"href",
"=",
"url",
".",
"toString",
"(",
")",
";",
"}"
]
| The actual URL instance. Instead of returning an object we've opted-in to
create an actual constructor as it's much more memory efficient and
faster and it pleases my CDO.
@constructor
@param {String} address URL we want to parse.
@param {Boolean|function} parser Parser for the query string.
@param {Object} location Location defaults for relative paths.
@api public | [
"The",
"actual",
"URL",
"instance",
".",
"Instead",
"of",
"returning",
"an",
"object",
"we",
"ve",
"opted",
"-",
"in",
"to",
"create",
"an",
"actual",
"constructor",
"as",
"it",
"s",
"much",
"more",
"memory",
"efficient",
"and",
"faster",
"and",
"it",
"pleases",
"my",
"CDO",
"."
]
| e6089c4ed0b8c6ed383a82cbd50514e1e720f154 | https://github.com/Runnable/api-client/blob/e6089c4ed0b8c6ed383a82cbd50514e1e720f154/lib/external/primus-client.js#L1118-L1215 |
41,863 | Runnable/api-client | lib/external/primus-client.js | Primus | function Primus(url, options) {
if (!(this instanceof Primus)) return new Primus(url, options);
if ('function' !== typeof this.client) {
var message = 'The client library has not been compiled correctly, ' +
'see https://github.com/primus/primus#client-library for more details';
return this.critical(new Error(message));
}
if ('object' === typeof url) {
options = url;
url = options.url || options.uri || defaultUrl;
} else {
options = options || {};
}
var primus = this;
// The maximum number of messages that can be placed in queue.
options.queueSize = 'queueSize' in options ? options.queueSize : Infinity;
// Connection timeout duration.
options.timeout = 'timeout' in options ? options.timeout : 10e3;
// Stores the back off configuration.
options.reconnect = 'reconnect' in options ? options.reconnect : {};
// Heartbeat ping interval.
options.ping = 'ping' in options ? options.ping : 25000;
// Heartbeat pong response timeout.
options.pong = 'pong' in options ? options.pong : 10e3;
// Reconnect strategies.
options.strategy = 'strategy' in options ? options.strategy : [];
// Custom transport options.
options.transport = 'transport' in options ? options.transport : {};
primus.buffer = []; // Stores premature send data.
primus.writable = true; // Silly stream compatibility.
primus.readable = true; // Silly stream compatibility.
primus.url = primus.parse(url || defaultUrl); // Parse the URL to a readable format.
primus.readyState = Primus.CLOSED; // The readyState of the connection.
primus.options = options; // Reference to the supplied options.
primus.timers = new TickTock(this); // Contains all our timers.
primus.socket = null; // Reference to the internal connection.
primus.latency = 0; // Latency between messages.
primus.stamps = 0; // Counter to make timestamps unique.
primus.disconnect = false; // Did we receive a disconnect packet?
primus.transport = options.transport; // Transport options.
primus.transformers = { // Message transformers.
outgoing: [],
incoming: []
};
//
// Create our reconnection instance.
//
primus.recovery = new Recovery(options.reconnect);
//
// Parse the reconnection strategy. It can have the following strategies:
//
// - timeout: Reconnect when we have a network timeout.
// - disconnect: Reconnect when we have an unexpected disconnect.
// - online: Reconnect when we're back online.
//
if ('string' === typeof options.strategy) {
options.strategy = options.strategy.split(/\s?\,\s?/g);
}
if (false === options.strategy) {
//
// Strategies are disabled, but we still need an empty array to join it in
// to nothing.
//
options.strategy = [];
} else if (!options.strategy.length) {
options.strategy.push('disconnect', 'online');
//
// Timeout based reconnection should only be enabled conditionally. When
// authorization is enabled it could trigger.
//
if (!this.authorization) options.strategy.push('timeout');
}
options.strategy = options.strategy.join(',').toLowerCase();
//
// Force the use of WebSockets, even when we've detected some potential
// broken WebSocket implementation.
//
if ('websockets' in options) {
primus.AVOID_WEBSOCKETS = !options.websockets;
}
//
// Force or disable the use of NETWORK events as leading client side
// disconnection detection.
//
if ('network' in options) {
primus.NETWORK_EVENTS = options.network;
}
//
// Check if the user wants to manually initialise a connection. If they don't,
// we want to do it after a really small timeout so we give the users enough
// time to listen for `error` events etc.
//
if (!options.manual) primus.timers.setTimeout('open', function open() {
primus.timers.clear('open');
primus.open();
}, 0);
primus.initialise(options);
} | javascript | function Primus(url, options) {
if (!(this instanceof Primus)) return new Primus(url, options);
if ('function' !== typeof this.client) {
var message = 'The client library has not been compiled correctly, ' +
'see https://github.com/primus/primus#client-library for more details';
return this.critical(new Error(message));
}
if ('object' === typeof url) {
options = url;
url = options.url || options.uri || defaultUrl;
} else {
options = options || {};
}
var primus = this;
// The maximum number of messages that can be placed in queue.
options.queueSize = 'queueSize' in options ? options.queueSize : Infinity;
// Connection timeout duration.
options.timeout = 'timeout' in options ? options.timeout : 10e3;
// Stores the back off configuration.
options.reconnect = 'reconnect' in options ? options.reconnect : {};
// Heartbeat ping interval.
options.ping = 'ping' in options ? options.ping : 25000;
// Heartbeat pong response timeout.
options.pong = 'pong' in options ? options.pong : 10e3;
// Reconnect strategies.
options.strategy = 'strategy' in options ? options.strategy : [];
// Custom transport options.
options.transport = 'transport' in options ? options.transport : {};
primus.buffer = []; // Stores premature send data.
primus.writable = true; // Silly stream compatibility.
primus.readable = true; // Silly stream compatibility.
primus.url = primus.parse(url || defaultUrl); // Parse the URL to a readable format.
primus.readyState = Primus.CLOSED; // The readyState of the connection.
primus.options = options; // Reference to the supplied options.
primus.timers = new TickTock(this); // Contains all our timers.
primus.socket = null; // Reference to the internal connection.
primus.latency = 0; // Latency between messages.
primus.stamps = 0; // Counter to make timestamps unique.
primus.disconnect = false; // Did we receive a disconnect packet?
primus.transport = options.transport; // Transport options.
primus.transformers = { // Message transformers.
outgoing: [],
incoming: []
};
//
// Create our reconnection instance.
//
primus.recovery = new Recovery(options.reconnect);
//
// Parse the reconnection strategy. It can have the following strategies:
//
// - timeout: Reconnect when we have a network timeout.
// - disconnect: Reconnect when we have an unexpected disconnect.
// - online: Reconnect when we're back online.
//
if ('string' === typeof options.strategy) {
options.strategy = options.strategy.split(/\s?\,\s?/g);
}
if (false === options.strategy) {
//
// Strategies are disabled, but we still need an empty array to join it in
// to nothing.
//
options.strategy = [];
} else if (!options.strategy.length) {
options.strategy.push('disconnect', 'online');
//
// Timeout based reconnection should only be enabled conditionally. When
// authorization is enabled it could trigger.
//
if (!this.authorization) options.strategy.push('timeout');
}
options.strategy = options.strategy.join(',').toLowerCase();
//
// Force the use of WebSockets, even when we've detected some potential
// broken WebSocket implementation.
//
if ('websockets' in options) {
primus.AVOID_WEBSOCKETS = !options.websockets;
}
//
// Force or disable the use of NETWORK events as leading client side
// disconnection detection.
//
if ('network' in options) {
primus.NETWORK_EVENTS = options.network;
}
//
// Check if the user wants to manually initialise a connection. If they don't,
// we want to do it after a really small timeout so we give the users enough
// time to listen for `error` events etc.
//
if (!options.manual) primus.timers.setTimeout('open', function open() {
primus.timers.clear('open');
primus.open();
}, 0);
primus.initialise(options);
} | [
"function",
"Primus",
"(",
"url",
",",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Primus",
")",
")",
"return",
"new",
"Primus",
"(",
"url",
",",
"options",
")",
";",
"if",
"(",
"'function'",
"!==",
"typeof",
"this",
".",
"client",
")",
"{",
"var",
"message",
"=",
"'The client library has not been compiled correctly, '",
"+",
"'see https://github.com/primus/primus#client-library for more details'",
";",
"return",
"this",
".",
"critical",
"(",
"new",
"Error",
"(",
"message",
")",
")",
";",
"}",
"if",
"(",
"'object'",
"===",
"typeof",
"url",
")",
"{",
"options",
"=",
"url",
";",
"url",
"=",
"options",
".",
"url",
"||",
"options",
".",
"uri",
"||",
"defaultUrl",
";",
"}",
"else",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"}",
"var",
"primus",
"=",
"this",
";",
"// The maximum number of messages that can be placed in queue.",
"options",
".",
"queueSize",
"=",
"'queueSize'",
"in",
"options",
"?",
"options",
".",
"queueSize",
":",
"Infinity",
";",
"// Connection timeout duration.",
"options",
".",
"timeout",
"=",
"'timeout'",
"in",
"options",
"?",
"options",
".",
"timeout",
":",
"10e3",
";",
"// Stores the back off configuration.",
"options",
".",
"reconnect",
"=",
"'reconnect'",
"in",
"options",
"?",
"options",
".",
"reconnect",
":",
"{",
"}",
";",
"// Heartbeat ping interval.",
"options",
".",
"ping",
"=",
"'ping'",
"in",
"options",
"?",
"options",
".",
"ping",
":",
"25000",
";",
"// Heartbeat pong response timeout.",
"options",
".",
"pong",
"=",
"'pong'",
"in",
"options",
"?",
"options",
".",
"pong",
":",
"10e3",
";",
"// Reconnect strategies.",
"options",
".",
"strategy",
"=",
"'strategy'",
"in",
"options",
"?",
"options",
".",
"strategy",
":",
"[",
"]",
";",
"// Custom transport options.",
"options",
".",
"transport",
"=",
"'transport'",
"in",
"options",
"?",
"options",
".",
"transport",
":",
"{",
"}",
";",
"primus",
".",
"buffer",
"=",
"[",
"]",
";",
"// Stores premature send data.",
"primus",
".",
"writable",
"=",
"true",
";",
"// Silly stream compatibility.",
"primus",
".",
"readable",
"=",
"true",
";",
"// Silly stream compatibility.",
"primus",
".",
"url",
"=",
"primus",
".",
"parse",
"(",
"url",
"||",
"defaultUrl",
")",
";",
"// Parse the URL to a readable format.",
"primus",
".",
"readyState",
"=",
"Primus",
".",
"CLOSED",
";",
"// The readyState of the connection.",
"primus",
".",
"options",
"=",
"options",
";",
"// Reference to the supplied options.",
"primus",
".",
"timers",
"=",
"new",
"TickTock",
"(",
"this",
")",
";",
"// Contains all our timers.",
"primus",
".",
"socket",
"=",
"null",
";",
"// Reference to the internal connection.",
"primus",
".",
"latency",
"=",
"0",
";",
"// Latency between messages.",
"primus",
".",
"stamps",
"=",
"0",
";",
"// Counter to make timestamps unique.",
"primus",
".",
"disconnect",
"=",
"false",
";",
"// Did we receive a disconnect packet?",
"primus",
".",
"transport",
"=",
"options",
".",
"transport",
";",
"// Transport options.",
"primus",
".",
"transformers",
"=",
"{",
"// Message transformers.",
"outgoing",
":",
"[",
"]",
",",
"incoming",
":",
"[",
"]",
"}",
";",
"//",
"// Create our reconnection instance.",
"//",
"primus",
".",
"recovery",
"=",
"new",
"Recovery",
"(",
"options",
".",
"reconnect",
")",
";",
"//",
"// Parse the reconnection strategy. It can have the following strategies:",
"//",
"// - timeout: Reconnect when we have a network timeout.",
"// - disconnect: Reconnect when we have an unexpected disconnect.",
"// - online: Reconnect when we're back online.",
"//",
"if",
"(",
"'string'",
"===",
"typeof",
"options",
".",
"strategy",
")",
"{",
"options",
".",
"strategy",
"=",
"options",
".",
"strategy",
".",
"split",
"(",
"/",
"\\s?\\,\\s?",
"/",
"g",
")",
";",
"}",
"if",
"(",
"false",
"===",
"options",
".",
"strategy",
")",
"{",
"//",
"// Strategies are disabled, but we still need an empty array to join it in",
"// to nothing.",
"//",
"options",
".",
"strategy",
"=",
"[",
"]",
";",
"}",
"else",
"if",
"(",
"!",
"options",
".",
"strategy",
".",
"length",
")",
"{",
"options",
".",
"strategy",
".",
"push",
"(",
"'disconnect'",
",",
"'online'",
")",
";",
"//",
"// Timeout based reconnection should only be enabled conditionally. When",
"// authorization is enabled it could trigger.",
"//",
"if",
"(",
"!",
"this",
".",
"authorization",
")",
"options",
".",
"strategy",
".",
"push",
"(",
"'timeout'",
")",
";",
"}",
"options",
".",
"strategy",
"=",
"options",
".",
"strategy",
".",
"join",
"(",
"','",
")",
".",
"toLowerCase",
"(",
")",
";",
"//",
"// Force the use of WebSockets, even when we've detected some potential",
"// broken WebSocket implementation.",
"//",
"if",
"(",
"'websockets'",
"in",
"options",
")",
"{",
"primus",
".",
"AVOID_WEBSOCKETS",
"=",
"!",
"options",
".",
"websockets",
";",
"}",
"//",
"// Force or disable the use of NETWORK events as leading client side",
"// disconnection detection.",
"//",
"if",
"(",
"'network'",
"in",
"options",
")",
"{",
"primus",
".",
"NETWORK_EVENTS",
"=",
"options",
".",
"network",
";",
"}",
"//",
"// Check if the user wants to manually initialise a connection. If they don't,",
"// we want to do it after a really small timeout so we give the users enough",
"// time to listen for `error` events etc.",
"//",
"if",
"(",
"!",
"options",
".",
"manual",
")",
"primus",
".",
"timers",
".",
"setTimeout",
"(",
"'open'",
",",
"function",
"open",
"(",
")",
"{",
"primus",
".",
"timers",
".",
"clear",
"(",
"'open'",
")",
";",
"primus",
".",
"open",
"(",
")",
";",
"}",
",",
"0",
")",
";",
"primus",
".",
"initialise",
"(",
"options",
")",
";",
"}"
]
| Primus is a real-time library agnostic framework for establishing real-time
connections with servers.
Options:
- reconnect, configuration for the reconnect process.
- manual, don't automatically call `.open` to start the connection.
- websockets, force the use of WebSockets, even when you should avoid them.
- timeout, connect timeout, server didn't respond in a timely manner.
- ping, The heartbeat interval for sending a ping packet to the server.
- pong, The heartbeat timeout for receiving a response to the ping.
- network, Use network events as leading method for network connection drops.
- strategy, Reconnection strategies.
- transport, Transport options.
- url, uri, The URL to use connect with the server.
@constructor
@param {String} url The URL of your server.
@param {Object} options The configuration.
@api public | [
"Primus",
"is",
"a",
"real",
"-",
"time",
"library",
"agnostic",
"framework",
"for",
"establishing",
"real",
"-",
"time",
"connections",
"with",
"servers",
"."
]
| e6089c4ed0b8c6ed383a82cbd50514e1e720f154 | https://github.com/Runnable/api-client/blob/e6089c4ed0b8c6ed383a82cbd50514e1e720f154/lib/external/primus-client.js#L1469-L1585 |
41,864 | Runnable/api-client | lib/external/primus-client.js | pong | function pong() {
primus.timers.clear('pong');
//
// The network events already captured the offline event.
//
if (!primus.online) return;
primus.online = false;
primus.emit('offline');
primus.emit('incoming::end');
} | javascript | function pong() {
primus.timers.clear('pong');
//
// The network events already captured the offline event.
//
if (!primus.online) return;
primus.online = false;
primus.emit('offline');
primus.emit('incoming::end');
} | [
"function",
"pong",
"(",
")",
"{",
"primus",
".",
"timers",
".",
"clear",
"(",
"'pong'",
")",
";",
"//",
"// The network events already captured the offline event.",
"//",
"if",
"(",
"!",
"primus",
".",
"online",
")",
"return",
";",
"primus",
".",
"online",
"=",
"false",
";",
"primus",
".",
"emit",
"(",
"'offline'",
")",
";",
"primus",
".",
"emit",
"(",
"'incoming::end'",
")",
";",
"}"
]
| Exterminate the connection as we've timed out.
@api private | [
"Exterminate",
"the",
"connection",
"as",
"we",
"ve",
"timed",
"out",
"."
]
| e6089c4ed0b8c6ed383a82cbd50514e1e720f154 | https://github.com/Runnable/api-client/blob/e6089c4ed0b8c6ed383a82cbd50514e1e720f154/lib/external/primus-client.js#L2268-L2279 |
41,865 | Runnable/api-client | lib/external/primus-client.js | ping | function ping() {
var value = +new Date();
primus.timers.clear('ping');
primus._write('primus::ping::'+ value);
primus.emit('outgoing::ping', value);
primus.timers.setTimeout('pong', pong, primus.options.pong);
} | javascript | function ping() {
var value = +new Date();
primus.timers.clear('ping');
primus._write('primus::ping::'+ value);
primus.emit('outgoing::ping', value);
primus.timers.setTimeout('pong', pong, primus.options.pong);
} | [
"function",
"ping",
"(",
")",
"{",
"var",
"value",
"=",
"+",
"new",
"Date",
"(",
")",
";",
"primus",
".",
"timers",
".",
"clear",
"(",
"'ping'",
")",
";",
"primus",
".",
"_write",
"(",
"'primus::ping::'",
"+",
"value",
")",
";",
"primus",
".",
"emit",
"(",
"'outgoing::ping'",
",",
"value",
")",
";",
"primus",
".",
"timers",
".",
"setTimeout",
"(",
"'pong'",
",",
"pong",
",",
"primus",
".",
"options",
".",
"pong",
")",
";",
"}"
]
| We should send a ping message to the server.
@api private | [
"We",
"should",
"send",
"a",
"ping",
"message",
"to",
"the",
"server",
"."
]
| e6089c4ed0b8c6ed383a82cbd50514e1e720f154 | https://github.com/Runnable/api-client/blob/e6089c4ed0b8c6ed383a82cbd50514e1e720f154/lib/external/primus-client.js#L2286-L2293 |
41,866 | atsid/circuits-js | js/util.js | function (name, separator) {
var fullName, sep = separator || "/";
if (name.indexOf(sep) >= 0) {
fullName = name; //already got fully-qualified (theoretically)
} else if (name.indexOf("Service") >= 0) {
fullName = "Schema" + sep + "services" + sep + name; //just got the service class name
} else {
fullName = "Schema" + sep + "services" + sep + name + "Service"; //just got the service "object" name
}
logger.debug("Service util created full name [" + fullName + "] from [" + name + "]");
return fullName;
} | javascript | function (name, separator) {
var fullName, sep = separator || "/";
if (name.indexOf(sep) >= 0) {
fullName = name; //already got fully-qualified (theoretically)
} else if (name.indexOf("Service") >= 0) {
fullName = "Schema" + sep + "services" + sep + name; //just got the service class name
} else {
fullName = "Schema" + sep + "services" + sep + name + "Service"; //just got the service "object" name
}
logger.debug("Service util created full name [" + fullName + "] from [" + name + "]");
return fullName;
} | [
"function",
"(",
"name",
",",
"separator",
")",
"{",
"var",
"fullName",
",",
"sep",
"=",
"separator",
"||",
"\"/\"",
";",
"if",
"(",
"name",
".",
"indexOf",
"(",
"sep",
")",
">=",
"0",
")",
"{",
"fullName",
"=",
"name",
";",
"//already got fully-qualified (theoretically)",
"}",
"else",
"if",
"(",
"name",
".",
"indexOf",
"(",
"\"Service\"",
")",
">=",
"0",
")",
"{",
"fullName",
"=",
"\"Schema\"",
"+",
"sep",
"+",
"\"services\"",
"+",
"sep",
"+",
"name",
";",
"//just got the service class name",
"}",
"else",
"{",
"fullName",
"=",
"\"Schema\"",
"+",
"sep",
"+",
"\"services\"",
"+",
"sep",
"+",
"name",
"+",
"\"Service\"",
";",
"//just got the service \"object\" name",
"}",
"logger",
".",
"debug",
"(",
"\"Service util created full name [\"",
"+",
"fullName",
"+",
"\"] from [\"",
"+",
"name",
"+",
"\"]\"",
")",
";",
"return",
"fullName",
";",
"}"
]
| Returns a fully-qualified name for a service from one of several partial formats. | [
"Returns",
"a",
"fully",
"-",
"qualified",
"name",
"for",
"a",
"service",
"from",
"one",
"of",
"several",
"partial",
"formats",
"."
]
| f1fa5e98d406b3b9f577dd8995782c7115d6b346 | https://github.com/atsid/circuits-js/blob/f1fa5e98d406b3b9f577dd8995782c7115d6b346/js/util.js#L42-L58 |
|
41,867 | atsid/circuits-js | js/util.js | function (plugins, func) {
var idx, plugin = null;
// iterate to process in reverse order without side-effects.
for (idx = 1; idx <= plugins.length; idx += 1) {
plugin = plugins[plugins.length - idx];
func(plugin);
if (plugin.stopProcessing) {
break;
}
}
} | javascript | function (plugins, func) {
var idx, plugin = null;
// iterate to process in reverse order without side-effects.
for (idx = 1; idx <= plugins.length; idx += 1) {
plugin = plugins[plugins.length - idx];
func(plugin);
if (plugin.stopProcessing) {
break;
}
}
} | [
"function",
"(",
"plugins",
",",
"func",
")",
"{",
"var",
"idx",
",",
"plugin",
"=",
"null",
";",
"// iterate to process in reverse order without side-effects.",
"for",
"(",
"idx",
"=",
"1",
";",
"idx",
"<=",
"plugins",
".",
"length",
";",
"idx",
"+=",
"1",
")",
"{",
"plugin",
"=",
"plugins",
"[",
"plugins",
".",
"length",
"-",
"idx",
"]",
";",
"func",
"(",
"plugin",
")",
";",
"if",
"(",
"plugin",
".",
"stopProcessing",
")",
"{",
"break",
";",
"}",
"}",
"}"
]
| Execute a plugin array, terminating if a plugin sets its stopProcessing property.
@param plugins - the array of plugins to execute.
@param func - the function to apply to each plugin, it accepts the plugin its single parameter. | [
"Execute",
"a",
"plugin",
"array",
"terminating",
"if",
"a",
"plugin",
"sets",
"its",
"stopProcessing",
"property",
"."
]
| f1fa5e98d406b3b9f577dd8995782c7115d6b346 | https://github.com/atsid/circuits-js/blob/f1fa5e98d406b3b9f577dd8995782c7115d6b346/js/util.js#L83-L93 |
|
41,868 | kt3k/bundle-through | index.js | bundleThrough | function bundleThrough(options) {
options = options || {}
var browserifyShouldCreateSourcemaps = options.debug || options.sourcemaps
var bundleTransform = through(function (file, enc, callback) {
var bundler = browserify(file.path, assign({}, options, {debug: browserifyShouldCreateSourcemaps}))
if (options.buffer === false) {
// if `buffer` option is `false` then `file.contents` is a stream
return callback(null, createNewFileByContents(file, bundler.bundle().on('error', callback)))
}
bundler.bundle(function (err, data) {
if (err) { return callback(err) }
callback(null, createNewFileByContents(file, data))
})
})
if (options.sourcemaps !== true) {
return bundleTransform
}
return duplexify.obj(bundleTransform, bundleTransform.pipe(sourcemaps.init({loadMaps: true})))
} | javascript | function bundleThrough(options) {
options = options || {}
var browserifyShouldCreateSourcemaps = options.debug || options.sourcemaps
var bundleTransform = through(function (file, enc, callback) {
var bundler = browserify(file.path, assign({}, options, {debug: browserifyShouldCreateSourcemaps}))
if (options.buffer === false) {
// if `buffer` option is `false` then `file.contents` is a stream
return callback(null, createNewFileByContents(file, bundler.bundle().on('error', callback)))
}
bundler.bundle(function (err, data) {
if (err) { return callback(err) }
callback(null, createNewFileByContents(file, data))
})
})
if (options.sourcemaps !== true) {
return bundleTransform
}
return duplexify.obj(bundleTransform, bundleTransform.pipe(sourcemaps.init({loadMaps: true})))
} | [
"function",
"bundleThrough",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
"var",
"browserifyShouldCreateSourcemaps",
"=",
"options",
".",
"debug",
"||",
"options",
".",
"sourcemaps",
"var",
"bundleTransform",
"=",
"through",
"(",
"function",
"(",
"file",
",",
"enc",
",",
"callback",
")",
"{",
"var",
"bundler",
"=",
"browserify",
"(",
"file",
".",
"path",
",",
"assign",
"(",
"{",
"}",
",",
"options",
",",
"{",
"debug",
":",
"browserifyShouldCreateSourcemaps",
"}",
")",
")",
"if",
"(",
"options",
".",
"buffer",
"===",
"false",
")",
"{",
"// if `buffer` option is `false` then `file.contents` is a stream",
"return",
"callback",
"(",
"null",
",",
"createNewFileByContents",
"(",
"file",
",",
"bundler",
".",
"bundle",
"(",
")",
".",
"on",
"(",
"'error'",
",",
"callback",
")",
")",
")",
"}",
"bundler",
".",
"bundle",
"(",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
"}",
"callback",
"(",
"null",
",",
"createNewFileByContents",
"(",
"file",
",",
"data",
")",
")",
"}",
")",
"}",
")",
"if",
"(",
"options",
".",
"sourcemaps",
"!==",
"true",
")",
"{",
"return",
"bundleTransform",
"}",
"return",
"duplexify",
".",
"obj",
"(",
"bundleTransform",
",",
"bundleTransform",
".",
"pipe",
"(",
"sourcemaps",
".",
"init",
"(",
"{",
"loadMaps",
":",
"true",
"}",
")",
")",
")",
"}"
]
| Returns a transform stream which bundles files in the given stream.
@param {object} [options] The options. This options are directly passed to the `browserify` constructor. You can pass any browserify options such as `transform` `plugin` `debug` etc.
@param {boolean} [options.buffer] `true` iff you want output file to have buffer type contents. Default is `true`. If set `false`, the output file has file contents as a stream.
@param {boolean} [options.sourcemaps] `true` iff you want to output sourcemaps. You need to *write* it using `gulp-sourcemaps`.
@return {Transform<Vinyl, Vinyl>} | [
"Returns",
"a",
"transform",
"stream",
"which",
"bundles",
"files",
"in",
"the",
"given",
"stream",
"."
]
| e474509585866a894fdae53347e9835e61b8e6d4 | https://github.com/kt3k/bundle-through/blob/e474509585866a894fdae53347e9835e61b8e6d4/index.js#L18-L51 |
41,869 | kt3k/bundle-through | index.js | createNewFileByContents | function createNewFileByContents(file, newContents) {
var newFile = file.clone()
newFile.contents = newContents
return newFile
} | javascript | function createNewFileByContents(file, newContents) {
var newFile = file.clone()
newFile.contents = newContents
return newFile
} | [
"function",
"createNewFileByContents",
"(",
"file",
",",
"newContents",
")",
"{",
"var",
"newFile",
"=",
"file",
".",
"clone",
"(",
")",
"newFile",
".",
"contents",
"=",
"newContents",
"return",
"newFile",
"}"
]
| Returns a new file from the given file and contents.
@param {Vinyl} file The input file
@param {Buffer|Stream} newContents The new contents for the file | [
"Returns",
"a",
"new",
"file",
"from",
"the",
"given",
"file",
"and",
"contents",
"."
]
| e474509585866a894fdae53347e9835e61b8e6d4 | https://github.com/kt3k/bundle-through/blob/e474509585866a894fdae53347e9835e61b8e6d4/index.js#L58-L65 |
41,870 | veo-labs/openveo-api | lib/middlewares/imageProcessorMiddleware.js | fetchStyle | function fetchStyle(id) {
for (var i = 0; i < styles.length; i++)
if (styles[i].id === id) return styles[i];
} | javascript | function fetchStyle(id) {
for (var i = 0; i < styles.length; i++)
if (styles[i].id === id) return styles[i];
} | [
"function",
"fetchStyle",
"(",
"id",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"styles",
".",
"length",
";",
"i",
"++",
")",
"if",
"(",
"styles",
"[",
"i",
"]",
".",
"id",
"===",
"id",
")",
"return",
"styles",
"[",
"i",
"]",
";",
"}"
]
| Fetches a style by its id from the list of styles.
@param {String} id The id of the style to fetch
@return {Object} The style description object | [
"Fetches",
"a",
"style",
"by",
"its",
"id",
"from",
"the",
"list",
"of",
"styles",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/middlewares/imageProcessorMiddleware.js#L61-L64 |
41,871 | veo-labs/openveo-api | lib/middlewares/imageProcessorMiddleware.js | sendFile | function sendFile(imagePath) {
response.set(headers);
response.download(imagePath, request.query.filename);
} | javascript | function sendFile(imagePath) {
response.set(headers);
response.download(imagePath, request.query.filename);
} | [
"function",
"sendFile",
"(",
"imagePath",
")",
"{",
"response",
".",
"set",
"(",
"headers",
")",
";",
"response",
".",
"download",
"(",
"imagePath",
",",
"request",
".",
"query",
".",
"filename",
")",
";",
"}"
]
| Sends an image to client as response.
@param {String} imagePath The absolute image path | [
"Sends",
"an",
"image",
"to",
"client",
"as",
"response",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/middlewares/imageProcessorMiddleware.js#L82-L85 |
41,872 | LeisureLink/magicbus | lib/middleware/pipeline.js | Pipeline | function Pipeline(actionFactory, pipe) {
assert.func(actionFactory, 'actionFactory');
assert.optionalArrayOfFunc(pipe, 'pipe');
let middleware = (pipe || []).slice();
let logger;
let module = {
/** Clone the middleware pipeline */
clone: () => {
return Pipeline(actionFactory, middleware);
},
/** Use a segment */
use: (segment) => {
middleware.push(segment);
return module;
},
/** Pass this logger to middleware functions */
useLogger: (theLogger) => {
logger = theLogger;
return module;
},
/**
* Prepare pipeline for execution, with an optional head middleware
* @param {Function} head - the function to execute at the beginning of the pipeline
* @returns {Function} a function to execute the middleware pipeline
*/
prepare: (head) => {
assert.optionalFunc(head, 'head');
let pipe = middleware.slice();
let actions = actionFactory();
if (head){
head(actions);
}
return (message, options) => {
return new Promise((resolve, reject) => {
function executeSegment(){
var segment;
if (pipe.length){
segment = pipe.shift();
segment(message, actions, logger, options);
}
else {
resolve();
}
}
actions.on('error', reject);
actions.on('next', executeSegment);
actions.on('finished', reject);
executeSegment();
});
};
}
};
return module;
} | javascript | function Pipeline(actionFactory, pipe) {
assert.func(actionFactory, 'actionFactory');
assert.optionalArrayOfFunc(pipe, 'pipe');
let middleware = (pipe || []).slice();
let logger;
let module = {
/** Clone the middleware pipeline */
clone: () => {
return Pipeline(actionFactory, middleware);
},
/** Use a segment */
use: (segment) => {
middleware.push(segment);
return module;
},
/** Pass this logger to middleware functions */
useLogger: (theLogger) => {
logger = theLogger;
return module;
},
/**
* Prepare pipeline for execution, with an optional head middleware
* @param {Function} head - the function to execute at the beginning of the pipeline
* @returns {Function} a function to execute the middleware pipeline
*/
prepare: (head) => {
assert.optionalFunc(head, 'head');
let pipe = middleware.slice();
let actions = actionFactory();
if (head){
head(actions);
}
return (message, options) => {
return new Promise((resolve, reject) => {
function executeSegment(){
var segment;
if (pipe.length){
segment = pipe.shift();
segment(message, actions, logger, options);
}
else {
resolve();
}
}
actions.on('error', reject);
actions.on('next', executeSegment);
actions.on('finished', reject);
executeSegment();
});
};
}
};
return module;
} | [
"function",
"Pipeline",
"(",
"actionFactory",
",",
"pipe",
")",
"{",
"assert",
".",
"func",
"(",
"actionFactory",
",",
"'actionFactory'",
")",
";",
"assert",
".",
"optionalArrayOfFunc",
"(",
"pipe",
",",
"'pipe'",
")",
";",
"let",
"middleware",
"=",
"(",
"pipe",
"||",
"[",
"]",
")",
".",
"slice",
"(",
")",
";",
"let",
"logger",
";",
"let",
"module",
"=",
"{",
"/** Clone the middleware pipeline */",
"clone",
":",
"(",
")",
"=>",
"{",
"return",
"Pipeline",
"(",
"actionFactory",
",",
"middleware",
")",
";",
"}",
",",
"/** Use a segment */",
"use",
":",
"(",
"segment",
")",
"=>",
"{",
"middleware",
".",
"push",
"(",
"segment",
")",
";",
"return",
"module",
";",
"}",
",",
"/** Pass this logger to middleware functions */",
"useLogger",
":",
"(",
"theLogger",
")",
"=>",
"{",
"logger",
"=",
"theLogger",
";",
"return",
"module",
";",
"}",
",",
"/**\n * Prepare pipeline for execution, with an optional head middleware\n * @param {Function} head - the function to execute at the beginning of the pipeline\n * @returns {Function} a function to execute the middleware pipeline\n */",
"prepare",
":",
"(",
"head",
")",
"=>",
"{",
"assert",
".",
"optionalFunc",
"(",
"head",
",",
"'head'",
")",
";",
"let",
"pipe",
"=",
"middleware",
".",
"slice",
"(",
")",
";",
"let",
"actions",
"=",
"actionFactory",
"(",
")",
";",
"if",
"(",
"head",
")",
"{",
"head",
"(",
"actions",
")",
";",
"}",
"return",
"(",
"message",
",",
"options",
")",
"=>",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"function",
"executeSegment",
"(",
")",
"{",
"var",
"segment",
";",
"if",
"(",
"pipe",
".",
"length",
")",
"{",
"segment",
"=",
"pipe",
".",
"shift",
"(",
")",
";",
"segment",
"(",
"message",
",",
"actions",
",",
"logger",
",",
"options",
")",
";",
"}",
"else",
"{",
"resolve",
"(",
")",
";",
"}",
"}",
"actions",
".",
"on",
"(",
"'error'",
",",
"reject",
")",
";",
"actions",
".",
"on",
"(",
"'next'",
",",
"executeSegment",
")",
";",
"actions",
".",
"on",
"(",
"'finished'",
",",
"reject",
")",
";",
"executeSegment",
"(",
")",
";",
"}",
")",
";",
"}",
";",
"}",
"}",
";",
"return",
"module",
";",
"}"
]
| Represents a pipeline of middleware to be executed for a message
@param {Function} actionFactory - factory function that returns an Actions instance
@param {Array} pipe - array of middleware to be executed
@returns {Object} a module with clone, use, and prepare functions | [
"Represents",
"a",
"pipeline",
"of",
"middleware",
"to",
"be",
"executed",
"for",
"a",
"message"
]
| 0370c38ebb8c7917cfd3894263d734aefc2d3d29 | https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/middleware/pipeline.js#L12-L72 |
41,873 | veo-labs/openveo-plugin-generator | generators/app/templates/tasks/_concat.js | getMinifiedJSFiles | function getMinifiedJSFiles(files) {
var minifiedFiles = [];
files.forEach(function(path) {
minifiedFiles.push('<%- project.uglify %>/' + path.replace('.js', '.min.js').replace('/<%= originalPluginName %>/', ''));
});
return minifiedFiles;
} | javascript | function getMinifiedJSFiles(files) {
var minifiedFiles = [];
files.forEach(function(path) {
minifiedFiles.push('<%- project.uglify %>/' + path.replace('.js', '.min.js').replace('/<%= originalPluginName %>/', ''));
});
return minifiedFiles;
} | [
"function",
"getMinifiedJSFiles",
"(",
"files",
")",
"{",
"var",
"minifiedFiles",
"=",
"[",
"]",
";",
"files",
".",
"forEach",
"(",
"function",
"(",
"path",
")",
"{",
"minifiedFiles",
".",
"push",
"(",
"'<%- project.uglify %>/'",
"+",
"path",
".",
"replace",
"(",
"'.js'",
",",
"'.min.js'",
")",
".",
"replace",
"(",
"'/<%= originalPluginName %>/'",
",",
"''",
")",
")",
";",
"}",
")",
";",
"return",
"minifiedFiles",
";",
"}"
]
| Gets the list of minified JavaScript files from the given list of files.
It will just replace ".js" by ".min.js".
@param Array files The list of files
@return Array The list of minified files | [
"Gets",
"the",
"list",
"of",
"minified",
"JavaScript",
"files",
"from",
"the",
"given",
"list",
"of",
"files",
"."
]
| ce54e1a17a81ef220a90a74e834dc4a5ff0b3f6b | https://github.com/veo-labs/openveo-plugin-generator/blob/ce54e1a17a81ef220a90a74e834dc4a5ff0b3f6b/generators/app/templates/tasks/_concat.js#L13-L19 |
41,874 | emeryrose/boscar | index.js | _createStreamPointer | function _createStreamPointer(self, stream, serializer) {
let id = uuid();
let readable = typeof stream.read === 'function';
let type = readable ? 'readable' : 'writable';
let pointer = `boscar:${type}:${id}`;
self.streams.set(id, stream);
if (readable) {
_bindReadable(pointer, stream, serializer);
}
return pointer;
} | javascript | function _createStreamPointer(self, stream, serializer) {
let id = uuid();
let readable = typeof stream.read === 'function';
let type = readable ? 'readable' : 'writable';
let pointer = `boscar:${type}:${id}`;
self.streams.set(id, stream);
if (readable) {
_bindReadable(pointer, stream, serializer);
}
return pointer;
} | [
"function",
"_createStreamPointer",
"(",
"self",
",",
"stream",
",",
"serializer",
")",
"{",
"let",
"id",
"=",
"uuid",
"(",
")",
";",
"let",
"readable",
"=",
"typeof",
"stream",
".",
"read",
"===",
"'function'",
";",
"let",
"type",
"=",
"readable",
"?",
"'readable'",
":",
"'writable'",
";",
"let",
"pointer",
"=",
"`",
"${",
"type",
"}",
"${",
"id",
"}",
"`",
";",
"self",
".",
"streams",
".",
"set",
"(",
"id",
",",
"stream",
")",
";",
"if",
"(",
"readable",
")",
"{",
"_bindReadable",
"(",
"pointer",
",",
"stream",
",",
"serializer",
")",
";",
"}",
"return",
"pointer",
";",
"}"
]
| Converts a stream object into a pointer string and sets up stream tracking
@param {object} self - Object with a `streams` property
@param {object} stream
@param {object} serializer
@returns {string} | [
"Converts",
"a",
"stream",
"object",
"into",
"a",
"pointer",
"string",
"and",
"sets",
"up",
"stream",
"tracking"
]
| 19d3c953a4380d6d6515eb0659fffe789a9eddd0 | https://github.com/emeryrose/boscar/blob/19d3c953a4380d6d6515eb0659fffe789a9eddd0/index.js#L87-L100 |
41,875 | emeryrose/boscar | index.js | _bindReadable | function _bindReadable(pointer, stream, serializer) {
stream.on('data', (data) => {
serializer.write(jsonrpc.notification(pointer, [data]));
});
stream.on('end', () => {
serializer.write(jsonrpc.notification(pointer, [null]));
});
stream.on('error', () => {
serializer.write(jsonrpc.notification(pointer, [null]));
});
} | javascript | function _bindReadable(pointer, stream, serializer) {
stream.on('data', (data) => {
serializer.write(jsonrpc.notification(pointer, [data]));
});
stream.on('end', () => {
serializer.write(jsonrpc.notification(pointer, [null]));
});
stream.on('error', () => {
serializer.write(jsonrpc.notification(pointer, [null]));
});
} | [
"function",
"_bindReadable",
"(",
"pointer",
",",
"stream",
",",
"serializer",
")",
"{",
"stream",
".",
"on",
"(",
"'data'",
",",
"(",
"data",
")",
"=>",
"{",
"serializer",
".",
"write",
"(",
"jsonrpc",
".",
"notification",
"(",
"pointer",
",",
"[",
"data",
"]",
")",
")",
";",
"}",
")",
";",
"stream",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"{",
"serializer",
".",
"write",
"(",
"jsonrpc",
".",
"notification",
"(",
"pointer",
",",
"[",
"null",
"]",
")",
")",
";",
"}",
")",
";",
"stream",
".",
"on",
"(",
"'error'",
",",
"(",
")",
"=>",
"{",
"serializer",
".",
"write",
"(",
"jsonrpc",
".",
"notification",
"(",
"pointer",
",",
"[",
"null",
"]",
")",
")",
";",
"}",
")",
";",
"}"
]
| Binds to readable stream events and write messages to the given serializer
@param {string} pointer
@param {object} stream
@param {object} serializer | [
"Binds",
"to",
"readable",
"stream",
"events",
"and",
"write",
"messages",
"to",
"the",
"given",
"serializer"
]
| 19d3c953a4380d6d6515eb0659fffe789a9eddd0 | https://github.com/emeryrose/boscar/blob/19d3c953a4380d6d6515eb0659fffe789a9eddd0/index.js#L108-L118 |
41,876 | localnerve/element-size-reporter | src/lib/index.js | round | function round (value, rules) {
let unit = 1.0, roundOp = Math.round;
if (rules) {
roundOp = Math[rules.type === 'top' ? 'floor' : 'ceil'];
if ('object' === typeof rules.grow) {
unit = rules.grow[rules.type] || 1.0;
}
}
return roundOp(value / unit) * unit;
} | javascript | function round (value, rules) {
let unit = 1.0, roundOp = Math.round;
if (rules) {
roundOp = Math[rules.type === 'top' ? 'floor' : 'ceil'];
if ('object' === typeof rules.grow) {
unit = rules.grow[rules.type] || 1.0;
}
}
return roundOp(value / unit) * unit;
} | [
"function",
"round",
"(",
"value",
",",
"rules",
")",
"{",
"let",
"unit",
"=",
"1.0",
",",
"roundOp",
"=",
"Math",
".",
"round",
";",
"if",
"(",
"rules",
")",
"{",
"roundOp",
"=",
"Math",
"[",
"rules",
".",
"type",
"===",
"'top'",
"?",
"'floor'",
":",
"'ceil'",
"]",
";",
"if",
"(",
"'object'",
"===",
"typeof",
"rules",
".",
"grow",
")",
"{",
"unit",
"=",
"rules",
".",
"grow",
"[",
"rules",
".",
"type",
"]",
"||",
"1.0",
";",
"}",
"}",
"return",
"roundOp",
"(",
"value",
"/",
"unit",
")",
"*",
"unit",
";",
"}"
]
| Round a number to nearest multiple according to rules.
Default multiple is 1.0. Supply nearest multiple in rules.grow parameter.
Rounding rules:
type === 'top' then use floor rounding.
otherwise, use ceiling rounding.
@param {Number} value - The raw value to round.
@param {Object} [rules] - Rounding rules. If omitted, just uses Math.round.
If supplied, must at least specify rules.type.
@param {String} [rules.type] - Can be one of 'top', 'width', or 'height'.
@param {Object} [rules.grow] - Options that control padding adjustments.
@param {Number} [rules.grow.top] - Nearest multiple to grow to. Used if
matches given type parameter.
@param {Number} [rules.grow.width] - Nearest multiple to grow to. Used if
matches given type parameter.
@param {Number} [rules.grow.height] - Nearest multiple to grow to. Used if
matches given type parameter.
@returns {Number} The rounded value according to rules derived from type and
grow. | [
"Round",
"a",
"number",
"to",
"nearest",
"multiple",
"according",
"to",
"rules",
".",
"Default",
"multiple",
"is",
"1",
".",
"0",
".",
"Supply",
"nearest",
"multiple",
"in",
"rules",
".",
"grow",
"parameter",
"."
]
| f4b43c794df390a3dc89da0c28ef416a772047d7 | https://github.com/localnerve/element-size-reporter/blob/f4b43c794df390a3dc89da0c28ef416a772047d7/src/lib/index.js#L50-L61 |
41,877 | Runnable/monitor-dog | lib/monitor.js | Monitor | function Monitor (opt) {
opt = opt || {};
this.prefix = opt.prefix || process.env.MONITOR_PREFIX || null;
this.host = opt.host || process.env.DATADOG_HOST;
this.port = opt.port || process.env.DATADOG_PORT;
this.interval = opt.interval || process.env.MONITOR_INTERVAL;
if (this.host && this.port) {
this.client = new StatsD(this.host, this.port);
this.socketsMonitor = new SocketsMonitor(this);
}
} | javascript | function Monitor (opt) {
opt = opt || {};
this.prefix = opt.prefix || process.env.MONITOR_PREFIX || null;
this.host = opt.host || process.env.DATADOG_HOST;
this.port = opt.port || process.env.DATADOG_PORT;
this.interval = opt.interval || process.env.MONITOR_INTERVAL;
if (this.host && this.port) {
this.client = new StatsD(this.host, this.port);
this.socketsMonitor = new SocketsMonitor(this);
}
} | [
"function",
"Monitor",
"(",
"opt",
")",
"{",
"opt",
"=",
"opt",
"||",
"{",
"}",
";",
"this",
".",
"prefix",
"=",
"opt",
".",
"prefix",
"||",
"process",
".",
"env",
".",
"MONITOR_PREFIX",
"||",
"null",
";",
"this",
".",
"host",
"=",
"opt",
".",
"host",
"||",
"process",
".",
"env",
".",
"DATADOG_HOST",
";",
"this",
".",
"port",
"=",
"opt",
".",
"port",
"||",
"process",
".",
"env",
".",
"DATADOG_PORT",
";",
"this",
".",
"interval",
"=",
"opt",
".",
"interval",
"||",
"process",
".",
"env",
".",
"MONITOR_INTERVAL",
";",
"if",
"(",
"this",
".",
"host",
"&&",
"this",
".",
"port",
")",
"{",
"this",
".",
"client",
"=",
"new",
"StatsD",
"(",
"this",
".",
"host",
",",
"this",
".",
"port",
")",
";",
"this",
".",
"socketsMonitor",
"=",
"new",
"SocketsMonitor",
"(",
"this",
")",
";",
"}",
"}"
]
| Monitoring and reporting.
@class
@param {object} opt Monitor options.
@param {string} [opt.prefix] User defined event prefix.
@param {string} [opt.host] Datadog host.
@param {string} [opt.port] Datadog port.
@param {string} [opt.interval] Sockets Monitor stats poll interval | [
"Monitoring",
"and",
"reporting",
"."
]
| 040b259dfc8c6b5d934dc235f76028e5ab9094cc | https://github.com/Runnable/monitor-dog/blob/040b259dfc8c6b5d934dc235f76028e5ab9094cc/lib/monitor.js#L31-L41 |
41,878 | SalvatorePreviti/eslint-config-quick | eslint-config-quick/eslint-quick.js | eslint | function eslint(options) {
if (typeof options === 'boolean') {
options = { fail: options }
}
options = { ...new ESLintOptions(), ...options }
return new Promise((resolve, reject) => {
const args = generateArguments(options)
const child = spawn('node', args, { stdio: options.stdio, cwd: path.resolve(options.appRootPath || getRootPath()) })
function handleError(error) {
if (options.fail === false) {
resolve(false)
} else {
reject(cleanupError(error))
}
}
child.on('error', handleError)
child.on('exit', error => {
if (error) {
handleError(error)
} else {
resolve(true)
}
})
})
} | javascript | function eslint(options) {
if (typeof options === 'boolean') {
options = { fail: options }
}
options = { ...new ESLintOptions(), ...options }
return new Promise((resolve, reject) => {
const args = generateArguments(options)
const child = spawn('node', args, { stdio: options.stdio, cwd: path.resolve(options.appRootPath || getRootPath()) })
function handleError(error) {
if (options.fail === false) {
resolve(false)
} else {
reject(cleanupError(error))
}
}
child.on('error', handleError)
child.on('exit', error => {
if (error) {
handleError(error)
} else {
resolve(true)
}
})
})
} | [
"function",
"eslint",
"(",
"options",
")",
"{",
"if",
"(",
"typeof",
"options",
"===",
"'boolean'",
")",
"{",
"options",
"=",
"{",
"fail",
":",
"options",
"}",
"}",
"options",
"=",
"{",
"...",
"new",
"ESLintOptions",
"(",
")",
",",
"...",
"options",
"}",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"args",
"=",
"generateArguments",
"(",
"options",
")",
"const",
"child",
"=",
"spawn",
"(",
"'node'",
",",
"args",
",",
"{",
"stdio",
":",
"options",
".",
"stdio",
",",
"cwd",
":",
"path",
".",
"resolve",
"(",
"options",
".",
"appRootPath",
"||",
"getRootPath",
"(",
")",
")",
"}",
")",
"function",
"handleError",
"(",
"error",
")",
"{",
"if",
"(",
"options",
".",
"fail",
"===",
"false",
")",
"{",
"resolve",
"(",
"false",
")",
"}",
"else",
"{",
"reject",
"(",
"cleanupError",
"(",
"error",
")",
")",
"}",
"}",
"child",
".",
"on",
"(",
"'error'",
",",
"handleError",
")",
"child",
".",
"on",
"(",
"'exit'",
",",
"error",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"handleError",
"(",
"error",
")",
"}",
"else",
"{",
"resolve",
"(",
"true",
")",
"}",
"}",
")",
"}",
")",
"}"
]
| Executes eslint for a project, asynchronously.
@param {boolean|ESLintOptions|undefined} [options=undefined] The options to use. If a boolean, options will be { fail: true|false }.
@returns {Promise<boolean>} A promise | [
"Executes",
"eslint",
"for",
"a",
"project",
"asynchronously",
"."
]
| 371541613d86a3a3ef44ee4cb2c896e5cbcf602c | https://github.com/SalvatorePreviti/eslint-config-quick/blob/371541613d86a3a3ef44ee4cb2c896e5cbcf602c/eslint-config-quick/eslint-quick.js#L65-L93 |
41,879 | LaxarJS/laxar-tooling | src/serialize.js | serializeArray | function serializeArray( array, indent = INDENT, pad = 0, space ) {
const elements = array
.map( element => serialize( element, indent, pad + indent, space ) );
return '[' + serializeList( elements, indent, pad, space ) + ']';
} | javascript | function serializeArray( array, indent = INDENT, pad = 0, space ) {
const elements = array
.map( element => serialize( element, indent, pad + indent, space ) );
return '[' + serializeList( elements, indent, pad, space ) + ']';
} | [
"function",
"serializeArray",
"(",
"array",
",",
"indent",
"=",
"INDENT",
",",
"pad",
"=",
"0",
",",
"space",
")",
"{",
"const",
"elements",
"=",
"array",
".",
"map",
"(",
"element",
"=>",
"serialize",
"(",
"element",
",",
"indent",
",",
"pad",
"+",
"indent",
",",
"space",
")",
")",
";",
"return",
"'['",
"+",
"serializeList",
"(",
"elements",
",",
"indent",
",",
"pad",
",",
"space",
")",
"+",
"']'",
";",
"}"
]
| Serialize an array.
@private
@param {Array} array the array to serialize
@param {Number} [indent] the number of spaces to use for indent
@param {Number} [pad] the initial left padding
@param {String} [space] the character(s) to use for padding
@return {String} the serialized JavaScript code | [
"Serialize",
"an",
"array",
"."
]
| 1c4a221994f342ec03a98b68533c4de77ccfeec6 | https://github.com/LaxarJS/laxar-tooling/blob/1c4a221994f342ec03a98b68533c4de77ccfeec6/src/serialize.js#L69-L74 |
41,880 | LaxarJS/laxar-tooling | src/serialize.js | serializeObject | function serializeObject( object, indent = INDENT, pad = 0, space ) {
const properties = Object.keys( object )
.map( key => serializeKey( key ) + ': ' +
serialize( object[ key ], indent, pad + indent, space ) );
return '{' + serializeList( properties, indent, pad, space ) + '}';
} | javascript | function serializeObject( object, indent = INDENT, pad = 0, space ) {
const properties = Object.keys( object )
.map( key => serializeKey( key ) + ': ' +
serialize( object[ key ], indent, pad + indent, space ) );
return '{' + serializeList( properties, indent, pad, space ) + '}';
} | [
"function",
"serializeObject",
"(",
"object",
",",
"indent",
"=",
"INDENT",
",",
"pad",
"=",
"0",
",",
"space",
")",
"{",
"const",
"properties",
"=",
"Object",
".",
"keys",
"(",
"object",
")",
".",
"map",
"(",
"key",
"=>",
"serializeKey",
"(",
"key",
")",
"+",
"': '",
"+",
"serialize",
"(",
"object",
"[",
"key",
"]",
",",
"indent",
",",
"pad",
"+",
"indent",
",",
"space",
")",
")",
";",
"return",
"'{'",
"+",
"serializeList",
"(",
"properties",
",",
"indent",
",",
"pad",
",",
"space",
")",
"+",
"'}'",
";",
"}"
]
| Serialize an object.
@private
@param {Object} object the object to serialize
@param {Number} [indent] the number of spaces to use for indent
@param {Number} [pad] the initial left padding
@param {String} [space] the character(s) to use for padding
@return {String} the serialized JavaScript code | [
"Serialize",
"an",
"object",
"."
]
| 1c4a221994f342ec03a98b68533c4de77ccfeec6 | https://github.com/LaxarJS/laxar-tooling/blob/1c4a221994f342ec03a98b68533c4de77ccfeec6/src/serialize.js#L85-L91 |
41,881 | LaxarJS/laxar-tooling | src/serialize.js | serializeList | function serializeList( elements, indent = INDENT, pad = 0, space ) {
if( elements.length === 0 ) {
return '';
}
const length = elements.reduce( ( sum, e ) => sum + e.length + 2, pad );
const multiline = elements.some( element => /\n/.test( element ) );
const compact = length < LIST_LENGTH && !multiline;
const leader = compact ? ' ' : `\n${spaces( pad + indent, space )}`;
const trailer = compact ? ' ' : `\n${spaces( pad, space )}`;
const separator = `,${leader}`;
const body = elements.join( separator );
return `${leader}${body}${trailer}`;
} | javascript | function serializeList( elements, indent = INDENT, pad = 0, space ) {
if( elements.length === 0 ) {
return '';
}
const length = elements.reduce( ( sum, e ) => sum + e.length + 2, pad );
const multiline = elements.some( element => /\n/.test( element ) );
const compact = length < LIST_LENGTH && !multiline;
const leader = compact ? ' ' : `\n${spaces( pad + indent, space )}`;
const trailer = compact ? ' ' : `\n${spaces( pad, space )}`;
const separator = `,${leader}`;
const body = elements.join( separator );
return `${leader}${body}${trailer}`;
} | [
"function",
"serializeList",
"(",
"elements",
",",
"indent",
"=",
"INDENT",
",",
"pad",
"=",
"0",
",",
"space",
")",
"{",
"if",
"(",
"elements",
".",
"length",
"===",
"0",
")",
"{",
"return",
"''",
";",
"}",
"const",
"length",
"=",
"elements",
".",
"reduce",
"(",
"(",
"sum",
",",
"e",
")",
"=>",
"sum",
"+",
"e",
".",
"length",
"+",
"2",
",",
"pad",
")",
";",
"const",
"multiline",
"=",
"elements",
".",
"some",
"(",
"element",
"=>",
"/",
"\\n",
"/",
".",
"test",
"(",
"element",
")",
")",
";",
"const",
"compact",
"=",
"length",
"<",
"LIST_LENGTH",
"&&",
"!",
"multiline",
";",
"const",
"leader",
"=",
"compact",
"?",
"' '",
":",
"`",
"\\n",
"${",
"spaces",
"(",
"pad",
"+",
"indent",
",",
"space",
")",
"}",
"`",
";",
"const",
"trailer",
"=",
"compact",
"?",
"' '",
":",
"`",
"\\n",
"${",
"spaces",
"(",
"pad",
",",
"space",
")",
"}",
"`",
";",
"const",
"separator",
"=",
"`",
"${",
"leader",
"}",
"`",
";",
"const",
"body",
"=",
"elements",
".",
"join",
"(",
"separator",
")",
";",
"return",
"`",
"${",
"leader",
"}",
"${",
"body",
"}",
"${",
"trailer",
"}",
"`",
";",
"}"
]
| Serialize the body of a list or object.
@private
@param {Array<String>} elements the serialized elements or key-value pairs
@param {Number} [indent] the number of spaces to use for indent
@param {Number} [pad] the initial left padding
@param {String} [space] the character(s) to use for padding
@return {String} the serialized JavaScript code | [
"Serialize",
"the",
"body",
"of",
"a",
"list",
"or",
"object",
"."
]
| 1c4a221994f342ec03a98b68533c4de77ccfeec6 | https://github.com/LaxarJS/laxar-tooling/blob/1c4a221994f342ec03a98b68533c4de77ccfeec6/src/serialize.js#L102-L118 |
41,882 | LaxarJS/laxar-tooling | src/serialize.js | serializeKey | function serializeKey( name ) {
const identifier = /^[A-Za-z$_][A-Za-z0-9$_]*$/.test( name );
const keyword = [
'if', 'else',
'switch', 'case', 'default',
'try', 'catch', 'finally',
'function', 'return',
'var', 'let', 'const'
].indexOf( name ) >= 0;
return ( identifier && !keyword ) ? name : `"${name}"`;
} | javascript | function serializeKey( name ) {
const identifier = /^[A-Za-z$_][A-Za-z0-9$_]*$/.test( name );
const keyword = [
'if', 'else',
'switch', 'case', 'default',
'try', 'catch', 'finally',
'function', 'return',
'var', 'let', 'const'
].indexOf( name ) >= 0;
return ( identifier && !keyword ) ? name : `"${name}"`;
} | [
"function",
"serializeKey",
"(",
"name",
")",
"{",
"const",
"identifier",
"=",
"/",
"^[A-Za-z$_][A-Za-z0-9$_]*$",
"/",
".",
"test",
"(",
"name",
")",
";",
"const",
"keyword",
"=",
"[",
"'if'",
",",
"'else'",
",",
"'switch'",
",",
"'case'",
",",
"'default'",
",",
"'try'",
",",
"'catch'",
",",
"'finally'",
",",
"'function'",
",",
"'return'",
",",
"'var'",
",",
"'let'",
",",
"'const'",
"]",
".",
"indexOf",
"(",
"name",
")",
">=",
"0",
";",
"return",
"(",
"identifier",
"&&",
"!",
"keyword",
")",
"?",
"name",
":",
"`",
"${",
"name",
"}",
"`",
";",
"}"
]
| Serialize an object key.
Wrap the key in quotes if it is either not a valid identifier or if it
is a problematic keyword.
@private
@param {String} name the key to serialize
@return {String} the serialized key | [
"Serialize",
"an",
"object",
"key",
".",
"Wrap",
"the",
"key",
"in",
"quotes",
"if",
"it",
"is",
"either",
"not",
"a",
"valid",
"identifier",
"or",
"if",
"it",
"is",
"a",
"problematic",
"keyword",
"."
]
| 1c4a221994f342ec03a98b68533c4de77ccfeec6 | https://github.com/LaxarJS/laxar-tooling/blob/1c4a221994f342ec03a98b68533c4de77ccfeec6/src/serialize.js#L128-L139 |
41,883 | LaxarJS/laxar-tooling | src/serialize.js | serializeValue | function serializeValue( value, indent, pad, space ) {
return leftpad( JSON.stringify( value, null, indent ), pad, space );
} | javascript | function serializeValue( value, indent, pad, space ) {
return leftpad( JSON.stringify( value, null, indent ), pad, space );
} | [
"function",
"serializeValue",
"(",
"value",
",",
"indent",
",",
"pad",
",",
"space",
")",
"{",
"return",
"leftpad",
"(",
"JSON",
".",
"stringify",
"(",
"value",
",",
"null",
",",
"indent",
")",
",",
"pad",
",",
"space",
")",
";",
"}"
]
| Serialize an atomic value.
Treat as JSON and pad with spaces to the specified indent.
@private
@param {Object} value the value to serialize
@param {Number} [indent] the number of spaces to use for indent
@param {Number} [pad] the initial left padding
@param {String} [space] the character(s) to use for padding
@return {String} the serialized JavaScript code | [
"Serialize",
"an",
"atomic",
"value",
".",
"Treat",
"as",
"JSON",
"and",
"pad",
"with",
"spaces",
"to",
"the",
"specified",
"indent",
"."
]
| 1c4a221994f342ec03a98b68533c4de77ccfeec6 | https://github.com/LaxarJS/laxar-tooling/blob/1c4a221994f342ec03a98b68533c4de77ccfeec6/src/serialize.js#L151-L153 |
41,884 | LaxarJS/laxar-tooling | src/serialize.js | leftpad | function leftpad( string, pad, space ) {
return string.split( '\n' ).join( `\n${spaces( pad, space )}` );
} | javascript | function leftpad( string, pad, space ) {
return string.split( '\n' ).join( `\n${spaces( pad, space )}` );
} | [
"function",
"leftpad",
"(",
"string",
",",
"pad",
",",
"space",
")",
"{",
"return",
"string",
".",
"split",
"(",
"'\\n'",
")",
".",
"join",
"(",
"`",
"\\n",
"${",
"spaces",
"(",
"pad",
",",
"space",
")",
"}",
"`",
")",
";",
"}"
]
| Take a multi-line string and pad each line with the given number of spaces.
@private
@param {String} string the string to pad
@param {Number} [pad] the number of spaces to use for indent
@param {String} [space] the character to repeat
@return {String} a string that can be used as padding | [
"Take",
"a",
"multi",
"-",
"line",
"string",
"and",
"pad",
"each",
"line",
"with",
"the",
"given",
"number",
"of",
"spaces",
"."
]
| 1c4a221994f342ec03a98b68533c4de77ccfeec6 | https://github.com/LaxarJS/laxar-tooling/blob/1c4a221994f342ec03a98b68533c4de77ccfeec6/src/serialize.js#L174-L176 |
41,885 | byu-oit/sans-server-router | bin/router.js | Router | function Router(req, res, next) {
const server = this;
const state = {
method: req.method.toUpperCase(),
params: {},
routes: routes.concat(),
routeUnhandled: true,
server: server,
};
run(state, req, res, err => {
req.params = {};
if (state.routeUnhandled) req.log('unhandled', 'Router had no matching paths');
next(err);
});
} | javascript | function Router(req, res, next) {
const server = this;
const state = {
method: req.method.toUpperCase(),
params: {},
routes: routes.concat(),
routeUnhandled: true,
server: server,
};
run(state, req, res, err => {
req.params = {};
if (state.routeUnhandled) req.log('unhandled', 'Router had no matching paths');
next(err);
});
} | [
"function",
"Router",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"const",
"server",
"=",
"this",
";",
"const",
"state",
"=",
"{",
"method",
":",
"req",
".",
"method",
".",
"toUpperCase",
"(",
")",
",",
"params",
":",
"{",
"}",
",",
"routes",
":",
"routes",
".",
"concat",
"(",
")",
",",
"routeUnhandled",
":",
"true",
",",
"server",
":",
"server",
",",
"}",
";",
"run",
"(",
"state",
",",
"req",
",",
"res",
",",
"err",
"=>",
"{",
"req",
".",
"params",
"=",
"{",
"}",
";",
"if",
"(",
"state",
".",
"routeUnhandled",
")",
"req",
".",
"log",
"(",
"'unhandled'",
",",
"'Router had no matching paths'",
")",
";",
"next",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
]
| define the router middleware | [
"define",
"the",
"router",
"middleware"
]
| d9986804fce06c9ec20098b7923cd83e7805a2d9 | https://github.com/byu-oit/sans-server-router/blob/d9986804fce06c9ec20098b7923cd83e7805a2d9/bin/router.js#L50-L64 |
41,886 | Mammut-FE/nejm | src/util/cache/cookie.js | function(_name){
var _cookie = document.cookie,
_search = '\\b'+_name+'=',
_index1 = _cookie.search(_search);
if (_index1<0) return '';
_index1 += _search.length-2;
var _index2 = _cookie.indexOf(';',_index1);
if (_index2<0) _index2 = _cookie.length;
return _cookie.substring(_index1,_index2)||'';
} | javascript | function(_name){
var _cookie = document.cookie,
_search = '\\b'+_name+'=',
_index1 = _cookie.search(_search);
if (_index1<0) return '';
_index1 += _search.length-2;
var _index2 = _cookie.indexOf(';',_index1);
if (_index2<0) _index2 = _cookie.length;
return _cookie.substring(_index1,_index2)||'';
} | [
"function",
"(",
"_name",
")",
"{",
"var",
"_cookie",
"=",
"document",
".",
"cookie",
",",
"_search",
"=",
"'\\\\b'",
"+",
"_name",
"+",
"'='",
",",
"_index1",
"=",
"_cookie",
".",
"search",
"(",
"_search",
")",
";",
"if",
"(",
"_index1",
"<",
"0",
")",
"return",
"''",
";",
"_index1",
"+=",
"_search",
".",
"length",
"-",
"2",
";",
"var",
"_index2",
"=",
"_cookie",
".",
"indexOf",
"(",
"';'",
",",
"_index1",
")",
";",
"if",
"(",
"_index2",
"<",
"0",
")",
"_index2",
"=",
"_cookie",
".",
"length",
";",
"return",
"_cookie",
".",
"substring",
"(",
"_index1",
",",
"_index2",
")",
"||",
"''",
";",
"}"
]
| milliseconds of one day | [
"milliseconds",
"of",
"one",
"day"
]
| dfc09ac66a8d67620a7aea65e34d8a179976b3fb | https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/util/cache/cookie.js#L55-L64 |
|
41,887 | arokor/pararr.js | lib/pararr.js | add | function add(item) {
var newEnd = (end + 1) % BUF_SIZE;
if(end >= 0 && newEnd === begin) {
throw Error('Buffer overflow: Buffer exceeded max size: ' + BUF_SIZE);
}
buffer[newEnd] = item;
end = newEnd;
} | javascript | function add(item) {
var newEnd = (end + 1) % BUF_SIZE;
if(end >= 0 && newEnd === begin) {
throw Error('Buffer overflow: Buffer exceeded max size: ' + BUF_SIZE);
}
buffer[newEnd] = item;
end = newEnd;
} | [
"function",
"add",
"(",
"item",
")",
"{",
"var",
"newEnd",
"=",
"(",
"end",
"+",
"1",
")",
"%",
"BUF_SIZE",
";",
"if",
"(",
"end",
">=",
"0",
"&&",
"newEnd",
"===",
"begin",
")",
"{",
"throw",
"Error",
"(",
"'Buffer overflow: Buffer exceeded max size: '",
"+",
"BUF_SIZE",
")",
";",
"}",
"buffer",
"[",
"newEnd",
"]",
"=",
"item",
";",
"end",
"=",
"newEnd",
";",
"}"
]
| Add item to buffer | [
"Add",
"item",
"to",
"buffer"
]
| 215ddc452e24fd239b42de3997738510d1888135 | https://github.com/arokor/pararr.js/blob/215ddc452e24fd239b42de3997738510d1888135/lib/pararr.js#L31-L40 |
41,888 | arokor/pararr.js | lib/pararr.js | next | function next() {
var next;
if (end < 0) { // Buffer is empty
return null;
}
next = buffer[begin];
delete buffer[begin];
if (begin === end) { // Last element
initBuffer();
} else {
begin = (begin + 1) % BUF_SIZE;
}
return next;
} | javascript | function next() {
var next;
if (end < 0) { // Buffer is empty
return null;
}
next = buffer[begin];
delete buffer[begin];
if (begin === end) { // Last element
initBuffer();
} else {
begin = (begin + 1) % BUF_SIZE;
}
return next;
} | [
"function",
"next",
"(",
")",
"{",
"var",
"next",
";",
"if",
"(",
"end",
"<",
"0",
")",
"{",
"// Buffer is empty",
"return",
"null",
";",
"}",
"next",
"=",
"buffer",
"[",
"begin",
"]",
";",
"delete",
"buffer",
"[",
"begin",
"]",
";",
"if",
"(",
"begin",
"===",
"end",
")",
"{",
"// Last element",
"initBuffer",
"(",
")",
";",
"}",
"else",
"{",
"begin",
"=",
"(",
"begin",
"+",
"1",
")",
"%",
"BUF_SIZE",
";",
"}",
"return",
"next",
";",
"}"
]
| Get next item from buffer | [
"Get",
"next",
"item",
"from",
"buffer"
]
| 215ddc452e24fd239b42de3997738510d1888135 | https://github.com/arokor/pararr.js/blob/215ddc452e24fd239b42de3997738510d1888135/lib/pararr.js#L43-L59 |
41,889 | arokor/pararr.js | lib/pararr.js | dispatchWorkItems | function dispatchWorkItems() {
var i,
workItem;
if (!buffer.isEmpty()) {
i = workerJobCount.indexOf(0);
if(i >= 0) { //Free worker found
workItem = buffer.next();
// Send task to worker
workerExec(i, workItem);
//Check for more free workers
dispatchWorkItems();
}
}
} | javascript | function dispatchWorkItems() {
var i,
workItem;
if (!buffer.isEmpty()) {
i = workerJobCount.indexOf(0);
if(i >= 0) { //Free worker found
workItem = buffer.next();
// Send task to worker
workerExec(i, workItem);
//Check for more free workers
dispatchWorkItems();
}
}
} | [
"function",
"dispatchWorkItems",
"(",
")",
"{",
"var",
"i",
",",
"workItem",
";",
"if",
"(",
"!",
"buffer",
".",
"isEmpty",
"(",
")",
")",
"{",
"i",
"=",
"workerJobCount",
".",
"indexOf",
"(",
"0",
")",
";",
"if",
"(",
"i",
">=",
"0",
")",
"{",
"//Free worker found",
"workItem",
"=",
"buffer",
".",
"next",
"(",
")",
";",
"// Send task to worker",
"workerExec",
"(",
"i",
",",
"workItem",
")",
";",
"//Check for more free workers",
"dispatchWorkItems",
"(",
")",
";",
"}",
"}",
"}"
]
| Dispatch work items on free workers | [
"Dispatch",
"work",
"items",
"on",
"free",
"workers"
]
| 215ddc452e24fd239b42de3997738510d1888135 | https://github.com/arokor/pararr.js/blob/215ddc452e24fd239b42de3997738510d1888135/lib/pararr.js#L83-L98 |
41,890 | arokor/pararr.js | lib/pararr.js | handleArrayResult | function handleArrayResult(m, workerIdx) {
var job = jobs[m.context.jobID],
partition = m.context.partition,
subResult = m.result,
result = [],
i;
job.result[partition] = subResult;
// Increase callback count.
job.cbCount++;
// When all workers are finished return result
if(job.cbCount === workers.length) {
for (i = 0; i < job.result.length; i++) {
result = result.concat(job.result[i]);
};
// Cle
job.cb(null, result);
}
// Worker is finished.
workerJobCount[workerIdx]--;
dispatchWorkItems();
} | javascript | function handleArrayResult(m, workerIdx) {
var job = jobs[m.context.jobID],
partition = m.context.partition,
subResult = m.result,
result = [],
i;
job.result[partition] = subResult;
// Increase callback count.
job.cbCount++;
// When all workers are finished return result
if(job.cbCount === workers.length) {
for (i = 0; i < job.result.length; i++) {
result = result.concat(job.result[i]);
};
// Cle
job.cb(null, result);
}
// Worker is finished.
workerJobCount[workerIdx]--;
dispatchWorkItems();
} | [
"function",
"handleArrayResult",
"(",
"m",
",",
"workerIdx",
")",
"{",
"var",
"job",
"=",
"jobs",
"[",
"m",
".",
"context",
".",
"jobID",
"]",
",",
"partition",
"=",
"m",
".",
"context",
".",
"partition",
",",
"subResult",
"=",
"m",
".",
"result",
",",
"result",
"=",
"[",
"]",
",",
"i",
";",
"job",
".",
"result",
"[",
"partition",
"]",
"=",
"subResult",
";",
"// Increase callback count.",
"job",
".",
"cbCount",
"++",
";",
"// When all workers are finished return result",
"if",
"(",
"job",
".",
"cbCount",
"===",
"workers",
".",
"length",
")",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"job",
".",
"result",
".",
"length",
";",
"i",
"++",
")",
"{",
"result",
"=",
"result",
".",
"concat",
"(",
"job",
".",
"result",
"[",
"i",
"]",
")",
";",
"}",
";",
"// Cle",
"job",
".",
"cb",
"(",
"null",
",",
"result",
")",
";",
"}",
"// Worker is finished.",
"workerJobCount",
"[",
"workerIdx",
"]",
"--",
";",
"dispatchWorkItems",
"(",
")",
";",
"}"
]
| Handles results from parallel array operations | [
"Handles",
"results",
"from",
"parallel",
"array",
"operations"
]
| 215ddc452e24fd239b42de3997738510d1888135 | https://github.com/arokor/pararr.js/blob/215ddc452e24fd239b42de3997738510d1888135/lib/pararr.js#L124-L149 |
41,891 | arokor/pararr.js | lib/pararr.js | handleExecResult | function handleExecResult(m, workerIdx) {
var job = jobs[m.context.jobID];
job.cb(m.err, m.result);
// Worker is finished.
workerJobCount[workerIdx]--;
dispatchWorkItems();
} | javascript | function handleExecResult(m, workerIdx) {
var job = jobs[m.context.jobID];
job.cb(m.err, m.result);
// Worker is finished.
workerJobCount[workerIdx]--;
dispatchWorkItems();
} | [
"function",
"handleExecResult",
"(",
"m",
",",
"workerIdx",
")",
"{",
"var",
"job",
"=",
"jobs",
"[",
"m",
".",
"context",
".",
"jobID",
"]",
";",
"job",
".",
"cb",
"(",
"m",
".",
"err",
",",
"m",
".",
"result",
")",
";",
"// Worker is finished.",
"workerJobCount",
"[",
"workerIdx",
"]",
"--",
";",
"dispatchWorkItems",
"(",
")",
";",
"}"
]
| Handles results from parallel function execution | [
"Handles",
"results",
"from",
"parallel",
"function",
"execution"
]
| 215ddc452e24fd239b42de3997738510d1888135 | https://github.com/arokor/pararr.js/blob/215ddc452e24fd239b42de3997738510d1888135/lib/pararr.js#L152-L160 |
41,892 | arokor/pararr.js | lib/pararr.js | handleMessage | function handleMessage(m, workerIdx) {
var job = jobs[m.context.jobID];
switch(job.type) {
case 'func':
handleArrayResult(m, workerIdx);
break;
case 'exec':
handleExecResult(m, workerIdx);
break;
default:
throw Error('Invalid job type: ' + job.type);
}
} | javascript | function handleMessage(m, workerIdx) {
var job = jobs[m.context.jobID];
switch(job.type) {
case 'func':
handleArrayResult(m, workerIdx);
break;
case 'exec':
handleExecResult(m, workerIdx);
break;
default:
throw Error('Invalid job type: ' + job.type);
}
} | [
"function",
"handleMessage",
"(",
"m",
",",
"workerIdx",
")",
"{",
"var",
"job",
"=",
"jobs",
"[",
"m",
".",
"context",
".",
"jobID",
"]",
";",
"switch",
"(",
"job",
".",
"type",
")",
"{",
"case",
"'func'",
":",
"handleArrayResult",
"(",
"m",
",",
"workerIdx",
")",
";",
"break",
";",
"case",
"'exec'",
":",
"handleExecResult",
"(",
"m",
",",
"workerIdx",
")",
";",
"break",
";",
"default",
":",
"throw",
"Error",
"(",
"'Invalid job type: '",
"+",
"job",
".",
"type",
")",
";",
"}",
"}"
]
| Handles messages from the workers | [
"Handles",
"messages",
"from",
"the",
"workers"
]
| 215ddc452e24fd239b42de3997738510d1888135 | https://github.com/arokor/pararr.js/blob/215ddc452e24fd239b42de3997738510d1888135/lib/pararr.js#L163-L176 |
41,893 | arokor/pararr.js | lib/pararr.js | executeParallel | function executeParallel(op, arr, iter, cb) {
var chunkSize = Math.floor(arr.length / numCPUs),
worker,
iterStr,
task,
offset,
i;
// Lazy initialization
init();
// Check params
if (!cb) {
throw Error('Expected callback');
}
if (arr == null) {
cb(null, []);
return;
}
if (!Array.isArray(arr)) {
cb(Error('Expected array'));
return;
}
if (typeof iter !== 'function') {
cb(Error('Expected iterator function'));
return;
}
if (!isValidOP(op)) {
cb(Error('Expected valid operation but got ' + op));
return;
}
iterStr = iter.toString(); //Serialize iter
for (i = 0; i < workers.length; i++) {
worker = workers[i];
offset = chunkSize * i;
task = {
type: 'func',
op: op,
data: (i === workers.length - 1 ? arr.slice(offset) : arr.slice(offset, offset + chunkSize)), // Partition arr
iter: iterStr,
context: {
partition: i,
jobID: jobID
}
};
// Send task to worker
// worker.send(task);
buffer.add(task);
}
dispatchWorkItems();
// Store job
jobs[jobID] = {
type: 'func',
result: [],
cbCount: 0,
cb: cb
};
// Increase jobID
jobID++;
} | javascript | function executeParallel(op, arr, iter, cb) {
var chunkSize = Math.floor(arr.length / numCPUs),
worker,
iterStr,
task,
offset,
i;
// Lazy initialization
init();
// Check params
if (!cb) {
throw Error('Expected callback');
}
if (arr == null) {
cb(null, []);
return;
}
if (!Array.isArray(arr)) {
cb(Error('Expected array'));
return;
}
if (typeof iter !== 'function') {
cb(Error('Expected iterator function'));
return;
}
if (!isValidOP(op)) {
cb(Error('Expected valid operation but got ' + op));
return;
}
iterStr = iter.toString(); //Serialize iter
for (i = 0; i < workers.length; i++) {
worker = workers[i];
offset = chunkSize * i;
task = {
type: 'func',
op: op,
data: (i === workers.length - 1 ? arr.slice(offset) : arr.slice(offset, offset + chunkSize)), // Partition arr
iter: iterStr,
context: {
partition: i,
jobID: jobID
}
};
// Send task to worker
// worker.send(task);
buffer.add(task);
}
dispatchWorkItems();
// Store job
jobs[jobID] = {
type: 'func',
result: [],
cbCount: 0,
cb: cb
};
// Increase jobID
jobID++;
} | [
"function",
"executeParallel",
"(",
"op",
",",
"arr",
",",
"iter",
",",
"cb",
")",
"{",
"var",
"chunkSize",
"=",
"Math",
".",
"floor",
"(",
"arr",
".",
"length",
"/",
"numCPUs",
")",
",",
"worker",
",",
"iterStr",
",",
"task",
",",
"offset",
",",
"i",
";",
"// Lazy initialization",
"init",
"(",
")",
";",
"// Check params",
"if",
"(",
"!",
"cb",
")",
"{",
"throw",
"Error",
"(",
"'Expected callback'",
")",
";",
"}",
"if",
"(",
"arr",
"==",
"null",
")",
"{",
"cb",
"(",
"null",
",",
"[",
"]",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"arr",
")",
")",
"{",
"cb",
"(",
"Error",
"(",
"'Expected array'",
")",
")",
";",
"return",
";",
"}",
"if",
"(",
"typeof",
"iter",
"!==",
"'function'",
")",
"{",
"cb",
"(",
"Error",
"(",
"'Expected iterator function'",
")",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"isValidOP",
"(",
"op",
")",
")",
"{",
"cb",
"(",
"Error",
"(",
"'Expected valid operation but got '",
"+",
"op",
")",
")",
";",
"return",
";",
"}",
"iterStr",
"=",
"iter",
".",
"toString",
"(",
")",
";",
"//Serialize iter",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"workers",
".",
"length",
";",
"i",
"++",
")",
"{",
"worker",
"=",
"workers",
"[",
"i",
"]",
";",
"offset",
"=",
"chunkSize",
"*",
"i",
";",
"task",
"=",
"{",
"type",
":",
"'func'",
",",
"op",
":",
"op",
",",
"data",
":",
"(",
"i",
"===",
"workers",
".",
"length",
"-",
"1",
"?",
"arr",
".",
"slice",
"(",
"offset",
")",
":",
"arr",
".",
"slice",
"(",
"offset",
",",
"offset",
"+",
"chunkSize",
")",
")",
",",
"// Partition arr",
"iter",
":",
"iterStr",
",",
"context",
":",
"{",
"partition",
":",
"i",
",",
"jobID",
":",
"jobID",
"}",
"}",
";",
"// Send task to worker",
"// worker.send(task);",
"buffer",
".",
"add",
"(",
"task",
")",
";",
"}",
"dispatchWorkItems",
"(",
")",
";",
"// Store job",
"jobs",
"[",
"jobID",
"]",
"=",
"{",
"type",
":",
"'func'",
",",
"result",
":",
"[",
"]",
",",
"cbCount",
":",
"0",
",",
"cb",
":",
"cb",
"}",
";",
"// Increase jobID",
"jobID",
"++",
";",
"}"
]
| Execute an array operation in parallel | [
"Execute",
"an",
"array",
"operation",
"in",
"parallel"
]
| 215ddc452e24fd239b42de3997738510d1888135 | https://github.com/arokor/pararr.js/blob/215ddc452e24fd239b42de3997738510d1888135/lib/pararr.js#L186-L252 |
41,894 | arokor/pararr.js | lib/pararr.js | merge | function merge(arrays, comp) {
var mid,
a1, i1,
a2, i2,
result;
if (arrays.length === 1) {
return arrays[0];
} else if (arrays.length === 2) {
// merge two arrays
a1 = arrays[0];
a2 = arrays[1];
i1 = i2 = 0;
result = [];
while(i1 < a1.length && i2 < a2.length) {
if (comp(a2[i2], a1[i1]) > 0) {
result.push(a1[i1]);
i1++;
} else {
result.push(a2[i2]);
i2++;
}
}
while(i1 < a1.length) {
result.push(a1[i1]);
i1++;
}
while(i2 < a2.length) {
result.push(a2[i2]);
i2++;
}
return result;
} else {
mid = Math.floor(arrays.length / 2);
return merge([
merge(arrays.slice(0, mid), comp),
merge(arrays.slice(mid), comp)
], comp);
}
} | javascript | function merge(arrays, comp) {
var mid,
a1, i1,
a2, i2,
result;
if (arrays.length === 1) {
return arrays[0];
} else if (arrays.length === 2) {
// merge two arrays
a1 = arrays[0];
a2 = arrays[1];
i1 = i2 = 0;
result = [];
while(i1 < a1.length && i2 < a2.length) {
if (comp(a2[i2], a1[i1]) > 0) {
result.push(a1[i1]);
i1++;
} else {
result.push(a2[i2]);
i2++;
}
}
while(i1 < a1.length) {
result.push(a1[i1]);
i1++;
}
while(i2 < a2.length) {
result.push(a2[i2]);
i2++;
}
return result;
} else {
mid = Math.floor(arrays.length / 2);
return merge([
merge(arrays.slice(0, mid), comp),
merge(arrays.slice(mid), comp)
], comp);
}
} | [
"function",
"merge",
"(",
"arrays",
",",
"comp",
")",
"{",
"var",
"mid",
",",
"a1",
",",
"i1",
",",
"a2",
",",
"i2",
",",
"result",
";",
"if",
"(",
"arrays",
".",
"length",
"===",
"1",
")",
"{",
"return",
"arrays",
"[",
"0",
"]",
";",
"}",
"else",
"if",
"(",
"arrays",
".",
"length",
"===",
"2",
")",
"{",
"// merge two arrays",
"a1",
"=",
"arrays",
"[",
"0",
"]",
";",
"a2",
"=",
"arrays",
"[",
"1",
"]",
";",
"i1",
"=",
"i2",
"=",
"0",
";",
"result",
"=",
"[",
"]",
";",
"while",
"(",
"i1",
"<",
"a1",
".",
"length",
"&&",
"i2",
"<",
"a2",
".",
"length",
")",
"{",
"if",
"(",
"comp",
"(",
"a2",
"[",
"i2",
"]",
",",
"a1",
"[",
"i1",
"]",
")",
">",
"0",
")",
"{",
"result",
".",
"push",
"(",
"a1",
"[",
"i1",
"]",
")",
";",
"i1",
"++",
";",
"}",
"else",
"{",
"result",
".",
"push",
"(",
"a2",
"[",
"i2",
"]",
")",
";",
"i2",
"++",
";",
"}",
"}",
"while",
"(",
"i1",
"<",
"a1",
".",
"length",
")",
"{",
"result",
".",
"push",
"(",
"a1",
"[",
"i1",
"]",
")",
";",
"i1",
"++",
";",
"}",
"while",
"(",
"i2",
"<",
"a2",
".",
"length",
")",
"{",
"result",
".",
"push",
"(",
"a2",
"[",
"i2",
"]",
")",
";",
"i2",
"++",
";",
"}",
"return",
"result",
";",
"}",
"else",
"{",
"mid",
"=",
"Math",
".",
"floor",
"(",
"arrays",
".",
"length",
"/",
"2",
")",
";",
"return",
"merge",
"(",
"[",
"merge",
"(",
"arrays",
".",
"slice",
"(",
"0",
",",
"mid",
")",
",",
"comp",
")",
",",
"merge",
"(",
"arrays",
".",
"slice",
"(",
"mid",
")",
",",
"comp",
")",
"]",
",",
"comp",
")",
";",
"}",
"}"
]
| Merge a number of arrays | [
"Merge",
"a",
"number",
"of",
"arrays"
]
| 215ddc452e24fd239b42de3997738510d1888135 | https://github.com/arokor/pararr.js/blob/215ddc452e24fd239b42de3997738510d1888135/lib/pararr.js#L342-L382 |
41,895 | arokor/pararr.js | lib/pararr.js | defaultComp | function defaultComp(a,b) {
var as = '' + a,
bs = '' + b;
if (as < bs) {
return -1;
} else if (as > bs) {
return 1;
} else {
return 0;
}
} | javascript | function defaultComp(a,b) {
var as = '' + a,
bs = '' + b;
if (as < bs) {
return -1;
} else if (as > bs) {
return 1;
} else {
return 0;
}
} | [
"function",
"defaultComp",
"(",
"a",
",",
"b",
")",
"{",
"var",
"as",
"=",
"''",
"+",
"a",
",",
"bs",
"=",
"''",
"+",
"b",
";",
"if",
"(",
"as",
"<",
"bs",
")",
"{",
"return",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"as",
">",
"bs",
")",
"{",
"return",
"1",
";",
"}",
"else",
"{",
"return",
"0",
";",
"}",
"}"
]
| The default comparator | [
"The",
"default",
"comparator"
]
| 215ddc452e24fd239b42de3997738510d1888135 | https://github.com/arokor/pararr.js/blob/215ddc452e24fd239b42de3997738510d1888135/lib/pararr.js#L385-L396 |
41,896 | arokor/pararr.js | lib/pararr.js | constructSortingFunction | function constructSortingFunction(comp) {
var funcStr = 'function(arr) { return arr.sort(%comp%); };',
func;
funcStr = funcStr.replace('%comp%', comp.toString());
// Eval is evil but necessary in this case
eval('func = '+ funcStr);
return func;
} | javascript | function constructSortingFunction(comp) {
var funcStr = 'function(arr) { return arr.sort(%comp%); };',
func;
funcStr = funcStr.replace('%comp%', comp.toString());
// Eval is evil but necessary in this case
eval('func = '+ funcStr);
return func;
} | [
"function",
"constructSortingFunction",
"(",
"comp",
")",
"{",
"var",
"funcStr",
"=",
"'function(arr) { return arr.sort(%comp%); };'",
",",
"func",
";",
"funcStr",
"=",
"funcStr",
".",
"replace",
"(",
"'%comp%'",
",",
"comp",
".",
"toString",
"(",
")",
")",
";",
"// Eval is evil but necessary in this case",
"eval",
"(",
"'func = '",
"+",
"funcStr",
")",
";",
"return",
"func",
";",
"}"
]
| Construct a sorting function for a specific comparator | [
"Construct",
"a",
"sorting",
"function",
"for",
"a",
"specific",
"comparator"
]
| 215ddc452e24fd239b42de3997738510d1888135 | https://github.com/arokor/pararr.js/blob/215ddc452e24fd239b42de3997738510d1888135/lib/pararr.js#L399-L407 |
41,897 | veo-labs/openveo-api | lib/grunt/ngDpTask/ngDpTask.js | mergeResults | function mergeResults(newResults) {
if (newResults.definitions)
results.definitions = utilApi.joinArray(results.definitions, newResults.definitions);
if (newResults.dependencies)
results.dependencies = utilApi.joinArray(results.dependencies, newResults.dependencies);
if (newResults.module)
results.module = newResults.module;
} | javascript | function mergeResults(newResults) {
if (newResults.definitions)
results.definitions = utilApi.joinArray(results.definitions, newResults.definitions);
if (newResults.dependencies)
results.dependencies = utilApi.joinArray(results.dependencies, newResults.dependencies);
if (newResults.module)
results.module = newResults.module;
} | [
"function",
"mergeResults",
"(",
"newResults",
")",
"{",
"if",
"(",
"newResults",
".",
"definitions",
")",
"results",
".",
"definitions",
"=",
"utilApi",
".",
"joinArray",
"(",
"results",
".",
"definitions",
",",
"newResults",
".",
"definitions",
")",
";",
"if",
"(",
"newResults",
".",
"dependencies",
")",
"results",
".",
"dependencies",
"=",
"utilApi",
".",
"joinArray",
"(",
"results",
".",
"dependencies",
",",
"newResults",
".",
"dependencies",
")",
";",
"if",
"(",
"newResults",
".",
"module",
")",
"results",
".",
"module",
"=",
"newResults",
".",
"module",
";",
"}"
]
| Merges results from sub expressions into results for the current expression.
@param {Object} newResults Sub expressions results
@param {Array} [newResults.definitions] The list of definitions in sub expression
@param {Array} [newResults.dependencies] The list of dependencies in sub expression
@param {String} [newResults.module] The name of the module the definitions belong to | [
"Merges",
"results",
"from",
"sub",
"expressions",
"into",
"results",
"for",
"the",
"current",
"expression",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/grunt/ngDpTask/ngDpTask.js#L66-L75 |
41,898 | veo-labs/openveo-api | lib/grunt/ngDpTask/ngDpTask.js | findScript | function findScript(scripts, property, value) {
for (var i = 0; i < scripts.length; i++) {
if ((Object.prototype.toString.call(scripts[i][property]) === '[object Array]' &&
scripts[i][property].indexOf(value) > -1) ||
(scripts[i][property] === value)
) {
return scripts[i];
}
}
return null;
} | javascript | function findScript(scripts, property, value) {
for (var i = 0; i < scripts.length; i++) {
if ((Object.prototype.toString.call(scripts[i][property]) === '[object Array]' &&
scripts[i][property].indexOf(value) > -1) ||
(scripts[i][property] === value)
) {
return scripts[i];
}
}
return null;
} | [
"function",
"findScript",
"(",
"scripts",
",",
"property",
",",
"value",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"scripts",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"(",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"scripts",
"[",
"i",
"]",
"[",
"property",
"]",
")",
"===",
"'[object Array]'",
"&&",
"scripts",
"[",
"i",
"]",
"[",
"property",
"]",
".",
"indexOf",
"(",
"value",
")",
">",
"-",
"1",
")",
"||",
"(",
"scripts",
"[",
"i",
"]",
"[",
"property",
"]",
"===",
"value",
")",
")",
"{",
"return",
"scripts",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"null",
";",
"}"
]
| Fetches a script from a list of scripts.
@method findScript
@param {Array} scripts The list of scripts
@param {String} property The script property used to identify the script to fetch
@param {String} value The expected value of the script property
@return {Object|Null} The found script or null if not found
@private | [
"Fetches",
"a",
"script",
"from",
"a",
"list",
"of",
"scripts",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/grunt/ngDpTask/ngDpTask.js#L156-L167 |
41,899 | veo-labs/openveo-api | lib/grunt/ngDpTask/ngDpTask.js | findLongestDependencyChains | function findLongestDependencyChains(scripts, script, modulesToIgnore) {
var chains = [];
if (!script) script = scripts[0];
// Avoid circular dependencies
if (modulesToIgnore && script.module && modulesToIgnore.indexOf(script.module) !== -1) return chains;
// Get script dependencies
if (script.dependencies && script.dependencies.length) {
var longestChainLength;
// Find dependency chains of the script
script.dependencies.forEach(function(dependency) {
var definitionScript = findScript(scripts, 'definitions', dependency);
if (definitionScript)
chains = chains.concat(findLongestDependencyChains(scripts, definitionScript, script.definitions));
});
if (chains.length > 0) {
// Keep the longest chain(s)
chains.sort(function(chain1, chain2) {
// -1 : chain1 before chain2
// 0 : nothing change
// 1 : chain1 after chain2
if (chain1.length > chain2.length)
return -1;
else if (chain1.length < chain2.length)
return 1;
else return 0;
});
longestChainLength = chains[0].length;
chains = chains.filter(function(chain) {
if (chain.length === longestChainLength) {
chain.push(script.path);
return true;
}
return false;
});
return chains;
}
}
chains.push([script.path]);
return chains;
} | javascript | function findLongestDependencyChains(scripts, script, modulesToIgnore) {
var chains = [];
if (!script) script = scripts[0];
// Avoid circular dependencies
if (modulesToIgnore && script.module && modulesToIgnore.indexOf(script.module) !== -1) return chains;
// Get script dependencies
if (script.dependencies && script.dependencies.length) {
var longestChainLength;
// Find dependency chains of the script
script.dependencies.forEach(function(dependency) {
var definitionScript = findScript(scripts, 'definitions', dependency);
if (definitionScript)
chains = chains.concat(findLongestDependencyChains(scripts, definitionScript, script.definitions));
});
if (chains.length > 0) {
// Keep the longest chain(s)
chains.sort(function(chain1, chain2) {
// -1 : chain1 before chain2
// 0 : nothing change
// 1 : chain1 after chain2
if (chain1.length > chain2.length)
return -1;
else if (chain1.length < chain2.length)
return 1;
else return 0;
});
longestChainLength = chains[0].length;
chains = chains.filter(function(chain) {
if (chain.length === longestChainLength) {
chain.push(script.path);
return true;
}
return false;
});
return chains;
}
}
chains.push([script.path]);
return chains;
} | [
"function",
"findLongestDependencyChains",
"(",
"scripts",
",",
"script",
",",
"modulesToIgnore",
")",
"{",
"var",
"chains",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"script",
")",
"script",
"=",
"scripts",
"[",
"0",
"]",
";",
"// Avoid circular dependencies",
"if",
"(",
"modulesToIgnore",
"&&",
"script",
".",
"module",
"&&",
"modulesToIgnore",
".",
"indexOf",
"(",
"script",
".",
"module",
")",
"!==",
"-",
"1",
")",
"return",
"chains",
";",
"// Get script dependencies",
"if",
"(",
"script",
".",
"dependencies",
"&&",
"script",
".",
"dependencies",
".",
"length",
")",
"{",
"var",
"longestChainLength",
";",
"// Find dependency chains of the script",
"script",
".",
"dependencies",
".",
"forEach",
"(",
"function",
"(",
"dependency",
")",
"{",
"var",
"definitionScript",
"=",
"findScript",
"(",
"scripts",
",",
"'definitions'",
",",
"dependency",
")",
";",
"if",
"(",
"definitionScript",
")",
"chains",
"=",
"chains",
".",
"concat",
"(",
"findLongestDependencyChains",
"(",
"scripts",
",",
"definitionScript",
",",
"script",
".",
"definitions",
")",
")",
";",
"}",
")",
";",
"if",
"(",
"chains",
".",
"length",
">",
"0",
")",
"{",
"// Keep the longest chain(s)",
"chains",
".",
"sort",
"(",
"function",
"(",
"chain1",
",",
"chain2",
")",
"{",
"// -1 : chain1 before chain2",
"// 0 : nothing change",
"// 1 : chain1 after chain2",
"if",
"(",
"chain1",
".",
"length",
">",
"chain2",
".",
"length",
")",
"return",
"-",
"1",
";",
"else",
"if",
"(",
"chain1",
".",
"length",
"<",
"chain2",
".",
"length",
")",
"return",
"1",
";",
"else",
"return",
"0",
";",
"}",
")",
";",
"longestChainLength",
"=",
"chains",
"[",
"0",
"]",
".",
"length",
";",
"chains",
"=",
"chains",
".",
"filter",
"(",
"function",
"(",
"chain",
")",
"{",
"if",
"(",
"chain",
".",
"length",
"===",
"longestChainLength",
")",
"{",
"chain",
".",
"push",
"(",
"script",
".",
"path",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
")",
";",
"return",
"chains",
";",
"}",
"}",
"chains",
".",
"push",
"(",
"[",
"script",
".",
"path",
"]",
")",
";",
"return",
"chains",
";",
"}"
]
| Browses a flat list of scripts to find a script longest dependency chains.
Each script may have several dependencies, each dependency can also have several dependencies.
findLongestDependencyChains helps find the longest dependency chain of one of the script.
As the script may have several longest dependency chain, a list of chains is returned.
A chain is an ordered list of script paths.
This is recursive.
@method findLongestDependencyChains
@param {Array} scripts The flat list of scripts with for each script:
- **dependencies** The list of dependency names of the script
- **definitions** The list of definition names of the script
- **path** The script path
@param {Object} [script] The script to analyze (default to the first one of the list of scripts)
@param {Array} [modulesToIgnore] The list of module names to ignore to avoid circular dependencies
@return {Array} The longest dependency chains
@private | [
"Browses",
"a",
"flat",
"list",
"of",
"scripts",
"to",
"find",
"a",
"script",
"longest",
"dependency",
"chains",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/grunt/ngDpTask/ngDpTask.js#L190-L242 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.