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
|
---|---|---|---|---|---|---|---|---|---|---|---|
45,200 | edappy/seneca-context | index.js | getContext | function getContext(seneca) {
var transactionId = seneca.fixedargs.tx$;
var context = seneca.fixedargs.context$;
if (typeof context === 'undefined') {
try {
context = seneca.fixedargs.context$ = JSON.parse(URLSafeBase64.decode(transactionId).toString('utf8'));
debug('context loaded from tx$ and cached in context$', transactionId, context);
} catch (error) {
context = null;
debug('context cannot be loaded from tx$', transactionId, error);
}
} else {
debug('context loaded from context$', transactionId, context);
}
return context;
} | javascript | function getContext(seneca) {
var transactionId = seneca.fixedargs.tx$;
var context = seneca.fixedargs.context$;
if (typeof context === 'undefined') {
try {
context = seneca.fixedargs.context$ = JSON.parse(URLSafeBase64.decode(transactionId).toString('utf8'));
debug('context loaded from tx$ and cached in context$', transactionId, context);
} catch (error) {
context = null;
debug('context cannot be loaded from tx$', transactionId, error);
}
} else {
debug('context loaded from context$', transactionId, context);
}
return context;
} | [
"function",
"getContext",
"(",
"seneca",
")",
"{",
"var",
"transactionId",
"=",
"seneca",
".",
"fixedargs",
".",
"tx$",
";",
"var",
"context",
"=",
"seneca",
".",
"fixedargs",
".",
"context$",
";",
"if",
"(",
"typeof",
"context",
"===",
"'undefined'",
")",
"{",
"try",
"{",
"context",
"=",
"seneca",
".",
"fixedargs",
".",
"context$",
"=",
"JSON",
".",
"parse",
"(",
"URLSafeBase64",
".",
"decode",
"(",
"transactionId",
")",
".",
"toString",
"(",
"'utf8'",
")",
")",
";",
"debug",
"(",
"'context loaded from tx$ and cached in context$'",
",",
"transactionId",
",",
"context",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"context",
"=",
"null",
";",
"debug",
"(",
"'context cannot be loaded from tx$'",
",",
"transactionId",
",",
"error",
")",
";",
"}",
"}",
"else",
"{",
"debug",
"(",
"'context loaded from context$'",
",",
"transactionId",
",",
"context",
")",
";",
"}",
"return",
"context",
";",
"}"
]
| Loads the context from the seneca transaction ID.
@param {seneca} seneca The seneca object, which is the context of a running action.
@returns {Object} A context object | [
"Loads",
"the",
"context",
"from",
"the",
"seneca",
"transaction",
"ID",
"."
]
| 1e0c8d36c5be4b661b062754c01f064de47873c4 | https://github.com/edappy/seneca-context/blob/1e0c8d36c5be4b661b062754c01f064de47873c4/index.js#L17-L34 |
45,201 | edappy/seneca-context | index.js | setContext | function setContext(seneca, context) {
seneca.fixedargs.tx$ = URLSafeBase64.encode(new Buffer(JSON.stringify(context)));
seneca.fixedargs.context$ = context;
debug('context saved', seneca.fixedargs.tx$, context);
} | javascript | function setContext(seneca, context) {
seneca.fixedargs.tx$ = URLSafeBase64.encode(new Buffer(JSON.stringify(context)));
seneca.fixedargs.context$ = context;
debug('context saved', seneca.fixedargs.tx$, context);
} | [
"function",
"setContext",
"(",
"seneca",
",",
"context",
")",
"{",
"seneca",
".",
"fixedargs",
".",
"tx$",
"=",
"URLSafeBase64",
".",
"encode",
"(",
"new",
"Buffer",
"(",
"JSON",
".",
"stringify",
"(",
"context",
")",
")",
")",
";",
"seneca",
".",
"fixedargs",
".",
"context$",
"=",
"context",
";",
"debug",
"(",
"'context saved'",
",",
"seneca",
".",
"fixedargs",
".",
"tx$",
",",
"context",
")",
";",
"}"
]
| Saves the specified context inside the seneca transaction ID.
@param {seneca} seneca The seneca object, which is the context of a running action.
@param {Object} context A context object | [
"Saves",
"the",
"specified",
"context",
"inside",
"the",
"seneca",
"transaction",
"ID",
"."
]
| 1e0c8d36c5be4b661b062754c01f064de47873c4 | https://github.com/edappy/seneca-context/blob/1e0c8d36c5be4b661b062754c01f064de47873c4/index.js#L42-L46 |
45,202 | cfpb/AtomicComponent | src/utilities/transition/BaseTransition.js | setElement | function setElement( targetElement ) {
// If the element has already been set,
// clear the transition classes from the old element.
if ( _dom ) {
remove();
animateOn();
}
_dom = targetElement;
_dom.classList.add( _classes.BASE_CLASS );
_transitionEndEvent = _getTransitionEndEvent( _dom );
} | javascript | function setElement( targetElement ) {
// If the element has already been set,
// clear the transition classes from the old element.
if ( _dom ) {
remove();
animateOn();
}
_dom = targetElement;
_dom.classList.add( _classes.BASE_CLASS );
_transitionEndEvent = _getTransitionEndEvent( _dom );
} | [
"function",
"setElement",
"(",
"targetElement",
")",
"{",
"// If the element has already been set,",
"// clear the transition classes from the old element.",
"if",
"(",
"_dom",
")",
"{",
"remove",
"(",
")",
";",
"animateOn",
"(",
")",
";",
"}",
"_dom",
"=",
"targetElement",
";",
"_dom",
".",
"classList",
".",
"add",
"(",
"_classes",
".",
"BASE_CLASS",
")",
";",
"_transitionEndEvent",
"=",
"_getTransitionEndEvent",
"(",
"_dom",
")",
";",
"}"
]
| Set the HTML element target of this transition.
@param {HTMLNode} targetElement - The target of the transition. | [
"Set",
"the",
"HTML",
"element",
"target",
"of",
"this",
"transition",
"."
]
| f45d7ded6687672c8b701c9910ddfe90c7ede742 | https://github.com/cfpb/AtomicComponent/blob/f45d7ded6687672c8b701c9910ddfe90c7ede742/src/utilities/transition/BaseTransition.js#L47-L57 |
45,203 | cfpb/AtomicComponent | src/utilities/transition/BaseTransition.js | halt | function halt() {
if ( !_isAnimating ) { return; }
_dom.style.webkitTransitionDuration = '0';
_dom.style.mozTransitionDuration = '0';
_dom.style.oTransitionDuration = '0';
_dom.style.transitionDuration = '0';
_dom.removeEventListener( _transitionEndEvent,
_transitionCompleteBinded );
_transitionCompleteBinded();
_dom.style.webkitTransitionDuration = '';
_dom.style.mozTransitionDuration = '';
_dom.style.oTransitionDuration = '';
_dom.style.transitionDuration = '';
} | javascript | function halt() {
if ( !_isAnimating ) { return; }
_dom.style.webkitTransitionDuration = '0';
_dom.style.mozTransitionDuration = '0';
_dom.style.oTransitionDuration = '0';
_dom.style.transitionDuration = '0';
_dom.removeEventListener( _transitionEndEvent,
_transitionCompleteBinded );
_transitionCompleteBinded();
_dom.style.webkitTransitionDuration = '';
_dom.style.mozTransitionDuration = '';
_dom.style.oTransitionDuration = '';
_dom.style.transitionDuration = '';
} | [
"function",
"halt",
"(",
")",
"{",
"if",
"(",
"!",
"_isAnimating",
")",
"{",
"return",
";",
"}",
"_dom",
".",
"style",
".",
"webkitTransitionDuration",
"=",
"'0'",
";",
"_dom",
".",
"style",
".",
"mozTransitionDuration",
"=",
"'0'",
";",
"_dom",
".",
"style",
".",
"oTransitionDuration",
"=",
"'0'",
";",
"_dom",
".",
"style",
".",
"transitionDuration",
"=",
"'0'",
";",
"_dom",
".",
"removeEventListener",
"(",
"_transitionEndEvent",
",",
"_transitionCompleteBinded",
")",
";",
"_transitionCompleteBinded",
"(",
")",
";",
"_dom",
".",
"style",
".",
"webkitTransitionDuration",
"=",
"''",
";",
"_dom",
".",
"style",
".",
"mozTransitionDuration",
"=",
"''",
";",
"_dom",
".",
"style",
".",
"oTransitionDuration",
"=",
"''",
";",
"_dom",
".",
"style",
".",
"transitionDuration",
"=",
"''",
";",
"}"
]
| Halt an in-progress animation and call the complete event immediately. | [
"Halt",
"an",
"in",
"-",
"progress",
"animation",
"and",
"call",
"the",
"complete",
"event",
"immediately",
"."
]
| f45d7ded6687672c8b701c9910ddfe90c7ede742 | https://github.com/cfpb/AtomicComponent/blob/f45d7ded6687672c8b701c9910ddfe90c7ede742/src/utilities/transition/BaseTransition.js#L93-L106 |
45,204 | cfpb/AtomicComponent | src/utilities/transition/BaseTransition.js | _addEventListener | function _addEventListener() {
_isAnimating = true;
// If transition is not supported, call handler directly (IE9/OperaMini).
if ( _transitionEndEvent ) {
_dom.addEventListener( _transitionEndEvent,
_transitionCompleteBinded );
this.trigger( BaseTransition.BEGIN_EVENT, { target: this } );
} else {
this.trigger( BaseTransition.BEGIN_EVENT, { target: this } );
_transitionCompleteBinded();
}
} | javascript | function _addEventListener() {
_isAnimating = true;
// If transition is not supported, call handler directly (IE9/OperaMini).
if ( _transitionEndEvent ) {
_dom.addEventListener( _transitionEndEvent,
_transitionCompleteBinded );
this.trigger( BaseTransition.BEGIN_EVENT, { target: this } );
} else {
this.trigger( BaseTransition.BEGIN_EVENT, { target: this } );
_transitionCompleteBinded();
}
} | [
"function",
"_addEventListener",
"(",
")",
"{",
"_isAnimating",
"=",
"true",
";",
"// If transition is not supported, call handler directly (IE9/OperaMini).",
"if",
"(",
"_transitionEndEvent",
")",
"{",
"_dom",
".",
"addEventListener",
"(",
"_transitionEndEvent",
",",
"_transitionCompleteBinded",
")",
";",
"this",
".",
"trigger",
"(",
"BaseTransition",
".",
"BEGIN_EVENT",
",",
"{",
"target",
":",
"this",
"}",
")",
";",
"}",
"else",
"{",
"this",
".",
"trigger",
"(",
"BaseTransition",
".",
"BEGIN_EVENT",
",",
"{",
"target",
":",
"this",
"}",
")",
";",
"_transitionCompleteBinded",
"(",
")",
";",
"}",
"}"
]
| Add an event listener to the transition, or call the transition
complete handler immediately if transition not supported. | [
"Add",
"an",
"event",
"listener",
"to",
"the",
"transition",
"or",
"call",
"the",
"transition",
"complete",
"handler",
"immediately",
"if",
"transition",
"not",
"supported",
"."
]
| f45d7ded6687672c8b701c9910ddfe90c7ede742 | https://github.com/cfpb/AtomicComponent/blob/f45d7ded6687672c8b701c9910ddfe90c7ede742/src/utilities/transition/BaseTransition.js#L112-L123 |
45,205 | cfpb/AtomicComponent | src/utilities/transition/BaseTransition.js | _flush | function _flush() {
for ( const prop in _classes ) {
if ( _classes.hasOwnProperty( prop ) &&
_classes[prop] !== _classes.BASE_CLASS &&
_dom.classList.contains( _classes[prop] ) ) {
_dom.classList.remove( _classes[prop] );
}
}
} | javascript | function _flush() {
for ( const prop in _classes ) {
if ( _classes.hasOwnProperty( prop ) &&
_classes[prop] !== _classes.BASE_CLASS &&
_dom.classList.contains( _classes[prop] ) ) {
_dom.classList.remove( _classes[prop] );
}
}
} | [
"function",
"_flush",
"(",
")",
"{",
"for",
"(",
"const",
"prop",
"in",
"_classes",
")",
"{",
"if",
"(",
"_classes",
".",
"hasOwnProperty",
"(",
"prop",
")",
"&&",
"_classes",
"[",
"prop",
"]",
"!==",
"_classes",
".",
"BASE_CLASS",
"&&",
"_dom",
".",
"classList",
".",
"contains",
"(",
"_classes",
"[",
"prop",
"]",
")",
")",
"{",
"_dom",
".",
"classList",
".",
"remove",
"(",
"_classes",
"[",
"prop",
"]",
")",
";",
"}",
"}",
"}"
]
| Search for and remove initial BaseTransition classes that have
already been applied to this BaseTransition's target element. | [
"Search",
"for",
"and",
"remove",
"initial",
"BaseTransition",
"classes",
"that",
"have",
"already",
"been",
"applied",
"to",
"this",
"BaseTransition",
"s",
"target",
"element",
"."
]
| f45d7ded6687672c8b701c9910ddfe90c7ede742 | https://github.com/cfpb/AtomicComponent/blob/f45d7ded6687672c8b701c9910ddfe90c7ede742/src/utilities/transition/BaseTransition.js#L145-L153 |
45,206 | cfpb/AtomicComponent | src/utilities/transition/BaseTransition.js | remove | function remove() {
if ( _dom ) {
halt();
_dom.classList.remove( _classes.BASE_CLASS );
_flush();
return true;
}
return false;
} | javascript | function remove() {
if ( _dom ) {
halt();
_dom.classList.remove( _classes.BASE_CLASS );
_flush();
return true;
}
return false;
} | [
"function",
"remove",
"(",
")",
"{",
"if",
"(",
"_dom",
")",
"{",
"halt",
"(",
")",
";",
"_dom",
".",
"classList",
".",
"remove",
"(",
"_classes",
".",
"BASE_CLASS",
")",
";",
"_flush",
"(",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
]
| Remove all transition classes, if transition is initialized.
@returns {boolean}
True, if the element's CSS classes were touched, false otherwise. | [
"Remove",
"all",
"transition",
"classes",
"if",
"transition",
"is",
"initialized",
"."
]
| f45d7ded6687672c8b701c9910ddfe90c7ede742 | https://github.com/cfpb/AtomicComponent/blob/f45d7ded6687672c8b701c9910ddfe90c7ede742/src/utilities/transition/BaseTransition.js#L160-L169 |
45,207 | henrytseng/angular-state-router | src/services/queue-handler.js | function(handler, priority) {
if(handler && handler.constructor === Array) {
handler.forEach(function(layer) {
layer.priority = typeof layer.priority === 'undefined' ? 1 : layer.priority;
});
_list = _list.concat(handler);
} else {
handler.priority = priority || (typeof handler.priority === 'undefined' ? 1 : handler.priority);
_list.push(handler);
}
return this;
} | javascript | function(handler, priority) {
if(handler && handler.constructor === Array) {
handler.forEach(function(layer) {
layer.priority = typeof layer.priority === 'undefined' ? 1 : layer.priority;
});
_list = _list.concat(handler);
} else {
handler.priority = priority || (typeof handler.priority === 'undefined' ? 1 : handler.priority);
_list.push(handler);
}
return this;
} | [
"function",
"(",
"handler",
",",
"priority",
")",
"{",
"if",
"(",
"handler",
"&&",
"handler",
".",
"constructor",
"===",
"Array",
")",
"{",
"handler",
".",
"forEach",
"(",
"function",
"(",
"layer",
")",
"{",
"layer",
".",
"priority",
"=",
"typeof",
"layer",
".",
"priority",
"===",
"'undefined'",
"?",
"1",
":",
"layer",
".",
"priority",
";",
"}",
")",
";",
"_list",
"=",
"_list",
".",
"concat",
"(",
"handler",
")",
";",
"}",
"else",
"{",
"handler",
".",
"priority",
"=",
"priority",
"||",
"(",
"typeof",
"handler",
".",
"priority",
"===",
"'undefined'",
"?",
"1",
":",
"handler",
".",
"priority",
")",
";",
"_list",
".",
"push",
"(",
"handler",
")",
";",
"}",
"return",
"this",
";",
"}"
]
| Add a handler
@param {Mixed} handler A Function or an Array of Functions to add to the queue
@return {Queue} Itself; chainable | [
"Add",
"a",
"handler"
]
| 5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b | https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/src/services/queue-handler.js#L20-L31 |
|
45,208 | henrytseng/angular-state-router | src/services/queue-handler.js | function(callback) {
var nextHandler;
var executionList = _list.slice(0).sort(function(a, b) {
return Math.max(-1, Math.min(1, b.priority - a.priority));
});
nextHandler = function() {
$rootScope.$evalAsync(function() {
var handler = executionList.shift();
// Complete
if(!handler) {
callback(null);
// Next handler
} else {
handler.call(null, _data, function(err) {
// Error
if(err) {
callback(err);
// Continue
} else {
nextHandler();
}
});
}
});
};
// Start
nextHandler();
} | javascript | function(callback) {
var nextHandler;
var executionList = _list.slice(0).sort(function(a, b) {
return Math.max(-1, Math.min(1, b.priority - a.priority));
});
nextHandler = function() {
$rootScope.$evalAsync(function() {
var handler = executionList.shift();
// Complete
if(!handler) {
callback(null);
// Next handler
} else {
handler.call(null, _data, function(err) {
// Error
if(err) {
callback(err);
// Continue
} else {
nextHandler();
}
});
}
});
};
// Start
nextHandler();
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"nextHandler",
";",
"var",
"executionList",
"=",
"_list",
".",
"slice",
"(",
"0",
")",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"Math",
".",
"max",
"(",
"-",
"1",
",",
"Math",
".",
"min",
"(",
"1",
",",
"b",
".",
"priority",
"-",
"a",
".",
"priority",
")",
")",
";",
"}",
")",
";",
"nextHandler",
"=",
"function",
"(",
")",
"{",
"$rootScope",
".",
"$evalAsync",
"(",
"function",
"(",
")",
"{",
"var",
"handler",
"=",
"executionList",
".",
"shift",
"(",
")",
";",
"// Complete",
"if",
"(",
"!",
"handler",
")",
"{",
"callback",
"(",
"null",
")",
";",
"// Next handler",
"}",
"else",
"{",
"handler",
".",
"call",
"(",
"null",
",",
"_data",
",",
"function",
"(",
"err",
")",
"{",
"// Error",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"// Continue",
"}",
"else",
"{",
"nextHandler",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
";",
"// Start",
"nextHandler",
"(",
")",
";",
"}"
]
| Begin execution and trigger callback at the end
@param {Function} callback A callback, function(err)
@return {Queue} Itself; chainable | [
"Begin",
"execution",
"and",
"trigger",
"callback",
"at",
"the",
"end"
]
| 5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b | https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/src/services/queue-handler.js#L50-L82 |
|
45,209 | glaunay/ms-jobmanager | build/index.js | isSpecs | function isSpecs(opt) {
//logger.debug('???');
//logger.debug(`${opt.cacheDir}`);
//let b:any = opt.cacheDir instanceof(String)
if (!path.isAbsolute(opt.cacheDir)) {
logger.error('cacheDir parameter must be an absolute path');
return false;
}
if ('cacheDir' in opt && 'tcp' in opt && 'port' in opt && 'engineSpec' in opt)
return typeof (opt.cacheDir) == 'string' && typeof (opt.tcp) == 'string' &&
typeof (opt.port) == 'number' && engineLib.isEngineSpec(opt.engineSpec);
//logger.debug('niet');
return false;
} | javascript | function isSpecs(opt) {
//logger.debug('???');
//logger.debug(`${opt.cacheDir}`);
//let b:any = opt.cacheDir instanceof(String)
if (!path.isAbsolute(opt.cacheDir)) {
logger.error('cacheDir parameter must be an absolute path');
return false;
}
if ('cacheDir' in opt && 'tcp' in opt && 'port' in opt && 'engineSpec' in opt)
return typeof (opt.cacheDir) == 'string' && typeof (opt.tcp) == 'string' &&
typeof (opt.port) == 'number' && engineLib.isEngineSpec(opt.engineSpec);
//logger.debug('niet');
return false;
} | [
"function",
"isSpecs",
"(",
"opt",
")",
"{",
"//logger.debug('???');",
"//logger.debug(`${opt.cacheDir}`);",
"//let b:any = opt.cacheDir instanceof(String)",
"if",
"(",
"!",
"path",
".",
"isAbsolute",
"(",
"opt",
".",
"cacheDir",
")",
")",
"{",
"logger",
".",
"error",
"(",
"'cacheDir parameter must be an absolute path'",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"'cacheDir'",
"in",
"opt",
"&&",
"'tcp'",
"in",
"opt",
"&&",
"'port'",
"in",
"opt",
"&&",
"'engineSpec'",
"in",
"opt",
")",
"return",
"typeof",
"(",
"opt",
".",
"cacheDir",
")",
"==",
"'string'",
"&&",
"typeof",
"(",
"opt",
".",
"tcp",
")",
"==",
"'string'",
"&&",
"typeof",
"(",
"opt",
".",
"port",
")",
"==",
"'number'",
"&&",
"engineLib",
".",
"isEngineSpec",
"(",
"opt",
".",
"engineSpec",
")",
";",
"//logger.debug('niet');",
"return",
"false",
";",
"}"
]
| VR change typeguard to warehouse | [
"VR",
"change",
"typeguard",
"to",
"warehouse"
]
| 997d4fb25fd1d2b41acfae1dd576b33f2c92bd15 | https://github.com/glaunay/ms-jobmanager/blob/997d4fb25fd1d2b41acfae1dd576b33f2c92bd15/build/index.js#L50-L63 |
45,210 | glaunay/ms-jobmanager | build/index.js | pushMS | function pushMS(data, socket) {
logger.debug(`newJob Packet arrived w/ ${util.format(data)}`);
logger.silly(` Memory size vs nWorker :: ${liveMemory.size()} <<>> ${nWorker}`);
if (liveMemory.size("notBound") >= nWorker) {
logger.debug("must refuse packet, max pool size reached");
jmServer.bouncer(data, socket);
return;
// No early exit yet
}
jmServer.granted(data, socket).then((_data) => {
let jobProfile = _data.jobProfile;
_data.fromConsumerMS = true;
//pool size
if (jobLib.isJobOptProxy(_data)) {
logger.debug(`jobOpt successfully decoded`);
}
let job = push(jobProfile, _data);
});
} | javascript | function pushMS(data, socket) {
logger.debug(`newJob Packet arrived w/ ${util.format(data)}`);
logger.silly(` Memory size vs nWorker :: ${liveMemory.size()} <<>> ${nWorker}`);
if (liveMemory.size("notBound") >= nWorker) {
logger.debug("must refuse packet, max pool size reached");
jmServer.bouncer(data, socket);
return;
// No early exit yet
}
jmServer.granted(data, socket).then((_data) => {
let jobProfile = _data.jobProfile;
_data.fromConsumerMS = true;
//pool size
if (jobLib.isJobOptProxy(_data)) {
logger.debug(`jobOpt successfully decoded`);
}
let job = push(jobProfile, _data);
});
} | [
"function",
"pushMS",
"(",
"data",
",",
"socket",
")",
"{",
"logger",
".",
"debug",
"(",
"`",
"${",
"util",
".",
"format",
"(",
"data",
")",
"}",
"`",
")",
";",
"logger",
".",
"silly",
"(",
"`",
"${",
"liveMemory",
".",
"size",
"(",
")",
"}",
"${",
"nWorker",
"}",
"`",
")",
";",
"if",
"(",
"liveMemory",
".",
"size",
"(",
"\"notBound\"",
")",
">=",
"nWorker",
")",
"{",
"logger",
".",
"debug",
"(",
"\"must refuse packet, max pool size reached\"",
")",
";",
"jmServer",
".",
"bouncer",
"(",
"data",
",",
"socket",
")",
";",
"return",
";",
"// No early exit yet",
"}",
"jmServer",
".",
"granted",
"(",
"data",
",",
"socket",
")",
".",
"then",
"(",
"(",
"_data",
")",
"=>",
"{",
"let",
"jobProfile",
"=",
"_data",
".",
"jobProfile",
";",
"_data",
".",
"fromConsumerMS",
"=",
"true",
";",
"//pool size",
"if",
"(",
"jobLib",
".",
"isJobOptProxy",
"(",
"_data",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"`",
"`",
")",
";",
"}",
"let",
"job",
"=",
"push",
"(",
"jobProfile",
",",
"_data",
")",
";",
"}",
")",
";",
"}"
]
| New job packet arrived on MS socket, 1st arg is streamMap, 2nd the socket | [
"New",
"job",
"packet",
"arrived",
"on",
"MS",
"socket",
"1st",
"arg",
"is",
"streamMap",
"2nd",
"the",
"socket"
]
| 997d4fb25fd1d2b41acfae1dd576b33f2c92bd15 | https://github.com/glaunay/ms-jobmanager/blob/997d4fb25fd1d2b41acfae1dd576b33f2c92bd15/build/index.js#L271-L289 |
45,211 | jrmerz/node-ckan | index.js | addFileResource | function addFileResource(cmd, file, params, callback) {
if( !file ) return callback({error:true,message:"no file provided"});
if( !fs.existsSync(file) ) return callback({error:true,message:"no file found: "+file});
if( !fs.statSync(file).isFile() ) return callback({error:true,message:"not a file: "+file});
if( !params ) return callback({error:true,message:"no resource parameters provided"});
if( !params.package_id ) return callback({error:true,message:"no package_id provided"});
// clean up filename
var name = getCkanFilename(file);
var folder = new Date().toISOString()+'/'+name;
// set default / known parameters
params.url = server+"/storage/f/"+encodeURIComponent(folder);
if( !params.name ) params.name = file.replace(/.*\//,'');
params.size = fs.statSync(file).size;
params.resource_type = "file.upload";
exports.exec(cmd, params, function(err, pkg){
if( err ) return callback(err);
rest.post(server + '/storage/upload_handle', {
multipart: true,
headers : {
Authorization : key
},
data: {
key: folder,
file: rest.file(file, null, fs.statSync(file).size, null, params.mimetype)
}
}).on('complete', function(data) {
// HACK: redirects seem to fire complete twice. this is bad
if( !callback ) return;
if (data instanceof Error) {
callback(data);
} else {
callback(null, data);
}
callback = null;
});
});
} | javascript | function addFileResource(cmd, file, params, callback) {
if( !file ) return callback({error:true,message:"no file provided"});
if( !fs.existsSync(file) ) return callback({error:true,message:"no file found: "+file});
if( !fs.statSync(file).isFile() ) return callback({error:true,message:"not a file: "+file});
if( !params ) return callback({error:true,message:"no resource parameters provided"});
if( !params.package_id ) return callback({error:true,message:"no package_id provided"});
// clean up filename
var name = getCkanFilename(file);
var folder = new Date().toISOString()+'/'+name;
// set default / known parameters
params.url = server+"/storage/f/"+encodeURIComponent(folder);
if( !params.name ) params.name = file.replace(/.*\//,'');
params.size = fs.statSync(file).size;
params.resource_type = "file.upload";
exports.exec(cmd, params, function(err, pkg){
if( err ) return callback(err);
rest.post(server + '/storage/upload_handle', {
multipart: true,
headers : {
Authorization : key
},
data: {
key: folder,
file: rest.file(file, null, fs.statSync(file).size, null, params.mimetype)
}
}).on('complete', function(data) {
// HACK: redirects seem to fire complete twice. this is bad
if( !callback ) return;
if (data instanceof Error) {
callback(data);
} else {
callback(null, data);
}
callback = null;
});
});
} | [
"function",
"addFileResource",
"(",
"cmd",
",",
"file",
",",
"params",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"file",
")",
"return",
"callback",
"(",
"{",
"error",
":",
"true",
",",
"message",
":",
"\"no file provided\"",
"}",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"file",
")",
")",
"return",
"callback",
"(",
"{",
"error",
":",
"true",
",",
"message",
":",
"\"no file found: \"",
"+",
"file",
"}",
")",
";",
"if",
"(",
"!",
"fs",
".",
"statSync",
"(",
"file",
")",
".",
"isFile",
"(",
")",
")",
"return",
"callback",
"(",
"{",
"error",
":",
"true",
",",
"message",
":",
"\"not a file: \"",
"+",
"file",
"}",
")",
";",
"if",
"(",
"!",
"params",
")",
"return",
"callback",
"(",
"{",
"error",
":",
"true",
",",
"message",
":",
"\"no resource parameters provided\"",
"}",
")",
";",
"if",
"(",
"!",
"params",
".",
"package_id",
")",
"return",
"callback",
"(",
"{",
"error",
":",
"true",
",",
"message",
":",
"\"no package_id provided\"",
"}",
")",
";",
"// clean up filename",
"var",
"name",
"=",
"getCkanFilename",
"(",
"file",
")",
";",
"var",
"folder",
"=",
"new",
"Date",
"(",
")",
".",
"toISOString",
"(",
")",
"+",
"'/'",
"+",
"name",
";",
"// set default / known parameters",
"params",
".",
"url",
"=",
"server",
"+",
"\"/storage/f/\"",
"+",
"encodeURIComponent",
"(",
"folder",
")",
";",
"if",
"(",
"!",
"params",
".",
"name",
")",
"params",
".",
"name",
"=",
"file",
".",
"replace",
"(",
"/",
".*\\/",
"/",
",",
"''",
")",
";",
"params",
".",
"size",
"=",
"fs",
".",
"statSync",
"(",
"file",
")",
".",
"size",
";",
"params",
".",
"resource_type",
"=",
"\"file.upload\"",
";",
"exports",
".",
"exec",
"(",
"cmd",
",",
"params",
",",
"function",
"(",
"err",
",",
"pkg",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"rest",
".",
"post",
"(",
"server",
"+",
"'/storage/upload_handle'",
",",
"{",
"multipart",
":",
"true",
",",
"headers",
":",
"{",
"Authorization",
":",
"key",
"}",
",",
"data",
":",
"{",
"key",
":",
"folder",
",",
"file",
":",
"rest",
".",
"file",
"(",
"file",
",",
"null",
",",
"fs",
".",
"statSync",
"(",
"file",
")",
".",
"size",
",",
"null",
",",
"params",
".",
"mimetype",
")",
"}",
"}",
")",
".",
"on",
"(",
"'complete'",
",",
"function",
"(",
"data",
")",
"{",
"// HACK: redirects seem to fire complete twice. this is bad",
"if",
"(",
"!",
"callback",
")",
"return",
";",
"if",
"(",
"data",
"instanceof",
"Error",
")",
"{",
"callback",
"(",
"data",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"data",
")",
";",
"}",
"callback",
"=",
"null",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| todo, check for read access | [
"todo",
"check",
"for",
"read",
"access"
]
| 55f6bb1ece7f57ccd5ba57be7888e4d3941bc659 | https://github.com/jrmerz/node-ckan/blob/55f6bb1ece7f57ccd5ba57be7888e4d3941bc659/index.js#L112-L154 |
45,212 | rBurgett/simple-sort | src/main.js | function(locale) {
this.intCol = (Intl && Intl.Collator) ? new Intl.Collator(locale) : new CollatorPolyfill(locale);
} | javascript | function(locale) {
this.intCol = (Intl && Intl.Collator) ? new Intl.Collator(locale) : new CollatorPolyfill(locale);
} | [
"function",
"(",
"locale",
")",
"{",
"this",
".",
"intCol",
"=",
"(",
"Intl",
"&&",
"Intl",
".",
"Collator",
")",
"?",
"new",
"Intl",
".",
"Collator",
"(",
"locale",
")",
":",
"new",
"CollatorPolyfill",
"(",
"locale",
")",
";",
"}"
]
| Constructs a sorter instance.
@constructor Sorter
@param {string} [locale] - the locale to sort by (e.g. 'en-US') | [
"Constructs",
"a",
"sorter",
"instance",
"."
]
| 1c27912b3dce1e581b2817dbe599fdfe7b8d1781 | https://github.com/rBurgett/simple-sort/blob/1c27912b3dce1e581b2817dbe599fdfe7b8d1781/src/main.js#L13-L15 |
|
45,213 | ryb73/dealers-choice-meta | packages/server/lib/game-managers/choice-provider/handle-bidding.js | giveAnswer | function giveAnswer(answeringPlayer, answer) {
if(answeringPlayer === seller) return;
if(answer <= currentBid) return;
buyer = answeringPlayer;
currentBid = answer;
resetTimer();
notify(false);
} | javascript | function giveAnswer(answeringPlayer, answer) {
if(answeringPlayer === seller) return;
if(answer <= currentBid) return;
buyer = answeringPlayer;
currentBid = answer;
resetTimer();
notify(false);
} | [
"function",
"giveAnswer",
"(",
"answeringPlayer",
",",
"answer",
")",
"{",
"if",
"(",
"answeringPlayer",
"===",
"seller",
")",
"return",
";",
"if",
"(",
"answer",
"<=",
"currentBid",
")",
"return",
";",
"buyer",
"=",
"answeringPlayer",
";",
"currentBid",
"=",
"answer",
";",
"resetTimer",
"(",
")",
";",
"notify",
"(",
"false",
")",
";",
"}"
]
| answer is the bid amount | [
"answer",
"is",
"the",
"bid",
"amount"
]
| 4632e8897c832b01d944a340cf87d5c807809925 | https://github.com/ryb73/dealers-choice-meta/blob/4632e8897c832b01d944a340cf87d5c807809925/packages/server/lib/game-managers/choice-provider/handle-bidding.js#L74-L83 |
45,214 | sham-ui/sham-ui | src/options/decorator.js | hoistingOptions | function hoistingOptions( target ) {
if ( !target.hasOwnProperty( '_options' ) ) {
let options;
if ( undefined === target._options ) {
options = {};
} else {
// Create copy with descriptors
options = Object.create(
null,
Object.getOwnPropertyDescriptors( target._options )
);
}
Object.defineProperty( target, '_options', {
value: options,
enumerable: false,
configurable: true
} );
}
} | javascript | function hoistingOptions( target ) {
if ( !target.hasOwnProperty( '_options' ) ) {
let options;
if ( undefined === target._options ) {
options = {};
} else {
// Create copy with descriptors
options = Object.create(
null,
Object.getOwnPropertyDescriptors( target._options )
);
}
Object.defineProperty( target, '_options', {
value: options,
enumerable: false,
configurable: true
} );
}
} | [
"function",
"hoistingOptions",
"(",
"target",
")",
"{",
"if",
"(",
"!",
"target",
".",
"hasOwnProperty",
"(",
"'_options'",
")",
")",
"{",
"let",
"options",
";",
"if",
"(",
"undefined",
"===",
"target",
".",
"_options",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"else",
"{",
"// Create copy with descriptors",
"options",
"=",
"Object",
".",
"create",
"(",
"null",
",",
"Object",
".",
"getOwnPropertyDescriptors",
"(",
"target",
".",
"_options",
")",
")",
";",
"}",
"Object",
".",
"defineProperty",
"(",
"target",
",",
"'_options'",
",",
"{",
"value",
":",
"options",
",",
"enumerable",
":",
"false",
",",
"configurable",
":",
"true",
"}",
")",
";",
"}",
"}"
]
| Hoisting options in prototype chain
@param {Object} target | [
"Hoisting",
"options",
"in",
"prototype",
"chain"
]
| d4a1a43deac246575557c5cca86fc5a7e7a1dd9f | https://github.com/sham-ui/sham-ui/blob/d4a1a43deac246575557c5cca86fc5a7e7a1dd9f/src/options/decorator.js#L5-L24 |
45,215 | mikolalysenko/overlay-pslg | overlay-pslg.js | markCells | function markCells(cells, adj, edges) {
//Initialize active/next queues and flags
var flags = new Array(cells.length)
var constraint = new Array(3*cells.length)
for(var i=0; i<3*cells.length; ++i) {
constraint[i] = false
}
var active = []
var next = []
for(var i=0; i<cells.length; ++i) {
var c = cells[i]
flags[i] = 0
for(var j=0; j<3; ++j) {
var a = c[(j+1)%3]
var b = c[(j+2)%3]
var constr = constraint[3*i+j] = isConstraint(edges, a, b)
if(adj[3*i+j] >= 0) {
continue
}
if(constr) {
next.push(i)
} else {
flags[i] = 1
active.push(i)
}
}
}
//Mark flags
var side = 1
while(active.length > 0 || next.length > 0) {
while(active.length > 0) {
var t = active.pop()
if(flags[t] === -side) {
continue
}
flags[t] = side
var c = cells[t]
for(var j=0; j<3; ++j) {
var f = adj[3*t+j]
if(f >= 0 && flags[f] === 0) {
if(constraint[3*t+j]) {
next.push(f)
} else {
active.push(f)
flags[f] = side
}
}
}
}
//Swap arrays and loop
var tmp = next
next = active
active = tmp
next.length = 0
side = -side
}
return flags
} | javascript | function markCells(cells, adj, edges) {
//Initialize active/next queues and flags
var flags = new Array(cells.length)
var constraint = new Array(3*cells.length)
for(var i=0; i<3*cells.length; ++i) {
constraint[i] = false
}
var active = []
var next = []
for(var i=0; i<cells.length; ++i) {
var c = cells[i]
flags[i] = 0
for(var j=0; j<3; ++j) {
var a = c[(j+1)%3]
var b = c[(j+2)%3]
var constr = constraint[3*i+j] = isConstraint(edges, a, b)
if(adj[3*i+j] >= 0) {
continue
}
if(constr) {
next.push(i)
} else {
flags[i] = 1
active.push(i)
}
}
}
//Mark flags
var side = 1
while(active.length > 0 || next.length > 0) {
while(active.length > 0) {
var t = active.pop()
if(flags[t] === -side) {
continue
}
flags[t] = side
var c = cells[t]
for(var j=0; j<3; ++j) {
var f = adj[3*t+j]
if(f >= 0 && flags[f] === 0) {
if(constraint[3*t+j]) {
next.push(f)
} else {
active.push(f)
flags[f] = side
}
}
}
}
//Swap arrays and loop
var tmp = next
next = active
active = tmp
next.length = 0
side = -side
}
return flags
} | [
"function",
"markCells",
"(",
"cells",
",",
"adj",
",",
"edges",
")",
"{",
"//Initialize active/next queues and flags",
"var",
"flags",
"=",
"new",
"Array",
"(",
"cells",
".",
"length",
")",
"var",
"constraint",
"=",
"new",
"Array",
"(",
"3",
"*",
"cells",
".",
"length",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"3",
"*",
"cells",
".",
"length",
";",
"++",
"i",
")",
"{",
"constraint",
"[",
"i",
"]",
"=",
"false",
"}",
"var",
"active",
"=",
"[",
"]",
"var",
"next",
"=",
"[",
"]",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"cells",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"c",
"=",
"cells",
"[",
"i",
"]",
"flags",
"[",
"i",
"]",
"=",
"0",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"3",
";",
"++",
"j",
")",
"{",
"var",
"a",
"=",
"c",
"[",
"(",
"j",
"+",
"1",
")",
"%",
"3",
"]",
"var",
"b",
"=",
"c",
"[",
"(",
"j",
"+",
"2",
")",
"%",
"3",
"]",
"var",
"constr",
"=",
"constraint",
"[",
"3",
"*",
"i",
"+",
"j",
"]",
"=",
"isConstraint",
"(",
"edges",
",",
"a",
",",
"b",
")",
"if",
"(",
"adj",
"[",
"3",
"*",
"i",
"+",
"j",
"]",
">=",
"0",
")",
"{",
"continue",
"}",
"if",
"(",
"constr",
")",
"{",
"next",
".",
"push",
"(",
"i",
")",
"}",
"else",
"{",
"flags",
"[",
"i",
"]",
"=",
"1",
"active",
".",
"push",
"(",
"i",
")",
"}",
"}",
"}",
"//Mark flags",
"var",
"side",
"=",
"1",
"while",
"(",
"active",
".",
"length",
">",
"0",
"||",
"next",
".",
"length",
">",
"0",
")",
"{",
"while",
"(",
"active",
".",
"length",
">",
"0",
")",
"{",
"var",
"t",
"=",
"active",
".",
"pop",
"(",
")",
"if",
"(",
"flags",
"[",
"t",
"]",
"===",
"-",
"side",
")",
"{",
"continue",
"}",
"flags",
"[",
"t",
"]",
"=",
"side",
"var",
"c",
"=",
"cells",
"[",
"t",
"]",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"3",
";",
"++",
"j",
")",
"{",
"var",
"f",
"=",
"adj",
"[",
"3",
"*",
"t",
"+",
"j",
"]",
"if",
"(",
"f",
">=",
"0",
"&&",
"flags",
"[",
"f",
"]",
"===",
"0",
")",
"{",
"if",
"(",
"constraint",
"[",
"3",
"*",
"t",
"+",
"j",
"]",
")",
"{",
"next",
".",
"push",
"(",
"f",
")",
"}",
"else",
"{",
"active",
".",
"push",
"(",
"f",
")",
"flags",
"[",
"f",
"]",
"=",
"side",
"}",
"}",
"}",
"}",
"//Swap arrays and loop",
"var",
"tmp",
"=",
"next",
"next",
"=",
"active",
"active",
"=",
"tmp",
"next",
".",
"length",
"=",
"0",
"side",
"=",
"-",
"side",
"}",
"return",
"flags",
"}"
]
| Classify all cells within boundary | [
"Classify",
"all",
"cells",
"within",
"boundary"
]
| 7f6490b5c44ecf2078dc17cbce252a190b734cbc | https://github.com/mikolalysenko/overlay-pslg/blob/7f6490b5c44ecf2078dc17cbce252a190b734cbc/overlay-pslg.js#L108-L169 |
45,216 | writetome51/array-has | dist/privy/arrayHasAny.js | arrayHasAny | function arrayHasAny(values, array) {
error_if_not_array_1.errorIfNotArray(values);
var i = -1;
while (++i < values.length) {
if (arrayHas_1.arrayHas(values[i], array))
return true;
}
return false;
} | javascript | function arrayHasAny(values, array) {
error_if_not_array_1.errorIfNotArray(values);
var i = -1;
while (++i < values.length) {
if (arrayHas_1.arrayHas(values[i], array))
return true;
}
return false;
} | [
"function",
"arrayHasAny",
"(",
"values",
",",
"array",
")",
"{",
"error_if_not_array_1",
".",
"errorIfNotArray",
"(",
"values",
")",
";",
"var",
"i",
"=",
"-",
"1",
";",
"while",
"(",
"++",
"i",
"<",
"values",
".",
"length",
")",
"{",
"if",
"(",
"arrayHas_1",
".",
"arrayHas",
"(",
"values",
"[",
"i",
"]",
",",
"array",
")",
")",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
]
| values cannot contain object. | [
"values",
"cannot",
"contain",
"object",
"."
]
| 8ced3fda5818940b814bbcdc37e03c65f285a965 | https://github.com/writetome51/array-has/blob/8ced3fda5818940b814bbcdc37e03c65f285a965/dist/privy/arrayHasAny.js#L6-L14 |
45,217 | RainBirdAi/rainbird-linter | report.js | setJSHint | function setJSHint(path, done) {
var opts = JSON.parse(fs.readFileSync(path, 'utf8'));
jsHintOptions.config = opts;
done();
} | javascript | function setJSHint(path, done) {
var opts = JSON.parse(fs.readFileSync(path, 'utf8'));
jsHintOptions.config = opts;
done();
} | [
"function",
"setJSHint",
"(",
"path",
",",
"done",
")",
"{",
"var",
"opts",
"=",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"path",
",",
"'utf8'",
")",
")",
";",
"jsHintOptions",
".",
"config",
"=",
"opts",
";",
"done",
"(",
")",
";",
"}"
]
| Plato uses the `jshintrc` as is, whereas JSHint-Build needs the options inserted into its own options. | [
"Plato",
"uses",
"the",
"jshintrc",
"as",
"is",
"whereas",
"JSHint",
"-",
"Build",
"needs",
"the",
"options",
"inserted",
"into",
"its",
"own",
"options",
"."
]
| 2831a0286bfe3fb956b5188f0508752c6d16a4de | https://github.com/RainBirdAi/rainbird-linter/blob/2831a0286bfe3fb956b5188f0508752c6d16a4de/report.js#L50-L55 |
45,218 | RainBirdAi/rainbird-linter | report.js | checkJSHint | function checkJSHint(done) {
if(!options.jshint) {
options.jshint = path.join(__dirname, '.jshintrc');
}
checkPath(options.jshint, setJSHint, done);
} | javascript | function checkJSHint(done) {
if(!options.jshint) {
options.jshint = path.join(__dirname, '.jshintrc');
}
checkPath(options.jshint, setJSHint, done);
} | [
"function",
"checkJSHint",
"(",
"done",
")",
"{",
"if",
"(",
"!",
"options",
".",
"jshint",
")",
"{",
"options",
".",
"jshint",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"'.jshintrc'",
")",
";",
"}",
"checkPath",
"(",
"options",
".",
"jshint",
",",
"setJSHint",
",",
"done",
")",
";",
"}"
]
| The default `jshintrc` from the linter package can be overridden with the `jshint` option. The provided file is checked to ensure it exists before it's used. | [
"The",
"default",
"jshintrc",
"from",
"the",
"linter",
"package",
"can",
"be",
"overridden",
"with",
"the",
"jshint",
"option",
".",
"The",
"provided",
"file",
"is",
"checked",
"to",
"ensure",
"it",
"exists",
"before",
"it",
"s",
"used",
"."
]
| 2831a0286bfe3fb956b5188f0508752c6d16a4de | https://github.com/RainBirdAi/rainbird-linter/blob/2831a0286bfe3fb956b5188f0508752c6d16a4de/report.js#L61-L67 |
45,219 | RainBirdAi/rainbird-linter | report.js | setFilesets | function setFilesets(path, done) {
var config = JSON.parse(fs.readFileSync(path, 'utf8'));
/* jshint sub: true */
var includeFiles = config['includeFiles'];
var excludeFiles = config['excludeFiles'];
var filterFiles = config['lintOnly'];
/* jshint sub: false */
if (filterFiles && !Array.isArray(filterFiles)) {
filterFiles = [];
console.log(chalk.yellow('invalid `lintOnly` set; ignoring'));
}
if (includeFiles && Array.isArray(includeFiles)) {
filesets.include(includeFiles, filterFiles);
} else {
console.log(chalk.yellow('valid `includeFiles` not found in %s'), path);
}
if (excludeFiles && Array.isArray(includeFiles)) {
filesets.exclude(excludeFiles);
} else {
console.log(chalk.yellow('valid `excludeFiles` not found in %s'), path);
}
done();
} | javascript | function setFilesets(path, done) {
var config = JSON.parse(fs.readFileSync(path, 'utf8'));
/* jshint sub: true */
var includeFiles = config['includeFiles'];
var excludeFiles = config['excludeFiles'];
var filterFiles = config['lintOnly'];
/* jshint sub: false */
if (filterFiles && !Array.isArray(filterFiles)) {
filterFiles = [];
console.log(chalk.yellow('invalid `lintOnly` set; ignoring'));
}
if (includeFiles && Array.isArray(includeFiles)) {
filesets.include(includeFiles, filterFiles);
} else {
console.log(chalk.yellow('valid `includeFiles` not found in %s'), path);
}
if (excludeFiles && Array.isArray(includeFiles)) {
filesets.exclude(excludeFiles);
} else {
console.log(chalk.yellow('valid `excludeFiles` not found in %s'), path);
}
done();
} | [
"function",
"setFilesets",
"(",
"path",
",",
"done",
")",
"{",
"var",
"config",
"=",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"path",
",",
"'utf8'",
")",
")",
";",
"/* jshint sub: true */",
"var",
"includeFiles",
"=",
"config",
"[",
"'includeFiles'",
"]",
";",
"var",
"excludeFiles",
"=",
"config",
"[",
"'excludeFiles'",
"]",
";",
"var",
"filterFiles",
"=",
"config",
"[",
"'lintOnly'",
"]",
";",
"/* jshint sub: false */",
"if",
"(",
"filterFiles",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"filterFiles",
")",
")",
"{",
"filterFiles",
"=",
"[",
"]",
";",
"console",
".",
"log",
"(",
"chalk",
".",
"yellow",
"(",
"'invalid `lintOnly` set; ignoring'",
")",
")",
";",
"}",
"if",
"(",
"includeFiles",
"&&",
"Array",
".",
"isArray",
"(",
"includeFiles",
")",
")",
"{",
"filesets",
".",
"include",
"(",
"includeFiles",
",",
"filterFiles",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"yellow",
"(",
"'valid `includeFiles` not found in %s'",
")",
",",
"path",
")",
";",
"}",
"if",
"(",
"excludeFiles",
"&&",
"Array",
".",
"isArray",
"(",
"includeFiles",
")",
")",
"{",
"filesets",
".",
"exclude",
"(",
"excludeFiles",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"yellow",
"(",
"'valid `excludeFiles` not found in %s'",
")",
",",
"path",
")",
";",
"}",
"done",
"(",
")",
";",
"}"
]
| Set the filesets from those defined in the provided configuration file. If a given fileset isn't defined then a warning will be output. The `lintOnly` fileset is an optional fileset that will be excluded from the Plato fileset. | [
"Set",
"the",
"filesets",
"from",
"those",
"defined",
"in",
"the",
"provided",
"configuration",
"file",
".",
"If",
"a",
"given",
"fileset",
"isn",
"t",
"defined",
"then",
"a",
"warning",
"will",
"be",
"output",
".",
"The",
"lintOnly",
"fileset",
"is",
"an",
"optional",
"fileset",
"that",
"will",
"be",
"excluded",
"from",
"the",
"Plato",
"fileset",
"."
]
| 2831a0286bfe3fb956b5188f0508752c6d16a4de | https://github.com/RainBirdAi/rainbird-linter/blob/2831a0286bfe3fb956b5188f0508752c6d16a4de/report.js#L73-L100 |
45,220 | RainBirdAi/rainbird-linter | report.js | runReports | function runReports(err) {
if (err) { console.log(chalk.red('Error running reports: %s'), err); }
var excludes = filesets.platoExcludes();
if (excludes) {
platoOptions.exclude = excludes;
}
jsHintOptions.ignore = filesets.jshintExcludes();
jsHintOptions.reporter = reporter.reporter;
console.log(chalk.blue('Building plato reports...'));
console.log(chalk.gray('(Ignore any output about being unable to parse ' +
'JSON files)'));
plato.inspect(filesets.platoIncludes(), outputDir, platoOptions,
function() {
console.log(chalk.blue('\nPlato reports have been built to: ') +
chalk.magenta(outputDir));
console.log(chalk.blue('\nJSHint Report\n=============\n'));
buildJSHint(filesets.jshintIncludes(), jsHintOptions,
reporter.callback);
}
);
} | javascript | function runReports(err) {
if (err) { console.log(chalk.red('Error running reports: %s'), err); }
var excludes = filesets.platoExcludes();
if (excludes) {
platoOptions.exclude = excludes;
}
jsHintOptions.ignore = filesets.jshintExcludes();
jsHintOptions.reporter = reporter.reporter;
console.log(chalk.blue('Building plato reports...'));
console.log(chalk.gray('(Ignore any output about being unable to parse ' +
'JSON files)'));
plato.inspect(filesets.platoIncludes(), outputDir, platoOptions,
function() {
console.log(chalk.blue('\nPlato reports have been built to: ') +
chalk.magenta(outputDir));
console.log(chalk.blue('\nJSHint Report\n=============\n'));
buildJSHint(filesets.jshintIncludes(), jsHintOptions,
reporter.callback);
}
);
} | [
"function",
"runReports",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"red",
"(",
"'Error running reports: %s'",
")",
",",
"err",
")",
";",
"}",
"var",
"excludes",
"=",
"filesets",
".",
"platoExcludes",
"(",
")",
";",
"if",
"(",
"excludes",
")",
"{",
"platoOptions",
".",
"exclude",
"=",
"excludes",
";",
"}",
"jsHintOptions",
".",
"ignore",
"=",
"filesets",
".",
"jshintExcludes",
"(",
")",
";",
"jsHintOptions",
".",
"reporter",
"=",
"reporter",
".",
"reporter",
";",
"console",
".",
"log",
"(",
"chalk",
".",
"blue",
"(",
"'Building plato reports...'",
")",
")",
";",
"console",
".",
"log",
"(",
"chalk",
".",
"gray",
"(",
"'(Ignore any output about being unable to parse '",
"+",
"'JSON files)'",
")",
")",
";",
"plato",
".",
"inspect",
"(",
"filesets",
".",
"platoIncludes",
"(",
")",
",",
"outputDir",
",",
"platoOptions",
",",
"function",
"(",
")",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"blue",
"(",
"'\\nPlato reports have been built to: '",
")",
"+",
"chalk",
".",
"magenta",
"(",
"outputDir",
")",
")",
";",
"console",
".",
"log",
"(",
"chalk",
".",
"blue",
"(",
"'\\nJSHint Report\\n=============\\n'",
")",
")",
";",
"buildJSHint",
"(",
"filesets",
".",
"jshintIncludes",
"(",
")",
",",
"jsHintOptions",
",",
"reporter",
".",
"callback",
")",
";",
"}",
")",
";",
"}"
]
| Run the actual reports. The plato reports are run first, then the JSHint report. The output is annotated with headers and details on where the reports are stored. | [
"Run",
"the",
"actual",
"reports",
".",
"The",
"plato",
"reports",
"are",
"run",
"first",
"then",
"the",
"JSHint",
"report",
".",
"The",
"output",
"is",
"annotated",
"with",
"headers",
"and",
"details",
"on",
"where",
"the",
"reports",
"are",
"stored",
"."
]
| 2831a0286bfe3fb956b5188f0508752c6d16a4de | https://github.com/RainBirdAi/rainbird-linter/blob/2831a0286bfe3fb956b5188f0508752c6d16a4de/report.js#L120-L145 |
45,221 | gabmontes/node-coindesk-api | lib/index.js | getHistoricalClosePrices | function getHistoricalClosePrices(options = {}) {
const { index, currency, start, end, yesterday } = options
return request(`/historical/close.json`, {
index,
currency,
start: start && end && formatDate(start) || undefined,
end: start && end && formatDate(end) || undefined,
for: yesterday ? 'yesterday' : undefined
})
} | javascript | function getHistoricalClosePrices(options = {}) {
const { index, currency, start, end, yesterday } = options
return request(`/historical/close.json`, {
index,
currency,
start: start && end && formatDate(start) || undefined,
end: start && end && formatDate(end) || undefined,
for: yesterday ? 'yesterday' : undefined
})
} | [
"function",
"getHistoricalClosePrices",
"(",
"options",
"=",
"{",
"}",
")",
"{",
"const",
"{",
"index",
",",
"currency",
",",
"start",
",",
"end",
",",
"yesterday",
"}",
"=",
"options",
"return",
"request",
"(",
"`",
"`",
",",
"{",
"index",
",",
"currency",
",",
"start",
":",
"start",
"&&",
"end",
"&&",
"formatDate",
"(",
"start",
")",
"||",
"undefined",
",",
"end",
":",
"start",
"&&",
"end",
"&&",
"formatDate",
"(",
"end",
")",
"||",
"undefined",
",",
"for",
":",
"yesterday",
"?",
"'yesterday'",
":",
"undefined",
"}",
")",
"}"
]
| memoize 1' TTL 15" | [
"memoize",
"1",
"TTL",
"15"
]
| 9f7a54c24d6edb493723bf52cd5db54952f62125 | https://github.com/gabmontes/node-coindesk-api/blob/9f7a54c24d6edb493723bf52cd5db54952f62125/lib/index.js#L23-L33 |
45,222 | MiguelCastillo/bit-loader | example/asyncfile/src/fileReader.js | fileReader | function fileReader(moduleMeta) {
// Read file from disk and return a module meta
return pstream(readFile(moduleMeta.path))
.then(function(text) {
return {
source: text
};
}, log2console);
} | javascript | function fileReader(moduleMeta) {
// Read file from disk and return a module meta
return pstream(readFile(moduleMeta.path))
.then(function(text) {
return {
source: text
};
}, log2console);
} | [
"function",
"fileReader",
"(",
"moduleMeta",
")",
"{",
"// Read file from disk and return a module meta",
"return",
"pstream",
"(",
"readFile",
"(",
"moduleMeta",
".",
"path",
")",
")",
".",
"then",
"(",
"function",
"(",
"text",
")",
"{",
"return",
"{",
"source",
":",
"text",
"}",
";",
"}",
",",
"log2console",
")",
";",
"}"
]
| Function that reads file from disk
@param {object} moduleMeta - Module meta with information about the module being loaded | [
"Function",
"that",
"reads",
"file",
"from",
"disk"
]
| da9d18952d87014fdb09e7a8320a24cbf1c2b436 | https://github.com/MiguelCastillo/bit-loader/blob/da9d18952d87014fdb09e7a8320a24cbf1c2b436/example/asyncfile/src/fileReader.js#L11-L19 |
45,223 | briancsparks/serverassist | lib/helpers.js | function(guess, filename) {
var ct = guess;
// Someone else just defaulted to octet-stream?
if (!ct || ct === 'application/octet-stream') {
ct = sg.mimeType(filename) || ct;
}
return ct || 'application/octet-stream';
} | javascript | function(guess, filename) {
var ct = guess;
// Someone else just defaulted to octet-stream?
if (!ct || ct === 'application/octet-stream') {
ct = sg.mimeType(filename) || ct;
}
return ct || 'application/octet-stream';
} | [
"function",
"(",
"guess",
",",
"filename",
")",
"{",
"var",
"ct",
"=",
"guess",
";",
"// Someone else just defaulted to octet-stream?",
"if",
"(",
"!",
"ct",
"||",
"ct",
"===",
"'application/octet-stream'",
")",
"{",
"ct",
"=",
"sg",
".",
"mimeType",
"(",
"filename",
")",
"||",
"ct",
";",
"}",
"return",
"ct",
"||",
"'application/octet-stream'",
";",
"}"
]
| Returns the Content-Type. | [
"Returns",
"the",
"Content",
"-",
"Type",
"."
]
| f966832aae287f502cce53a71f5129b962ada8a3 | https://github.com/briancsparks/serverassist/blob/f966832aae287f502cce53a71f5129b962ada8a3/lib/helpers.js#L222-L231 |
|
45,224 | MiguelCastillo/bit-loader | src/module.js | Module | function Module(options) {
options = options || {};
if (types.isString(options)) {
options = {
name: options
};
}
if (!types.isString(options.name) && !types.isString(options.source)) {
throw new TypeError("Must provide a name or source for the module");
}
this.deps = options.deps ? options.deps.slice(0) : [];
this.type = options.type || Type.UNKNOWN;
return this.merge(options);
} | javascript | function Module(options) {
options = options || {};
if (types.isString(options)) {
options = {
name: options
};
}
if (!types.isString(options.name) && !types.isString(options.source)) {
throw new TypeError("Must provide a name or source for the module");
}
this.deps = options.deps ? options.deps.slice(0) : [];
this.type = options.type || Type.UNKNOWN;
return this.merge(options);
} | [
"function",
"Module",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"types",
".",
"isString",
"(",
"options",
")",
")",
"{",
"options",
"=",
"{",
"name",
":",
"options",
"}",
";",
"}",
"if",
"(",
"!",
"types",
".",
"isString",
"(",
"options",
".",
"name",
")",
"&&",
"!",
"types",
".",
"isString",
"(",
"options",
".",
"source",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"\"Must provide a name or source for the module\"",
")",
";",
"}",
"this",
".",
"deps",
"=",
"options",
".",
"deps",
"?",
"options",
".",
"deps",
".",
"slice",
"(",
"0",
")",
":",
"[",
"]",
";",
"this",
".",
"type",
"=",
"options",
".",
"type",
"||",
"Type",
".",
"UNKNOWN",
";",
"return",
"this",
".",
"merge",
"(",
"options",
")",
";",
"}"
]
| Intermediate representation of a Module which contains the information that is processed
in the different pipelines in order to generate a Module instance.
@class
@memberof Module
@property {string} id - Module id
@property {string} name - Module name
@property {string[]} deps - Array of module dependencies
@property {function} factory - Function that generates the data a particular module exports
@property {any} exports - Data exported by the module | [
"Intermediate",
"representation",
"of",
"a",
"Module",
"which",
"contains",
"the",
"information",
"that",
"is",
"processed",
"in",
"the",
"different",
"pipelines",
"in",
"order",
"to",
"generate",
"a",
"Module",
"instance",
"."
]
| da9d18952d87014fdb09e7a8320a24cbf1c2b436 | https://github.com/MiguelCastillo/bit-loader/blob/da9d18952d87014fdb09e7a8320a24cbf1c2b436/src/module.js#L106-L122 |
45,225 | onecommons/base | lib/utils.js | function(doRecentCheck, req, res, next) {
var app = req.app;
var config = app.loadConfig('auth');
var failed = !req.isAuthenticated();
if (!failed && doRecentCheck && !req.session.impersonated) {
//skip recent check if login is impersonated
//note: loginTime maybe a string since sessions are serialized as json
failed = !req.session.loginTime ||
!(new Date() - new Date(req.session.loginTime) <= config.recentLoginTimeoutSeconds*1000);
if (failed) { //force reauthentication (e.g. for facebook login for example)
req.session.reauthenticate = true;
}
}
// if user is not authenticated, redirect to login
if (failed) {
// remember original requested url
req.session.returnTo = req.url;
req.session.returnToMethod = req.method;
req.flash('login.danger', req.session.reauthenticate ? 'You need to login again to access this page.' : 'You need to login to access this page.');
res.redirect('/login');
return;
}
if (config.requireEmailVerification
&& req.user && !req.user.local.verified) {
if (config.requireEmailVerification == 'nag') {
req.flash('warning', 'Please confirm your email address by clicking the link sent to <strong>'+ req.user.local.email +"</strong>. <a class='send-resend' href='#'>Resend confirmation email</a>.");
} else if (config.requireEmailVerification == 'require') {
// redirect to the email verification page
req.session.returnTo = req.url;
req.session.returnToMethod = req.method;
res.redirect('/verification-required');
return;
}
}
return next();
} | javascript | function(doRecentCheck, req, res, next) {
var app = req.app;
var config = app.loadConfig('auth');
var failed = !req.isAuthenticated();
if (!failed && doRecentCheck && !req.session.impersonated) {
//skip recent check if login is impersonated
//note: loginTime maybe a string since sessions are serialized as json
failed = !req.session.loginTime ||
!(new Date() - new Date(req.session.loginTime) <= config.recentLoginTimeoutSeconds*1000);
if (failed) { //force reauthentication (e.g. for facebook login for example)
req.session.reauthenticate = true;
}
}
// if user is not authenticated, redirect to login
if (failed) {
// remember original requested url
req.session.returnTo = req.url;
req.session.returnToMethod = req.method;
req.flash('login.danger', req.session.reauthenticate ? 'You need to login again to access this page.' : 'You need to login to access this page.');
res.redirect('/login');
return;
}
if (config.requireEmailVerification
&& req.user && !req.user.local.verified) {
if (config.requireEmailVerification == 'nag') {
req.flash('warning', 'Please confirm your email address by clicking the link sent to <strong>'+ req.user.local.email +"</strong>. <a class='send-resend' href='#'>Resend confirmation email</a>.");
} else if (config.requireEmailVerification == 'require') {
// redirect to the email verification page
req.session.returnTo = req.url;
req.session.returnToMethod = req.method;
res.redirect('/verification-required');
return;
}
}
return next();
} | [
"function",
"(",
"doRecentCheck",
",",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"app",
"=",
"req",
".",
"app",
";",
"var",
"config",
"=",
"app",
".",
"loadConfig",
"(",
"'auth'",
")",
";",
"var",
"failed",
"=",
"!",
"req",
".",
"isAuthenticated",
"(",
")",
";",
"if",
"(",
"!",
"failed",
"&&",
"doRecentCheck",
"&&",
"!",
"req",
".",
"session",
".",
"impersonated",
")",
"{",
"//skip recent check if login is impersonated",
"//note: loginTime maybe a string since sessions are serialized as json",
"failed",
"=",
"!",
"req",
".",
"session",
".",
"loginTime",
"||",
"!",
"(",
"new",
"Date",
"(",
")",
"-",
"new",
"Date",
"(",
"req",
".",
"session",
".",
"loginTime",
")",
"<=",
"config",
".",
"recentLoginTimeoutSeconds",
"*",
"1000",
")",
";",
"if",
"(",
"failed",
")",
"{",
"//force reauthentication (e.g. for facebook login for example)",
"req",
".",
"session",
".",
"reauthenticate",
"=",
"true",
";",
"}",
"}",
"// if user is not authenticated, redirect to login",
"if",
"(",
"failed",
")",
"{",
"// remember original requested url",
"req",
".",
"session",
".",
"returnTo",
"=",
"req",
".",
"url",
";",
"req",
".",
"session",
".",
"returnToMethod",
"=",
"req",
".",
"method",
";",
"req",
".",
"flash",
"(",
"'login.danger'",
",",
"req",
".",
"session",
".",
"reauthenticate",
"?",
"'You need to login again to access this page.'",
":",
"'You need to login to access this page.'",
")",
";",
"res",
".",
"redirect",
"(",
"'/login'",
")",
";",
"return",
";",
"}",
"if",
"(",
"config",
".",
"requireEmailVerification",
"&&",
"req",
".",
"user",
"&&",
"!",
"req",
".",
"user",
".",
"local",
".",
"verified",
")",
"{",
"if",
"(",
"config",
".",
"requireEmailVerification",
"==",
"'nag'",
")",
"{",
"req",
".",
"flash",
"(",
"'warning'",
",",
"'Please confirm your email address by clicking the link sent to <strong>'",
"+",
"req",
".",
"user",
".",
"local",
".",
"email",
"+",
"\"</strong>. <a class='send-resend' href='#'>Resend confirmation email</a>.\"",
")",
";",
"}",
"else",
"if",
"(",
"config",
".",
"requireEmailVerification",
"==",
"'require'",
")",
"{",
"// redirect to the email verification page",
"req",
".",
"session",
".",
"returnTo",
"=",
"req",
".",
"url",
";",
"req",
".",
"session",
".",
"returnToMethod",
"=",
"req",
".",
"method",
";",
"res",
".",
"redirect",
"(",
"'/verification-required'",
")",
";",
"return",
";",
"}",
"}",
"return",
"next",
"(",
")",
";",
"}"
]
| route middleware to make sure a user is logged in | [
"route",
"middleware",
"to",
"make",
"sure",
"a",
"user",
"is",
"logged",
"in"
]
| 4f35d9f714d0367b0622a3504802363404290246 | https://github.com/onecommons/base/blob/4f35d9f714d0367b0622a3504802363404290246/lib/utils.js#L34-L73 |
|
45,226 | styonsk/elmongoose | lib/sync.js | function (next) {
// index creation options
var body = {
settings: {
number_of_shards : 3,
number_of_replicas : 2,
analysis: {
// analyzer definitions go here
analyzer: {
// default analyzer used for search & indexing
default: {
tokenizer: 'uax_url_email',
// indexing/search analysis:
// - trims leading/trailing whitespace
// - is case-insensitive
// - transforms non ascii characters into ascii character equivalents
// - splits on word/number boundaries and other delimiter rules
filter: [ 'trim', 'lowercase', 'asciifolding', 'word_delimiter_1' ]
},
// analyzer to use in indexing for autocomplete - we want ngrams of our data to be indexed
autocomplete_index: {
type: 'custom',
// use our own own ngram tokenizer
tokenizer: 'autocomplete_ngram',
filter: [ 'trim', 'lowercase', 'asciifolding', 'word_delimiter_1' ]
},
// analyzer to use in analyzing autocomplete search queries (don't generate ngrams from search queries)
autocomplete_search: {
type: 'custom',
tokenizer: 'keyword',
filter: [ 'trim', 'lowercase', 'asciifolding' ]
}
},
// filter definitions go here
filter: {
// custom word_delimiter filter to preserve original input as well as tokenize it
word_delimiter_1: {
type: 'word_delimiter',
preserve_original: true
}
},
// tokenizer definitions go here
tokenizer: {
// tokenizer to use for generating ngrams of our indexed data
autocomplete_ngram: {
type: 'edgeNGram',
// min and max ngram length
min_gram: 1,
max_gram: 50,
// generate ngrams that start from the front of the token only (eg. c, ca, cat)
side: 'front'
}
}
}
}
}
// if non-default mapping info was defined on the schema (e.g. autocomplete), apply the mappings to the index
body.mappings = {}
body.mappings[options.type] = indexMap
// console.log('mapping for', options.type, util.inspect(indexMap, true, 10, true))
var reqOpts = {
method: 'PUT',
url: versionedUri,
body: JSON.stringify(body)
}
if(options.auth) {
reqOpts.auth = {
user: options.auth.user,
pass: options.auth.password,
sendImmediately: false
};
}
// console.log('versionedUri', versionedUri)
helpers.backOffRequest(reqOpts, function (err, res, body) {
if (err) {
return cb(err)
}
if (!helpers.elasticsearchBodyOk(body)) {
var error = new Error('Unexpected index creation reply: '+util.inspect(body, true, 10, true))
error.body = body
return next(error)
}
return next()
})
} | javascript | function (next) {
// index creation options
var body = {
settings: {
number_of_shards : 3,
number_of_replicas : 2,
analysis: {
// analyzer definitions go here
analyzer: {
// default analyzer used for search & indexing
default: {
tokenizer: 'uax_url_email',
// indexing/search analysis:
// - trims leading/trailing whitespace
// - is case-insensitive
// - transforms non ascii characters into ascii character equivalents
// - splits on word/number boundaries and other delimiter rules
filter: [ 'trim', 'lowercase', 'asciifolding', 'word_delimiter_1' ]
},
// analyzer to use in indexing for autocomplete - we want ngrams of our data to be indexed
autocomplete_index: {
type: 'custom',
// use our own own ngram tokenizer
tokenizer: 'autocomplete_ngram',
filter: [ 'trim', 'lowercase', 'asciifolding', 'word_delimiter_1' ]
},
// analyzer to use in analyzing autocomplete search queries (don't generate ngrams from search queries)
autocomplete_search: {
type: 'custom',
tokenizer: 'keyword',
filter: [ 'trim', 'lowercase', 'asciifolding' ]
}
},
// filter definitions go here
filter: {
// custom word_delimiter filter to preserve original input as well as tokenize it
word_delimiter_1: {
type: 'word_delimiter',
preserve_original: true
}
},
// tokenizer definitions go here
tokenizer: {
// tokenizer to use for generating ngrams of our indexed data
autocomplete_ngram: {
type: 'edgeNGram',
// min and max ngram length
min_gram: 1,
max_gram: 50,
// generate ngrams that start from the front of the token only (eg. c, ca, cat)
side: 'front'
}
}
}
}
}
// if non-default mapping info was defined on the schema (e.g. autocomplete), apply the mappings to the index
body.mappings = {}
body.mappings[options.type] = indexMap
// console.log('mapping for', options.type, util.inspect(indexMap, true, 10, true))
var reqOpts = {
method: 'PUT',
url: versionedUri,
body: JSON.stringify(body)
}
if(options.auth) {
reqOpts.auth = {
user: options.auth.user,
pass: options.auth.password,
sendImmediately: false
};
}
// console.log('versionedUri', versionedUri)
helpers.backOffRequest(reqOpts, function (err, res, body) {
if (err) {
return cb(err)
}
if (!helpers.elasticsearchBodyOk(body)) {
var error = new Error('Unexpected index creation reply: '+util.inspect(body, true, 10, true))
error.body = body
return next(error)
}
return next()
})
} | [
"function",
"(",
"next",
")",
"{",
"// index creation options",
"var",
"body",
"=",
"{",
"settings",
":",
"{",
"number_of_shards",
":",
"3",
",",
"number_of_replicas",
":",
"2",
",",
"analysis",
":",
"{",
"// analyzer definitions go here",
"analyzer",
":",
"{",
"// default analyzer used for search & indexing",
"default",
":",
"{",
"tokenizer",
":",
"'uax_url_email'",
",",
"// indexing/search analysis:",
"// - trims leading/trailing whitespace",
"// - is case-insensitive",
"// - transforms non ascii characters into ascii character equivalents",
"// - splits on word/number boundaries and other delimiter rules",
"filter",
":",
"[",
"'trim'",
",",
"'lowercase'",
",",
"'asciifolding'",
",",
"'word_delimiter_1'",
"]",
"}",
",",
"// analyzer to use in indexing for autocomplete - we want ngrams of our data to be indexed",
"autocomplete_index",
":",
"{",
"type",
":",
"'custom'",
",",
"// use our own own ngram tokenizer",
"tokenizer",
":",
"'autocomplete_ngram'",
",",
"filter",
":",
"[",
"'trim'",
",",
"'lowercase'",
",",
"'asciifolding'",
",",
"'word_delimiter_1'",
"]",
"}",
",",
"// analyzer to use in analyzing autocomplete search queries (don't generate ngrams from search queries)",
"autocomplete_search",
":",
"{",
"type",
":",
"'custom'",
",",
"tokenizer",
":",
"'keyword'",
",",
"filter",
":",
"[",
"'trim'",
",",
"'lowercase'",
",",
"'asciifolding'",
"]",
"}",
"}",
",",
"// filter definitions go here",
"filter",
":",
"{",
"// custom word_delimiter filter to preserve original input as well as tokenize it",
"word_delimiter_1",
":",
"{",
"type",
":",
"'word_delimiter'",
",",
"preserve_original",
":",
"true",
"}",
"}",
",",
"// tokenizer definitions go here",
"tokenizer",
":",
"{",
"// tokenizer to use for generating ngrams of our indexed data",
"autocomplete_ngram",
":",
"{",
"type",
":",
"'edgeNGram'",
",",
"// min and max ngram length",
"min_gram",
":",
"1",
",",
"max_gram",
":",
"50",
",",
"// generate ngrams that start from the front of the token only (eg. c, ca, cat)",
"side",
":",
"'front'",
"}",
"}",
"}",
"}",
"}",
"// if non-default mapping info was defined on the schema (e.g. autocomplete), apply the mappings to the index",
"body",
".",
"mappings",
"=",
"{",
"}",
"body",
".",
"mappings",
"[",
"options",
".",
"type",
"]",
"=",
"indexMap",
"// console.log('mapping for', options.type, util.inspect(indexMap, true, 10, true))",
"var",
"reqOpts",
"=",
"{",
"method",
":",
"'PUT'",
",",
"url",
":",
"versionedUri",
",",
"body",
":",
"JSON",
".",
"stringify",
"(",
"body",
")",
"}",
"if",
"(",
"options",
".",
"auth",
")",
"{",
"reqOpts",
".",
"auth",
"=",
"{",
"user",
":",
"options",
".",
"auth",
".",
"user",
",",
"pass",
":",
"options",
".",
"auth",
".",
"password",
",",
"sendImmediately",
":",
"false",
"}",
";",
"}",
"// console.log('versionedUri', versionedUri)",
"helpers",
".",
"backOffRequest",
"(",
"reqOpts",
",",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
"}",
"if",
"(",
"!",
"helpers",
".",
"elasticsearchBodyOk",
"(",
"body",
")",
")",
"{",
"var",
"error",
"=",
"new",
"Error",
"(",
"'Unexpected index creation reply: '",
"+",
"util",
".",
"inspect",
"(",
"body",
",",
"true",
",",
"10",
",",
"true",
")",
")",
"error",
".",
"body",
"=",
"body",
"return",
"next",
"(",
"error",
")",
"}",
"return",
"next",
"(",
")",
"}",
")",
"}"
]
| create an elasticsearch index, versioned with the current timestamp | [
"create",
"an",
"elasticsearch",
"index",
"versioned",
"with",
"the",
"current",
"timestamp"
]
| b83f7dd67330c7288e7f17866d3e67f12a2adc1d | https://github.com/styonsk/elmongoose/blob/b83f7dd67330c7288e7f17866d3e67f12a2adc1d/lib/sync.js#L45-L139 |
|
45,227 | styonsk/elmongoose | lib/sync.js | function (next) {
self.count().exec(function (err, count) {
if (err) {
return next(err)
}
docsToIndex = count
return next()
})
} | javascript | function (next) {
self.count().exec(function (err, count) {
if (err) {
return next(err)
}
docsToIndex = count
return next()
})
} | [
"function",
"(",
"next",
")",
"{",
"self",
".",
"count",
"(",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"count",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
"}",
"docsToIndex",
"=",
"count",
"return",
"next",
"(",
")",
"}",
")",
"}"
]
| get a count of how many documents we have to index | [
"get",
"a",
"count",
"of",
"how",
"many",
"documents",
"we",
"have",
"to",
"index"
]
| b83f7dd67330c7288e7f17866d3e67f12a2adc1d | https://github.com/styonsk/elmongoose/blob/b83f7dd67330c7288e7f17866d3e67f12a2adc1d/lib/sync.js#L141-L151 |
|
45,228 | styonsk/elmongoose | lib/sync.js | function (next) {
// if no documents to index, skip population
if (!docsToIndex) {
return next()
}
// stream docs - and upload in batches of size BATCH_SIZE
var docStream = self.find().stream()
// elasticsearch commands to perform batch-indexing
var commandSequence = [];
docStream.on('data', function (doc) {
if (!doc || !doc._id) {
excludedDocs++;
return
}
// get rid of mongoose-added functions
doc = helpers.serializeModel(doc,options)
var selfStream = this
var strObjectId = doc._id
var command = {
index: {
_index: versionedIndexName,
_type: options.type,
_id: strObjectId
}
}
// append elasticsearch command and JSON-ified doc to command
commandSequence.push(command)
commandSequence.push(doc)
if (commandSequence.length === BATCH_SIZE) {
// pause the stream of incoming docs until we're done
// indexing the batch in elasticsearch
selfStream.pause()
exports.bulkIndexRequest(versionedIndexName, commandSequence, options, function (err) {
if (err) {
return next(err)
}
// empty our commandSequence
commandSequence = []
// keep streaming now that we're ready to accept more
selfStream.resume()
})
}
})
docStream.on('close', function () {
// if no documents left in buffer, don't perform a bulk index request
if (!commandSequence.length) {
return next()
}
// take care of the rest of the docs left in the buffer
exports.bulkIndexRequest(versionedIndexName, commandSequence, options, function (err) {
if (err) {
return next(err)
}
// empty the commandSequence
commandSequence = []
return next()
})
})
} | javascript | function (next) {
// if no documents to index, skip population
if (!docsToIndex) {
return next()
}
// stream docs - and upload in batches of size BATCH_SIZE
var docStream = self.find().stream()
// elasticsearch commands to perform batch-indexing
var commandSequence = [];
docStream.on('data', function (doc) {
if (!doc || !doc._id) {
excludedDocs++;
return
}
// get rid of mongoose-added functions
doc = helpers.serializeModel(doc,options)
var selfStream = this
var strObjectId = doc._id
var command = {
index: {
_index: versionedIndexName,
_type: options.type,
_id: strObjectId
}
}
// append elasticsearch command and JSON-ified doc to command
commandSequence.push(command)
commandSequence.push(doc)
if (commandSequence.length === BATCH_SIZE) {
// pause the stream of incoming docs until we're done
// indexing the batch in elasticsearch
selfStream.pause()
exports.bulkIndexRequest(versionedIndexName, commandSequence, options, function (err) {
if (err) {
return next(err)
}
// empty our commandSequence
commandSequence = []
// keep streaming now that we're ready to accept more
selfStream.resume()
})
}
})
docStream.on('close', function () {
// if no documents left in buffer, don't perform a bulk index request
if (!commandSequence.length) {
return next()
}
// take care of the rest of the docs left in the buffer
exports.bulkIndexRequest(versionedIndexName, commandSequence, options, function (err) {
if (err) {
return next(err)
}
// empty the commandSequence
commandSequence = []
return next()
})
})
} | [
"function",
"(",
"next",
")",
"{",
"// if no documents to index, skip population",
"if",
"(",
"!",
"docsToIndex",
")",
"{",
"return",
"next",
"(",
")",
"}",
"// stream docs - and upload in batches of size BATCH_SIZE",
"var",
"docStream",
"=",
"self",
".",
"find",
"(",
")",
".",
"stream",
"(",
")",
"// elasticsearch commands to perform batch-indexing",
"var",
"commandSequence",
"=",
"[",
"]",
";",
"docStream",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"doc",
")",
"{",
"if",
"(",
"!",
"doc",
"||",
"!",
"doc",
".",
"_id",
")",
"{",
"excludedDocs",
"++",
";",
"return",
"}",
"// get rid of mongoose-added functions",
"doc",
"=",
"helpers",
".",
"serializeModel",
"(",
"doc",
",",
"options",
")",
"var",
"selfStream",
"=",
"this",
"var",
"strObjectId",
"=",
"doc",
".",
"_id",
"var",
"command",
"=",
"{",
"index",
":",
"{",
"_index",
":",
"versionedIndexName",
",",
"_type",
":",
"options",
".",
"type",
",",
"_id",
":",
"strObjectId",
"}",
"}",
"// append elasticsearch command and JSON-ified doc to command",
"commandSequence",
".",
"push",
"(",
"command",
")",
"commandSequence",
".",
"push",
"(",
"doc",
")",
"if",
"(",
"commandSequence",
".",
"length",
"===",
"BATCH_SIZE",
")",
"{",
"// pause the stream of incoming docs until we're done",
"// indexing the batch in elasticsearch",
"selfStream",
".",
"pause",
"(",
")",
"exports",
".",
"bulkIndexRequest",
"(",
"versionedIndexName",
",",
"commandSequence",
",",
"options",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
"}",
"// empty our commandSequence",
"commandSequence",
"=",
"[",
"]",
"// keep streaming now that we're ready to accept more",
"selfStream",
".",
"resume",
"(",
")",
"}",
")",
"}",
"}",
")",
"docStream",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
")",
"{",
"// if no documents left in buffer, don't perform a bulk index request",
"if",
"(",
"!",
"commandSequence",
".",
"length",
")",
"{",
"return",
"next",
"(",
")",
"}",
"// take care of the rest of the docs left in the buffer",
"exports",
".",
"bulkIndexRequest",
"(",
"versionedIndexName",
",",
"commandSequence",
",",
"options",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
"}",
"// empty the commandSequence",
"commandSequence",
"=",
"[",
"]",
"return",
"next",
"(",
")",
"}",
")",
"}",
")",
"}"
]
| populate the newly created index with this collection's documents | [
"populate",
"the",
"newly",
"created",
"index",
"with",
"this",
"collection",
"s",
"documents"
]
| b83f7dd67330c7288e7f17866d3e67f12a2adc1d | https://github.com/styonsk/elmongoose/blob/b83f7dd67330c7288e7f17866d3e67f12a2adc1d/lib/sync.js#L153-L227 |
|
45,229 | styonsk/elmongoose | lib/sync.js | function (next) {
var reqOpts = {
method: 'GET',
url: helpers.makeAliasUri(options)
}
if(options.auth) {
reqOpts.auth = {
user: options.auth.user,
pass: options.auth.password,
sendImmediately: false
};
}
helpers.backOffRequest(reqOpts, function (err, res, body) {
if (err) {
return next(err)
}
var existingIndices = Object.keys(body)
// console.log('\nexistingIndices', body)
var aliasName = helpers.makeIndexName(options)
// get all aliases pertaining to this collection & are not the index we just created
// we will remove all of them
indicesToRemove = existingIndices.filter(function (indexName) {
return (indexName.indexOf(aliasName) === 0 && indexName !== versionedIndexName)
})
// console.log('\nindicesToRemove', indicesToRemove)
// generate elasticsearch request body to atomically remove old indices and add the new one
var requestBody = {
actions: [
{
add: {
alias: aliasName,
index: versionedIndexName
}
}
]
}
indicesToRemove.forEach(function (indexToRemove) {
var removeObj = {
remove: {
alias: aliasName,
index: indexToRemove
}
}
requestBody.actions.unshift(removeObj)
})
var reqOpts = {
method: 'POST',
url: helpers.makeAliasUri(options),
body: JSON.stringify(requestBody)
}
if(options.auth) {
reqOpts.auth = {
user: options.auth.user,
pass: options.auth.password,
sendImmediately: false
};
}
helpers.backOffRequest(reqOpts, function (err, res, body) {
if (err) {
return next(err)
}
if (!helpers.elasticsearchBodyOk(body)) {
var error = new Error('Alias deletion error. Elasticsearch reply:'+util.inspect(body, true, 10, true))
error.elasticsearchReply = body
error.elasticsearchRequestBody = requestBody
return next(error)
}
return next()
})
})
} | javascript | function (next) {
var reqOpts = {
method: 'GET',
url: helpers.makeAliasUri(options)
}
if(options.auth) {
reqOpts.auth = {
user: options.auth.user,
pass: options.auth.password,
sendImmediately: false
};
}
helpers.backOffRequest(reqOpts, function (err, res, body) {
if (err) {
return next(err)
}
var existingIndices = Object.keys(body)
// console.log('\nexistingIndices', body)
var aliasName = helpers.makeIndexName(options)
// get all aliases pertaining to this collection & are not the index we just created
// we will remove all of them
indicesToRemove = existingIndices.filter(function (indexName) {
return (indexName.indexOf(aliasName) === 0 && indexName !== versionedIndexName)
})
// console.log('\nindicesToRemove', indicesToRemove)
// generate elasticsearch request body to atomically remove old indices and add the new one
var requestBody = {
actions: [
{
add: {
alias: aliasName,
index: versionedIndexName
}
}
]
}
indicesToRemove.forEach(function (indexToRemove) {
var removeObj = {
remove: {
alias: aliasName,
index: indexToRemove
}
}
requestBody.actions.unshift(removeObj)
})
var reqOpts = {
method: 'POST',
url: helpers.makeAliasUri(options),
body: JSON.stringify(requestBody)
}
if(options.auth) {
reqOpts.auth = {
user: options.auth.user,
pass: options.auth.password,
sendImmediately: false
};
}
helpers.backOffRequest(reqOpts, function (err, res, body) {
if (err) {
return next(err)
}
if (!helpers.elasticsearchBodyOk(body)) {
var error = new Error('Alias deletion error. Elasticsearch reply:'+util.inspect(body, true, 10, true))
error.elasticsearchReply = body
error.elasticsearchRequestBody = requestBody
return next(error)
}
return next()
})
})
} | [
"function",
"(",
"next",
")",
"{",
"var",
"reqOpts",
"=",
"{",
"method",
":",
"'GET'",
",",
"url",
":",
"helpers",
".",
"makeAliasUri",
"(",
"options",
")",
"}",
"if",
"(",
"options",
".",
"auth",
")",
"{",
"reqOpts",
".",
"auth",
"=",
"{",
"user",
":",
"options",
".",
"auth",
".",
"user",
",",
"pass",
":",
"options",
".",
"auth",
".",
"password",
",",
"sendImmediately",
":",
"false",
"}",
";",
"}",
"helpers",
".",
"backOffRequest",
"(",
"reqOpts",
",",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
"}",
"var",
"existingIndices",
"=",
"Object",
".",
"keys",
"(",
"body",
")",
"// console.log('\\nexistingIndices', body)",
"var",
"aliasName",
"=",
"helpers",
".",
"makeIndexName",
"(",
"options",
")",
"// get all aliases pertaining to this collection & are not the index we just created",
"// we will remove all of them",
"indicesToRemove",
"=",
"existingIndices",
".",
"filter",
"(",
"function",
"(",
"indexName",
")",
"{",
"return",
"(",
"indexName",
".",
"indexOf",
"(",
"aliasName",
")",
"===",
"0",
"&&",
"indexName",
"!==",
"versionedIndexName",
")",
"}",
")",
"// console.log('\\nindicesToRemove', indicesToRemove)",
"// generate elasticsearch request body to atomically remove old indices and add the new one",
"var",
"requestBody",
"=",
"{",
"actions",
":",
"[",
"{",
"add",
":",
"{",
"alias",
":",
"aliasName",
",",
"index",
":",
"versionedIndexName",
"}",
"}",
"]",
"}",
"indicesToRemove",
".",
"forEach",
"(",
"function",
"(",
"indexToRemove",
")",
"{",
"var",
"removeObj",
"=",
"{",
"remove",
":",
"{",
"alias",
":",
"aliasName",
",",
"index",
":",
"indexToRemove",
"}",
"}",
"requestBody",
".",
"actions",
".",
"unshift",
"(",
"removeObj",
")",
"}",
")",
"var",
"reqOpts",
"=",
"{",
"method",
":",
"'POST'",
",",
"url",
":",
"helpers",
".",
"makeAliasUri",
"(",
"options",
")",
",",
"body",
":",
"JSON",
".",
"stringify",
"(",
"requestBody",
")",
"}",
"if",
"(",
"options",
".",
"auth",
")",
"{",
"reqOpts",
".",
"auth",
"=",
"{",
"user",
":",
"options",
".",
"auth",
".",
"user",
",",
"pass",
":",
"options",
".",
"auth",
".",
"password",
",",
"sendImmediately",
":",
"false",
"}",
";",
"}",
"helpers",
".",
"backOffRequest",
"(",
"reqOpts",
",",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
"}",
"if",
"(",
"!",
"helpers",
".",
"elasticsearchBodyOk",
"(",
"body",
")",
")",
"{",
"var",
"error",
"=",
"new",
"Error",
"(",
"'Alias deletion error. Elasticsearch reply:'",
"+",
"util",
".",
"inspect",
"(",
"body",
",",
"true",
",",
"10",
",",
"true",
")",
")",
"error",
".",
"elasticsearchReply",
"=",
"body",
"error",
".",
"elasticsearchRequestBody",
"=",
"requestBody",
"return",
"next",
"(",
"error",
")",
"}",
"return",
"next",
"(",
")",
"}",
")",
"}",
")",
"}"
]
| atomically replace existing aliases for this collection with the new one we just created | [
"atomically",
"replace",
"existing",
"aliases",
"for",
"this",
"collection",
"with",
"the",
"new",
"one",
"we",
"just",
"created"
]
| b83f7dd67330c7288e7f17866d3e67f12a2adc1d | https://github.com/styonsk/elmongoose/blob/b83f7dd67330c7288e7f17866d3e67f12a2adc1d/lib/sync.js#L259-L345 |
|
45,230 | ryb73/dealers-choice-meta | packages/server/lib/game-managers/pending-game-manager.js | addPlayer | function addPlayer(userId, callbacks) {
let player = factory.addPlayer();
if(!player) return null;
self._callbacks.set(player, callbacks);
// If the game didn't have an owner, it does now
// This should only happen when the game is first created
// and the initial player is added
if(!owner)
owner = player;
self._users[userId] = { id: userId, player };
return player;
} | javascript | function addPlayer(userId, callbacks) {
let player = factory.addPlayer();
if(!player) return null;
self._callbacks.set(player, callbacks);
// If the game didn't have an owner, it does now
// This should only happen when the game is first created
// and the initial player is added
if(!owner)
owner = player;
self._users[userId] = { id: userId, player };
return player;
} | [
"function",
"addPlayer",
"(",
"userId",
",",
"callbacks",
")",
"{",
"let",
"player",
"=",
"factory",
".",
"addPlayer",
"(",
")",
";",
"if",
"(",
"!",
"player",
")",
"return",
"null",
";",
"self",
".",
"_callbacks",
".",
"set",
"(",
"player",
",",
"callbacks",
")",
";",
"// If the game didn't have an owner, it does now",
"// This should only happen when the game is first created",
"// and the initial player is added",
"if",
"(",
"!",
"owner",
")",
"owner",
"=",
"player",
";",
"self",
".",
"_users",
"[",
"userId",
"]",
"=",
"{",
"id",
":",
"userId",
",",
"player",
"}",
";",
"return",
"player",
";",
"}"
]
| callback is used to send messages to the players in the game | [
"callback",
"is",
"used",
"to",
"send",
"messages",
"to",
"the",
"players",
"in",
"the",
"game"
]
| 4632e8897c832b01d944a340cf87d5c807809925 | https://github.com/ryb73/dealers-choice-meta/blob/4632e8897c832b01d944a340cf87d5c807809925/packages/server/lib/game-managers/pending-game-manager.js#L39-L54 |
45,231 | uvworkspace/uvwlib | lib/utils/slice.js | slice | function slice (args, start, end) {
var len = args.length;
start = start > 0 ? start : 0;
end = end >= 0 && end < len ? end : len;
var n = end - start;
if (n <= 0) return [];
var ret = new Array(n);
for (var i = 0; i < n; ++i) {
ret[i] = args[i + start];
}
return ret;
} | javascript | function slice (args, start, end) {
var len = args.length;
start = start > 0 ? start : 0;
end = end >= 0 && end < len ? end : len;
var n = end - start;
if (n <= 0) return [];
var ret = new Array(n);
for (var i = 0; i < n; ++i) {
ret[i] = args[i + start];
}
return ret;
} | [
"function",
"slice",
"(",
"args",
",",
"start",
",",
"end",
")",
"{",
"var",
"len",
"=",
"args",
".",
"length",
";",
"start",
"=",
"start",
">",
"0",
"?",
"start",
":",
"0",
";",
"end",
"=",
"end",
">=",
"0",
"&&",
"end",
"<",
"len",
"?",
"end",
":",
"len",
";",
"var",
"n",
"=",
"end",
"-",
"start",
";",
"if",
"(",
"n",
"<=",
"0",
")",
"return",
"[",
"]",
";",
"var",
"ret",
"=",
"new",
"Array",
"(",
"n",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"ret",
"[",
"i",
"]",
"=",
"args",
"[",
"i",
"+",
"start",
"]",
";",
"}",
"return",
"ret",
";",
"}"
]
| force copying to avoid leaking arguments | [
"force",
"copying",
"to",
"avoid",
"leaking",
"arguments"
]
| ef1893e0c9cdcaa321186dd5dc17fc2c9bd9e641 | https://github.com/uvworkspace/uvwlib/blob/ef1893e0c9cdcaa321186dd5dc17fc2c9bd9e641/lib/utils/slice.js#L4-L17 |
45,232 | aheckmann/mongodb-schema-miner | lib/index.js | read | function read (stream, opts, db, cb) {
var schema = new exports.Schema;
if (opts.onType) {
schema.onType = opts.onType;
}
stream.once('error', function (err) {
debug('aborting with error: ' + err);
db.close(cb.bind(err));
});
stream.on('data', function (doc) {
var err = schema.consume(doc);
if (err) return abort(err, stream, db, cb);
})
stream.on('end', function () {
debug('db closing');
db.close(function () {
debug('db closed');
cb(null, schema);
})
})
} | javascript | function read (stream, opts, db, cb) {
var schema = new exports.Schema;
if (opts.onType) {
schema.onType = opts.onType;
}
stream.once('error', function (err) {
debug('aborting with error: ' + err);
db.close(cb.bind(err));
});
stream.on('data', function (doc) {
var err = schema.consume(doc);
if (err) return abort(err, stream, db, cb);
})
stream.on('end', function () {
debug('db closing');
db.close(function () {
debug('db closed');
cb(null, schema);
})
})
} | [
"function",
"read",
"(",
"stream",
",",
"opts",
",",
"db",
",",
"cb",
")",
"{",
"var",
"schema",
"=",
"new",
"exports",
".",
"Schema",
";",
"if",
"(",
"opts",
".",
"onType",
")",
"{",
"schema",
".",
"onType",
"=",
"opts",
".",
"onType",
";",
"}",
"stream",
".",
"once",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"debug",
"(",
"'aborting with error: '",
"+",
"err",
")",
";",
"db",
".",
"close",
"(",
"cb",
".",
"bind",
"(",
"err",
")",
")",
";",
"}",
")",
";",
"stream",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"doc",
")",
"{",
"var",
"err",
"=",
"schema",
".",
"consume",
"(",
"doc",
")",
";",
"if",
"(",
"err",
")",
"return",
"abort",
"(",
"err",
",",
"stream",
",",
"db",
",",
"cb",
")",
";",
"}",
")",
"stream",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"debug",
"(",
"'db closing'",
")",
";",
"db",
".",
"close",
"(",
"function",
"(",
")",
"{",
"debug",
"(",
"'db closed'",
")",
";",
"cb",
"(",
"null",
",",
"schema",
")",
";",
"}",
")",
"}",
")",
"}"
]
| process documents from the stream | [
"process",
"documents",
"from",
"the",
"stream"
]
| c56220bd527d82f6a1712f90b45f10828290961f | https://github.com/aheckmann/mongodb-schema-miner/blob/c56220bd527d82f6a1712f90b45f10828290961f/lib/index.js#L38-L62 |
45,233 | aheckmann/mongodb-schema-miner | lib/index.js | abort | function abort (err, stream, db, cb) {
debug('aborting with error: ' + err);
stream.destroy();
db.close(function () {
cb(err);
})
} | javascript | function abort (err, stream, db, cb) {
debug('aborting with error: ' + err);
stream.destroy();
db.close(function () {
cb(err);
})
} | [
"function",
"abort",
"(",
"err",
",",
"stream",
",",
"db",
",",
"cb",
")",
"{",
"debug",
"(",
"'aborting with error: '",
"+",
"err",
")",
";",
"stream",
".",
"destroy",
"(",
")",
";",
"db",
".",
"close",
"(",
"function",
"(",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
")",
"}"
]
| abort the stream | [
"abort",
"the",
"stream"
]
| c56220bd527d82f6a1712f90b45f10828290961f | https://github.com/aheckmann/mongodb-schema-miner/blob/c56220bd527d82f6a1712f90b45f10828290961f/lib/index.js#L68-L74 |
45,234 | aheckmann/mongodb-schema-miner | lib/index.js | validate | function validate (uri, collection, cb) {
if ('function' != typeof cb) {
throw new TypeError('cb must be a function');
}
if ('string' != typeof collection) {
throw new TypeError('collection must be a string');
}
if ('string' != typeof uri) {
throw new TypeError('uri must be a string');
}
} | javascript | function validate (uri, collection, cb) {
if ('function' != typeof cb) {
throw new TypeError('cb must be a function');
}
if ('string' != typeof collection) {
throw new TypeError('collection must be a string');
}
if ('string' != typeof uri) {
throw new TypeError('uri must be a string');
}
} | [
"function",
"validate",
"(",
"uri",
",",
"collection",
",",
"cb",
")",
"{",
"if",
"(",
"'function'",
"!=",
"typeof",
"cb",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'cb must be a function'",
")",
";",
"}",
"if",
"(",
"'string'",
"!=",
"typeof",
"collection",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'collection must be a string'",
")",
";",
"}",
"if",
"(",
"'string'",
"!=",
"typeof",
"uri",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'uri must be a string'",
")",
";",
"}",
"}"
]
| validate "miner" arguments | [
"validate",
"miner",
"arguments"
]
| c56220bd527d82f6a1712f90b45f10828290961f | https://github.com/aheckmann/mongodb-schema-miner/blob/c56220bd527d82f6a1712f90b45f10828290961f/lib/index.js#L80-L92 |
45,235 | gavagai-corp/gavagai-node | lib/tonality.js | function (texts, options, callback) {
if (typeof(options) === 'function') {
callback = options;
options = {};
}
if (Array.isArray(texts)) {
texts = texts.map(function (text, i) {
return textObj(text, i);
});
} else if (typeof(texts) === 'string') {
texts = [textObj(texts)];
}
options = options || {};
options.language = options.language || 'en';
var body = {};
for (var key in options) {
if (options.hasOwnProperty(key)) {
body[key] = options[key]
}
}
body.texts = texts;
var params = {
method: 'POST',
url: '/tonality',
body: body
};
return client.request(params, callback);
} | javascript | function (texts, options, callback) {
if (typeof(options) === 'function') {
callback = options;
options = {};
}
if (Array.isArray(texts)) {
texts = texts.map(function (text, i) {
return textObj(text, i);
});
} else if (typeof(texts) === 'string') {
texts = [textObj(texts)];
}
options = options || {};
options.language = options.language || 'en';
var body = {};
for (var key in options) {
if (options.hasOwnProperty(key)) {
body[key] = options[key]
}
}
body.texts = texts;
var params = {
method: 'POST',
url: '/tonality',
body: body
};
return client.request(params, callback);
} | [
"function",
"(",
"texts",
",",
"options",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"(",
"options",
")",
"===",
"'function'",
")",
"{",
"callback",
"=",
"options",
";",
"options",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"texts",
")",
")",
"{",
"texts",
"=",
"texts",
".",
"map",
"(",
"function",
"(",
"text",
",",
"i",
")",
"{",
"return",
"textObj",
"(",
"text",
",",
"i",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"(",
"texts",
")",
"===",
"'string'",
")",
"{",
"texts",
"=",
"[",
"textObj",
"(",
"texts",
")",
"]",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"options",
".",
"language",
"=",
"options",
".",
"language",
"||",
"'en'",
";",
"var",
"body",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"options",
")",
"{",
"if",
"(",
"options",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"body",
"[",
"key",
"]",
"=",
"options",
"[",
"key",
"]",
"}",
"}",
"body",
".",
"texts",
"=",
"texts",
";",
"var",
"params",
"=",
"{",
"method",
":",
"'POST'",
",",
"url",
":",
"'/tonality'",
",",
"body",
":",
"body",
"}",
";",
"return",
"client",
".",
"request",
"(",
"params",
",",
"callback",
")",
";",
"}"
]
| Given a set of documents, return their tonality based on lexical analysis in multiple dimensions.
The tonality is calculated on a document level, that is, the response will return the tonality of
each document.
@param {Array|string} texts - an array of document objects or strings to be analyzed.
@param {object} [options] - optional set of options, forwarded to Gavagai API.
@param callback - callback function for when request is complete
- @param {object} error - an error object if there was a problem processing the request
- @param {object} data - the JSON-parsed data
@returns {*} - a promise. | [
"Given",
"a",
"set",
"of",
"documents",
"return",
"their",
"tonality",
"based",
"on",
"lexical",
"analysis",
"in",
"multiple",
"dimensions",
".",
"The",
"tonality",
"is",
"calculated",
"on",
"a",
"document",
"level",
"that",
"is",
"the",
"response",
"will",
"return",
"the",
"tonality",
"of",
"each",
"document",
"."
]
| d3f5e3f59f25d9c3ebbf6fd3a3ecb70b3a4047eb | https://github.com/gavagai-corp/gavagai-node/blob/d3f5e3f59f25d9c3ebbf6fd3a3ecb70b3a4047eb/lib/tonality.js#L18-L51 |
|
45,236 | theboyWhoCriedWoolf/transition-manager | example/example.js | clickRegion | function clickRegion( e ) {
let pos = {
x : e.clientX,
y : e.clientY
},
region = '',
dividant = 4,
right = window.innerWidth - (window.innerWidth / dividant),
left = (window.innerWidth / dividant),
top = (window.innerHeight / dividant),
bottom = window.innerHeight - (window.innerHeight / dividant);
if( pos.y <= top ) { region = 'top'; }
else if( pos.y >= bottom ) { region = 'bottom'; }
if( pos.x <= left ) { region = 'left'; }
else if( pos.x >= right ) { region = 'right'; }
return region;
} | javascript | function clickRegion( e ) {
let pos = {
x : e.clientX,
y : e.clientY
},
region = '',
dividant = 4,
right = window.innerWidth - (window.innerWidth / dividant),
left = (window.innerWidth / dividant),
top = (window.innerHeight / dividant),
bottom = window.innerHeight - (window.innerHeight / dividant);
if( pos.y <= top ) { region = 'top'; }
else if( pos.y >= bottom ) { region = 'bottom'; }
if( pos.x <= left ) { region = 'left'; }
else if( pos.x >= right ) { region = 'right'; }
return region;
} | [
"function",
"clickRegion",
"(",
"e",
")",
"{",
"let",
"pos",
"=",
"{",
"x",
":",
"e",
".",
"clientX",
",",
"y",
":",
"e",
".",
"clientY",
"}",
",",
"region",
"=",
"''",
",",
"dividant",
"=",
"4",
",",
"right",
"=",
"window",
".",
"innerWidth",
"-",
"(",
"window",
".",
"innerWidth",
"/",
"dividant",
")",
",",
"left",
"=",
"(",
"window",
".",
"innerWidth",
"/",
"dividant",
")",
",",
"top",
"=",
"(",
"window",
".",
"innerHeight",
"/",
"dividant",
")",
",",
"bottom",
"=",
"window",
".",
"innerHeight",
"-",
"(",
"window",
".",
"innerHeight",
"/",
"dividant",
")",
";",
"if",
"(",
"pos",
".",
"y",
"<=",
"top",
")",
"{",
"region",
"=",
"'top'",
";",
"}",
"else",
"if",
"(",
"pos",
".",
"y",
">=",
"bottom",
")",
"{",
"region",
"=",
"'bottom'",
";",
"}",
"if",
"(",
"pos",
".",
"x",
"<=",
"left",
")",
"{",
"region",
"=",
"'left'",
";",
"}",
"else",
"if",
"(",
"pos",
".",
"x",
">=",
"right",
")",
"{",
"region",
"=",
"'right'",
";",
"}",
"return",
"region",
";",
"}"
]
| get click quadrant based on mouse position | [
"get",
"click",
"quadrant",
"based",
"on",
"mouse",
"position"
]
| a20fda0bb07c0098bf709ea03770b1ee2a855655 | https://github.com/theboyWhoCriedWoolf/transition-manager/blob/a20fda0bb07c0098bf709ea03770b1ee2a855655/example/example.js#L54-L74 |
45,237 | edappy/seneca-context | plugins/getContext.js | getContextPlugin | function getContextPlugin(options) {
var seneca = this;
var plugin = 'get-context';
seneca.wrap(options.pin, function (message, done) {
var seneca = this;
message.context$ = getContext(seneca);
seneca.prior(message, done);
});
return {name: plugin};
} | javascript | function getContextPlugin(options) {
var seneca = this;
var plugin = 'get-context';
seneca.wrap(options.pin, function (message, done) {
var seneca = this;
message.context$ = getContext(seneca);
seneca.prior(message, done);
});
return {name: plugin};
} | [
"function",
"getContextPlugin",
"(",
"options",
")",
"{",
"var",
"seneca",
"=",
"this",
";",
"var",
"plugin",
"=",
"'get-context'",
";",
"seneca",
".",
"wrap",
"(",
"options",
".",
"pin",
",",
"function",
"(",
"message",
",",
"done",
")",
"{",
"var",
"seneca",
"=",
"this",
";",
"message",
".",
"context$",
"=",
"getContext",
"(",
"seneca",
")",
";",
"seneca",
".",
"prior",
"(",
"message",
",",
"done",
")",
";",
"}",
")",
";",
"return",
"{",
"name",
":",
"plugin",
"}",
";",
"}"
]
| A seneca plugin, which automatically exposes the context as a property of the incoming message.
@param {{
pin: string|Object // a seneca pattern to which this plugin should be applied
}} options | [
"A",
"seneca",
"plugin",
"which",
"automatically",
"exposes",
"the",
"context",
"as",
"a",
"property",
"of",
"the",
"incoming",
"message",
"."
]
| 1e0c8d36c5be4b661b062754c01f064de47873c4 | https://github.com/edappy/seneca-context/blob/1e0c8d36c5be4b661b062754c01f064de47873c4/plugins/getContext.js#L14-L25 |
45,238 | fknussel/custom-scripts | scripts/build.js | build | function build() {
console.log('Creating an optimized production build...\n');
webpack(config)
.run((err, stats) => {
if (err) {
printErrors('Failed to compile.', [err]);
process.exit(1);
}
if (stats.compilation.errors.length) {
printErrors('Failed to compile.', stats.compilation.errors);
process.exit(1);
}
if (process.env.CI && stats.compilation.warnings.length) {
printErrors('Failed to compile.', stats.compilation.warnings);
process.exit(1);
}
logSuccess('Compiled successfully.\n');
console.log('Bundle size details:\n');
printFileSizes(stats);
console.log(`\nThe ${chalk.green('build')} folder is ready to be deployed.\n`);
});
} | javascript | function build() {
console.log('Creating an optimized production build...\n');
webpack(config)
.run((err, stats) => {
if (err) {
printErrors('Failed to compile.', [err]);
process.exit(1);
}
if (stats.compilation.errors.length) {
printErrors('Failed to compile.', stats.compilation.errors);
process.exit(1);
}
if (process.env.CI && stats.compilation.warnings.length) {
printErrors('Failed to compile.', stats.compilation.warnings);
process.exit(1);
}
logSuccess('Compiled successfully.\n');
console.log('Bundle size details:\n');
printFileSizes(stats);
console.log(`\nThe ${chalk.green('build')} folder is ready to be deployed.\n`);
});
} | [
"function",
"build",
"(",
")",
"{",
"console",
".",
"log",
"(",
"'Creating an optimized production build...\\n'",
")",
";",
"webpack",
"(",
"config",
")",
".",
"run",
"(",
"(",
"err",
",",
"stats",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"printErrors",
"(",
"'Failed to compile.'",
",",
"[",
"err",
"]",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"if",
"(",
"stats",
".",
"compilation",
".",
"errors",
".",
"length",
")",
"{",
"printErrors",
"(",
"'Failed to compile.'",
",",
"stats",
".",
"compilation",
".",
"errors",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"if",
"(",
"process",
".",
"env",
".",
"CI",
"&&",
"stats",
".",
"compilation",
".",
"warnings",
".",
"length",
")",
"{",
"printErrors",
"(",
"'Failed to compile.'",
",",
"stats",
".",
"compilation",
".",
"warnings",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"logSuccess",
"(",
"'Compiled successfully.\\n'",
")",
";",
"console",
".",
"log",
"(",
"'Bundle size details:\\n'",
")",
";",
"printFileSizes",
"(",
"stats",
")",
";",
"console",
".",
"log",
"(",
"`",
"\\n",
"${",
"chalk",
".",
"green",
"(",
"'build'",
")",
"}",
"\\n",
"`",
")",
";",
"}",
")",
";",
"}"
]
| Create a production build | [
"Create",
"a",
"production",
"build"
]
| 801ad6f42bcde265e317d427b7ee0f371eeb0e9b | https://github.com/fknussel/custom-scripts/blob/801ad6f42bcde265e317d427b7ee0f371eeb0e9b/scripts/build.js#L26-L53 |
45,239 | onecommons/base | routes/crud.js | addToFooter | function addToFooter(schema, path, unwind) {
Object.keys(schema).forEach(function(name) {
if (name.slice(0,2) == '__')
return true;
if (!path && (name == 'id' || name == '_id'))
return;
if (model.schema.nested[path+name]) {
addToFooter(schema[name], path+name+'.', '')
} else if (schema[name] && schema[name].tree) {
addToFooter(schema[name].tree, path+name+'.');
if (typeof schema[name].options.strict === 'boolean' && !schema[name].options.strict) {
footer.push({name:name, path: path+name+'.*'});
}
} else if (name === unwind) {
addToFooter(schema[name][0].tree, path+name+'.0.')
if (typeof schema[name][0].options.strict === 'boolean' && !schema[name][0].options.strict) {
footer.push({name:name, path: path+name+'.0.*'});
}
} else {
if (skipField(path+name)) {
return;
}
footer.push({name:name, path: path+name})
}
});
} | javascript | function addToFooter(schema, path, unwind) {
Object.keys(schema).forEach(function(name) {
if (name.slice(0,2) == '__')
return true;
if (!path && (name == 'id' || name == '_id'))
return;
if (model.schema.nested[path+name]) {
addToFooter(schema[name], path+name+'.', '')
} else if (schema[name] && schema[name].tree) {
addToFooter(schema[name].tree, path+name+'.');
if (typeof schema[name].options.strict === 'boolean' && !schema[name].options.strict) {
footer.push({name:name, path: path+name+'.*'});
}
} else if (name === unwind) {
addToFooter(schema[name][0].tree, path+name+'.0.')
if (typeof schema[name][0].options.strict === 'boolean' && !schema[name][0].options.strict) {
footer.push({name:name, path: path+name+'.0.*'});
}
} else {
if (skipField(path+name)) {
return;
}
footer.push({name:name, path: path+name})
}
});
} | [
"function",
"addToFooter",
"(",
"schema",
",",
"path",
",",
"unwind",
")",
"{",
"Object",
".",
"keys",
"(",
"schema",
")",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"if",
"(",
"name",
".",
"slice",
"(",
"0",
",",
"2",
")",
"==",
"'__'",
")",
"return",
"true",
";",
"if",
"(",
"!",
"path",
"&&",
"(",
"name",
"==",
"'id'",
"||",
"name",
"==",
"'_id'",
")",
")",
"return",
";",
"if",
"(",
"model",
".",
"schema",
".",
"nested",
"[",
"path",
"+",
"name",
"]",
")",
"{",
"addToFooter",
"(",
"schema",
"[",
"name",
"]",
",",
"path",
"+",
"name",
"+",
"'.'",
",",
"''",
")",
"}",
"else",
"if",
"(",
"schema",
"[",
"name",
"]",
"&&",
"schema",
"[",
"name",
"]",
".",
"tree",
")",
"{",
"addToFooter",
"(",
"schema",
"[",
"name",
"]",
".",
"tree",
",",
"path",
"+",
"name",
"+",
"'.'",
")",
";",
"if",
"(",
"typeof",
"schema",
"[",
"name",
"]",
".",
"options",
".",
"strict",
"===",
"'boolean'",
"&&",
"!",
"schema",
"[",
"name",
"]",
".",
"options",
".",
"strict",
")",
"{",
"footer",
".",
"push",
"(",
"{",
"name",
":",
"name",
",",
"path",
":",
"path",
"+",
"name",
"+",
"'.*'",
"}",
")",
";",
"}",
"}",
"else",
"if",
"(",
"name",
"===",
"unwind",
")",
"{",
"addToFooter",
"(",
"schema",
"[",
"name",
"]",
"[",
"0",
"]",
".",
"tree",
",",
"path",
"+",
"name",
"+",
"'.0.'",
")",
"if",
"(",
"typeof",
"schema",
"[",
"name",
"]",
"[",
"0",
"]",
".",
"options",
".",
"strict",
"===",
"'boolean'",
"&&",
"!",
"schema",
"[",
"name",
"]",
"[",
"0",
"]",
".",
"options",
".",
"strict",
")",
"{",
"footer",
".",
"push",
"(",
"{",
"name",
":",
"name",
",",
"path",
":",
"path",
"+",
"name",
"+",
"'.0.*'",
"}",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"skipField",
"(",
"path",
"+",
"name",
")",
")",
"{",
"return",
";",
"}",
"footer",
".",
"push",
"(",
"{",
"name",
":",
"name",
",",
"path",
":",
"path",
"+",
"name",
"}",
")",
"}",
"}",
")",
";",
"}"
]
| only include leaves | [
"only",
"include",
"leaves"
]
| 4f35d9f714d0367b0622a3504802363404290246 | https://github.com/onecommons/base/blob/4f35d9f714d0367b0622a3504802363404290246/routes/crud.js#L514-L539 |
45,240 | vid/SenseBase | lib/content.js | diffContentItems | function diffContentItems(lhs, rhs) {
var d = diff(lhs, rhs, function(key, value) {
return value === 'visitors' || value === 'headers';
});
return d;
} | javascript | function diffContentItems(lhs, rhs) {
var d = diff(lhs, rhs, function(key, value) {
return value === 'visitors' || value === 'headers';
});
return d;
} | [
"function",
"diffContentItems",
"(",
"lhs",
",",
"rhs",
")",
"{",
"var",
"d",
"=",
"diff",
"(",
"lhs",
",",
"rhs",
",",
"function",
"(",
"key",
",",
"value",
")",
"{",
"return",
"value",
"===",
"'visitors'",
"||",
"value",
"===",
"'headers'",
";",
"}",
")",
";",
"return",
"d",
";",
"}"
]
| Compare two content items, returning any difference | [
"Compare",
"two",
"content",
"items",
"returning",
"any",
"difference"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/content.js#L247-L252 |
45,241 | vid/SenseBase | lib/content.js | extractContent | function extractContent(desc) {
/*
// search all possible matches, returning first find
var founds = sites.findMatch(desc.uri);
if (founds.length) {
var $ = cheerio.load(desc.content);
// use first found extractor
founds.forEach(function(found) {
if ($(found.selector)) {
var content = $(found.selector).html();
return { selector: found.selector, content: content };
}
});
}
// ok, let's try unfluff
var uf = unfluff(desc.content);
return { selector: 'body', content: desc.content, text: uf.text, title: uf.title };
*/
var title = getTitle(desc.content, '<title') || getTitle(desc.content, '<TITLE');
return { selector: 'body', content: desc.content, text: 'NOTEXTRACTED', title: title };
} | javascript | function extractContent(desc) {
/*
// search all possible matches, returning first find
var founds = sites.findMatch(desc.uri);
if (founds.length) {
var $ = cheerio.load(desc.content);
// use first found extractor
founds.forEach(function(found) {
if ($(found.selector)) {
var content = $(found.selector).html();
return { selector: found.selector, content: content };
}
});
}
// ok, let's try unfluff
var uf = unfluff(desc.content);
return { selector: 'body', content: desc.content, text: uf.text, title: uf.title };
*/
var title = getTitle(desc.content, '<title') || getTitle(desc.content, '<TITLE');
return { selector: 'body', content: desc.content, text: 'NOTEXTRACTED', title: title };
} | [
"function",
"extractContent",
"(",
"desc",
")",
"{",
"/*\n // search all possible matches, returning first find\n var founds = sites.findMatch(desc.uri);\n\n if (founds.length) {\n var $ = cheerio.load(desc.content);\n // use first found extractor\n founds.forEach(function(found) {\n if ($(found.selector)) {\n var content = $(found.selector).html();\n return { selector: found.selector, content: content };\n }\n });\n }\n // ok, let's try unfluff\n var uf = unfluff(desc.content);\n return { selector: 'body', content: desc.content, text: uf.text, title: uf.title };\n */",
"var",
"title",
"=",
"getTitle",
"(",
"desc",
".",
"content",
",",
"'<title'",
")",
"||",
"getTitle",
"(",
"desc",
".",
"content",
",",
"'<TITLE'",
")",
";",
"return",
"{",
"selector",
":",
"'body'",
",",
"content",
":",
"desc",
".",
"content",
",",
"text",
":",
"'NOTEXTRACTED'",
",",
"title",
":",
"title",
"}",
";",
"}"
]
| find finer content areas if available extract content based on site definitions | [
"find",
"finer",
"content",
"areas",
"if",
"available",
"extract",
"content",
"based",
"on",
"site",
"definitions"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/content.js#L348-L370 |
45,242 | vid/SenseBase | lib/content.js | getTitle | function getTitle(content, tag) {
if (!content) {
return;
}
var ts = content.indexOf(tag);
if (ts < 0) {
return;
}
var te = content.indexOf('>', ts);
var cs = content.indexOf('<', te + 1);
var title = content.substring(te + 1, cs);
return title.trim();
} | javascript | function getTitle(content, tag) {
if (!content) {
return;
}
var ts = content.indexOf(tag);
if (ts < 0) {
return;
}
var te = content.indexOf('>', ts);
var cs = content.indexOf('<', te + 1);
var title = content.substring(te + 1, cs);
return title.trim();
} | [
"function",
"getTitle",
"(",
"content",
",",
"tag",
")",
"{",
"if",
"(",
"!",
"content",
")",
"{",
"return",
";",
"}",
"var",
"ts",
"=",
"content",
".",
"indexOf",
"(",
"tag",
")",
";",
"if",
"(",
"ts",
"<",
"0",
")",
"{",
"return",
";",
"}",
"var",
"te",
"=",
"content",
".",
"indexOf",
"(",
"'>'",
",",
"ts",
")",
";",
"var",
"cs",
"=",
"content",
".",
"indexOf",
"(",
"'<'",
",",
"te",
"+",
"1",
")",
";",
"var",
"title",
"=",
"content",
".",
"substring",
"(",
"te",
"+",
"1",
",",
"cs",
")",
";",
"return",
"title",
".",
"trim",
"(",
")",
";",
"}"
]
| Get an HTML title the old-fashioned way. | [
"Get",
"an",
"HTML",
"title",
"the",
"old",
"-",
"fashioned",
"way",
"."
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/content.js#L373-L385 |
45,243 | henrytseng/angular-state-router | example/app.js | function() {
var i = Math.floor(_listing.length-1 * Math.random());
return $q.when(_listing[i]);
} | javascript | function() {
var i = Math.floor(_listing.length-1 * Math.random());
return $q.when(_listing[i]);
} | [
"function",
"(",
")",
"{",
"var",
"i",
"=",
"Math",
".",
"floor",
"(",
"_listing",
".",
"length",
"-",
"1",
"*",
"Math",
".",
"random",
"(",
")",
")",
";",
"return",
"$q",
".",
"when",
"(",
"_listing",
"[",
"i",
"]",
")",
";",
"}"
]
| Get random item | [
"Get",
"random",
"item"
]
| 5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b | https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/example/app.js#L299-L302 |
|
45,244 | henrytseng/angular-state-router | example/app.js | function(criteria) {
var results = [];
criteria = angular.isArray(criteria) ? criteria : [criteria];
// Search through each
criteria.forEach(function(q) {
if(q && q !== '') {
_listing.forEach(function(item) {
for(var name in item) {
if(item[name].toLowerCase().indexOf(q.toLowerCase()) !== -1 && results.indexOf(item) === -1) {
results.push(item);
}
}
});
}
});
return $q.when(results);
} | javascript | function(criteria) {
var results = [];
criteria = angular.isArray(criteria) ? criteria : [criteria];
// Search through each
criteria.forEach(function(q) {
if(q && q !== '') {
_listing.forEach(function(item) {
for(var name in item) {
if(item[name].toLowerCase().indexOf(q.toLowerCase()) !== -1 && results.indexOf(item) === -1) {
results.push(item);
}
}
});
}
});
return $q.when(results);
} | [
"function",
"(",
"criteria",
")",
"{",
"var",
"results",
"=",
"[",
"]",
";",
"criteria",
"=",
"angular",
".",
"isArray",
"(",
"criteria",
")",
"?",
"criteria",
":",
"[",
"criteria",
"]",
";",
"// Search through each",
"criteria",
".",
"forEach",
"(",
"function",
"(",
"q",
")",
"{",
"if",
"(",
"q",
"&&",
"q",
"!==",
"''",
")",
"{",
"_listing",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"for",
"(",
"var",
"name",
"in",
"item",
")",
"{",
"if",
"(",
"item",
"[",
"name",
"]",
".",
"toLowerCase",
"(",
")",
".",
"indexOf",
"(",
"q",
".",
"toLowerCase",
"(",
")",
")",
"!==",
"-",
"1",
"&&",
"results",
".",
"indexOf",
"(",
"item",
")",
"===",
"-",
"1",
")",
"{",
"results",
".",
"push",
"(",
"item",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"return",
"$q",
".",
"when",
"(",
"results",
")",
";",
"}"
]
| Search for a product | [
"Search",
"for",
"a",
"product"
]
| 5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b | https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/example/app.js#L305-L325 |
|
45,245 | benaston/partial-application | dist/partial-application.js | partialWithArityOfOne | function partialWithArityOfOne(fn) {
var args = arguments;
return function(a) {
return partial.apply(this, args).apply(this, arguments);
};
} | javascript | function partialWithArityOfOne(fn) {
var args = arguments;
return function(a) {
return partial.apply(this, args).apply(this, arguments);
};
} | [
"function",
"partialWithArityOfOne",
"(",
"fn",
")",
"{",
"var",
"args",
"=",
"arguments",
";",
"return",
"function",
"(",
"a",
")",
"{",
"return",
"partial",
".",
"apply",
"(",
"this",
",",
"args",
")",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
";",
"}"
]
| Partially apply a function, but ensure the returned function has an arity of one.
@param {Function} fn The function to partially apply.
@return {Function} The partially applied function. | [
"Partially",
"apply",
"a",
"function",
"but",
"ensure",
"the",
"returned",
"function",
"has",
"an",
"arity",
"of",
"one",
"."
]
| bfb79abc7d6a81f2ad5c237bc618c261051692d3 | https://github.com/benaston/partial-application/blob/bfb79abc7d6a81f2ad5c237bc618c261051692d3/dist/partial-application.js#L39-L45 |
45,246 | binduwavell/generator-alfresco-common | lib/maven-archetype-metadata.js | _getFileSet | function _getFileSet (fileSetElement) {
var filtered = utils.toBoolean(fileSetElement.getAttribute('filtered'), false);
var packaged = utils.toBoolean(fileSetElement.getAttribute('packaged'), false);
var encoding = fileSetElement.getAttribute('encoding');
var directory = domutils.getChild(fileSetElement, 'desc', 'directory').textContent;
var includes = domutils.selectMatchingXPath('desc:includes/desc:include', fileSetElement);
var excludes = domutils.selectMatchingXPath('desc:excludes/desc:exclude', fileSetElement);
var fileSet = {
filtered: filtered, packaged: packaged, encoding: encoding, directory: directory, includes: [], excludes: [],
};
includes.forEach(function (include) {
fileSet.includes.push(include.textContent);
});
excludes.forEach(function (exclude) {
fileSet.excludes.push(exclude.textContent);
});
return fileSet;
} | javascript | function _getFileSet (fileSetElement) {
var filtered = utils.toBoolean(fileSetElement.getAttribute('filtered'), false);
var packaged = utils.toBoolean(fileSetElement.getAttribute('packaged'), false);
var encoding = fileSetElement.getAttribute('encoding');
var directory = domutils.getChild(fileSetElement, 'desc', 'directory').textContent;
var includes = domutils.selectMatchingXPath('desc:includes/desc:include', fileSetElement);
var excludes = domutils.selectMatchingXPath('desc:excludes/desc:exclude', fileSetElement);
var fileSet = {
filtered: filtered, packaged: packaged, encoding: encoding, directory: directory, includes: [], excludes: [],
};
includes.forEach(function (include) {
fileSet.includes.push(include.textContent);
});
excludes.forEach(function (exclude) {
fileSet.excludes.push(exclude.textContent);
});
return fileSet;
} | [
"function",
"_getFileSet",
"(",
"fileSetElement",
")",
"{",
"var",
"filtered",
"=",
"utils",
".",
"toBoolean",
"(",
"fileSetElement",
".",
"getAttribute",
"(",
"'filtered'",
")",
",",
"false",
")",
";",
"var",
"packaged",
"=",
"utils",
".",
"toBoolean",
"(",
"fileSetElement",
".",
"getAttribute",
"(",
"'packaged'",
")",
",",
"false",
")",
";",
"var",
"encoding",
"=",
"fileSetElement",
".",
"getAttribute",
"(",
"'encoding'",
")",
";",
"var",
"directory",
"=",
"domutils",
".",
"getChild",
"(",
"fileSetElement",
",",
"'desc'",
",",
"'directory'",
")",
".",
"textContent",
";",
"var",
"includes",
"=",
"domutils",
".",
"selectMatchingXPath",
"(",
"'desc:includes/desc:include'",
",",
"fileSetElement",
")",
";",
"var",
"excludes",
"=",
"domutils",
".",
"selectMatchingXPath",
"(",
"'desc:excludes/desc:exclude'",
",",
"fileSetElement",
")",
";",
"var",
"fileSet",
"=",
"{",
"filtered",
":",
"filtered",
",",
"packaged",
":",
"packaged",
",",
"encoding",
":",
"encoding",
",",
"directory",
":",
"directory",
",",
"includes",
":",
"[",
"]",
",",
"excludes",
":",
"[",
"]",
",",
"}",
";",
"includes",
".",
"forEach",
"(",
"function",
"(",
"include",
")",
"{",
"fileSet",
".",
"includes",
".",
"push",
"(",
"include",
".",
"textContent",
")",
";",
"}",
")",
";",
"excludes",
".",
"forEach",
"(",
"function",
"(",
"exclude",
")",
"{",
"fileSet",
".",
"excludes",
".",
"push",
"(",
"exclude",
".",
"textContent",
")",
";",
"}",
")",
";",
"return",
"fileSet",
";",
"}"
]
| Produces a JavaScript object representing a fileSet.
@param {Element} fileSetElement
@returns {{filtered: (boolean|undefined), packaged: (boolean|undefined), encoding: (string|*), directory, includes: Array, excludes: Array}}
@private | [
"Produces",
"a",
"JavaScript",
"object",
"representing",
"a",
"fileSet",
"."
]
| d9ba309a1b1d26a97268a07a49ac9e5d86b31dc4 | https://github.com/binduwavell/generator-alfresco-common/blob/d9ba309a1b1d26a97268a07a49ac9e5d86b31dc4/lib/maven-archetype-metadata.js#L91-L108 |
45,247 | binduwavell/generator-alfresco-common | lib/maven-archetype-metadata.js | _getModule | function _getModule (moduleElement) {
var id = moduleElement.getAttribute('id');
var dir = moduleElement.getAttribute('dir');
var name = moduleElement.getAttribute('name');
var fileSets = domutils.getChild(moduleElement, 'desc', 'fileSets');
var modules = domutils.getChild(moduleElement, 'desc', 'modules');
var module = { id: id, dir: dir, name: name, fileSets: [], modules: [] };
if (fileSets !== undefined) {
var fileSetElements = domutils.selectMatchingXPath('desc:fileSet', fileSets);
var numFileSets = fileSetElements.length;
for (var fsIdx = 0; fsIdx < numFileSets; fsIdx++) {
module.fileSets.push(_getFileSet(fileSetElements[fsIdx]));
}
}
if (modules !== undefined) {
var moduleElements = domutils.selectMatchingXPath('desc:module', modules);
var numModules = moduleElements.length;
for (var mIdx = 0; mIdx < numModules; mIdx++) {
module.modules.push(_getModule(moduleElements[mIdx]));
}
}
return module;
} | javascript | function _getModule (moduleElement) {
var id = moduleElement.getAttribute('id');
var dir = moduleElement.getAttribute('dir');
var name = moduleElement.getAttribute('name');
var fileSets = domutils.getChild(moduleElement, 'desc', 'fileSets');
var modules = domutils.getChild(moduleElement, 'desc', 'modules');
var module = { id: id, dir: dir, name: name, fileSets: [], modules: [] };
if (fileSets !== undefined) {
var fileSetElements = domutils.selectMatchingXPath('desc:fileSet', fileSets);
var numFileSets = fileSetElements.length;
for (var fsIdx = 0; fsIdx < numFileSets; fsIdx++) {
module.fileSets.push(_getFileSet(fileSetElements[fsIdx]));
}
}
if (modules !== undefined) {
var moduleElements = domutils.selectMatchingXPath('desc:module', modules);
var numModules = moduleElements.length;
for (var mIdx = 0; mIdx < numModules; mIdx++) {
module.modules.push(_getModule(moduleElements[mIdx]));
}
}
return module;
} | [
"function",
"_getModule",
"(",
"moduleElement",
")",
"{",
"var",
"id",
"=",
"moduleElement",
".",
"getAttribute",
"(",
"'id'",
")",
";",
"var",
"dir",
"=",
"moduleElement",
".",
"getAttribute",
"(",
"'dir'",
")",
";",
"var",
"name",
"=",
"moduleElement",
".",
"getAttribute",
"(",
"'name'",
")",
";",
"var",
"fileSets",
"=",
"domutils",
".",
"getChild",
"(",
"moduleElement",
",",
"'desc'",
",",
"'fileSets'",
")",
";",
"var",
"modules",
"=",
"domutils",
".",
"getChild",
"(",
"moduleElement",
",",
"'desc'",
",",
"'modules'",
")",
";",
"var",
"module",
"=",
"{",
"id",
":",
"id",
",",
"dir",
":",
"dir",
",",
"name",
":",
"name",
",",
"fileSets",
":",
"[",
"]",
",",
"modules",
":",
"[",
"]",
"}",
";",
"if",
"(",
"fileSets",
"!==",
"undefined",
")",
"{",
"var",
"fileSetElements",
"=",
"domutils",
".",
"selectMatchingXPath",
"(",
"'desc:fileSet'",
",",
"fileSets",
")",
";",
"var",
"numFileSets",
"=",
"fileSetElements",
".",
"length",
";",
"for",
"(",
"var",
"fsIdx",
"=",
"0",
";",
"fsIdx",
"<",
"numFileSets",
";",
"fsIdx",
"++",
")",
"{",
"module",
".",
"fileSets",
".",
"push",
"(",
"_getFileSet",
"(",
"fileSetElements",
"[",
"fsIdx",
"]",
")",
")",
";",
"}",
"}",
"if",
"(",
"modules",
"!==",
"undefined",
")",
"{",
"var",
"moduleElements",
"=",
"domutils",
".",
"selectMatchingXPath",
"(",
"'desc:module'",
",",
"modules",
")",
";",
"var",
"numModules",
"=",
"moduleElements",
".",
"length",
";",
"for",
"(",
"var",
"mIdx",
"=",
"0",
";",
"mIdx",
"<",
"numModules",
";",
"mIdx",
"++",
")",
"{",
"module",
".",
"modules",
".",
"push",
"(",
"_getModule",
"(",
"moduleElements",
"[",
"mIdx",
"]",
")",
")",
";",
"}",
"}",
"return",
"module",
";",
"}"
]
| Produces a JavaScript object representing a module.
@param {!Element} moduleElement
@returns {{id: (string|*), dir: (string|*), name: (string|*), fileSets: Array, modules: Array}}
@private | [
"Produces",
"a",
"JavaScript",
"object",
"representing",
"a",
"module",
"."
]
| d9ba309a1b1d26a97268a07a49ac9e5d86b31dc4 | https://github.com/binduwavell/generator-alfresco-common/blob/d9ba309a1b1d26a97268a07a49ac9e5d86b31dc4/lib/maven-archetype-metadata.js#L134-L156 |
45,248 | jldec/pub-generator | generator.js | unload | function unload() {
u.each(opts.sources, function(source) {
if (source.src && source.src.unref) { source.src.unref(); }
if (source.cache && source.cache.unref) { source.cache.unref(); }
});
u.each(opts.outputs, function(output) {
if (output.output && output.output.cancel) { output.output.cancel(); }
});
if (generator.reload && generator.reload.cancel) { generator.reload.cancel(); }
if (generator.clientSave && generator.clientSave.cancel) { generator.clientSave.cancel(); }
} | javascript | function unload() {
u.each(opts.sources, function(source) {
if (source.src && source.src.unref) { source.src.unref(); }
if (source.cache && source.cache.unref) { source.cache.unref(); }
});
u.each(opts.outputs, function(output) {
if (output.output && output.output.cancel) { output.output.cancel(); }
});
if (generator.reload && generator.reload.cancel) { generator.reload.cancel(); }
if (generator.clientSave && generator.clientSave.cancel) { generator.clientSave.cancel(); }
} | [
"function",
"unload",
"(",
")",
"{",
"u",
".",
"each",
"(",
"opts",
".",
"sources",
",",
"function",
"(",
"source",
")",
"{",
"if",
"(",
"source",
".",
"src",
"&&",
"source",
".",
"src",
".",
"unref",
")",
"{",
"source",
".",
"src",
".",
"unref",
"(",
")",
";",
"}",
"if",
"(",
"source",
".",
"cache",
"&&",
"source",
".",
"cache",
".",
"unref",
")",
"{",
"source",
".",
"cache",
".",
"unref",
"(",
")",
";",
"}",
"}",
")",
";",
"u",
".",
"each",
"(",
"opts",
".",
"outputs",
",",
"function",
"(",
"output",
")",
"{",
"if",
"(",
"output",
".",
"output",
"&&",
"output",
".",
"output",
".",
"cancel",
")",
"{",
"output",
".",
"output",
".",
"cancel",
"(",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"generator",
".",
"reload",
"&&",
"generator",
".",
"reload",
".",
"cancel",
")",
"{",
"generator",
".",
"reload",
".",
"cancel",
"(",
")",
";",
"}",
"if",
"(",
"generator",
".",
"clientSave",
"&&",
"generator",
".",
"clientSave",
".",
"cancel",
")",
"{",
"generator",
".",
"clientSave",
".",
"cancel",
"(",
")",
";",
"}",
"}"
]
| disconnect all sources and cancel all throttled functions | [
"disconnect",
"all",
"sources",
"and",
"cancel",
"all",
"throttled",
"functions"
]
| 524081509921ac8cb897753142324d61e10afdf3 | https://github.com/jldec/pub-generator/blob/524081509921ac8cb897753142324d61e10afdf3/generator.js#L140-L150 |
45,249 | jldec/pub-generator | generator.js | redirect | function redirect(url) {
var path = u.urlPath(url);
var params = u.urlParams(url);
var pg = generator.aliase$[path];
if (pg) return { status:301, url:pg._href + params };
pg = generator.redirect$[path];
if (pg) return { status:302, url:pg._href + params };
// customRedirects return params also
pg = generator.customRedirect && generator.customRedirect(url);
if (pg) return { status:301, url:pg };
} | javascript | function redirect(url) {
var path = u.urlPath(url);
var params = u.urlParams(url);
var pg = generator.aliase$[path];
if (pg) return { status:301, url:pg._href + params };
pg = generator.redirect$[path];
if (pg) return { status:302, url:pg._href + params };
// customRedirects return params also
pg = generator.customRedirect && generator.customRedirect(url);
if (pg) return { status:301, url:pg };
} | [
"function",
"redirect",
"(",
"url",
")",
"{",
"var",
"path",
"=",
"u",
".",
"urlPath",
"(",
"url",
")",
";",
"var",
"params",
"=",
"u",
".",
"urlParams",
"(",
"url",
")",
";",
"var",
"pg",
"=",
"generator",
".",
"aliase$",
"[",
"path",
"]",
";",
"if",
"(",
"pg",
")",
"return",
"{",
"status",
":",
"301",
",",
"url",
":",
"pg",
".",
"_href",
"+",
"params",
"}",
";",
"pg",
"=",
"generator",
".",
"redirect$",
"[",
"path",
"]",
";",
"if",
"(",
"pg",
")",
"return",
"{",
"status",
":",
"302",
",",
"url",
":",
"pg",
".",
"_href",
"+",
"params",
"}",
";",
"// customRedirects return params also",
"pg",
"=",
"generator",
".",
"customRedirect",
"&&",
"generator",
".",
"customRedirect",
"(",
"url",
")",
";",
"if",
"(",
"pg",
")",
"return",
"{",
"status",
":",
"301",
",",
"url",
":",
"pg",
"}",
";",
"}"
]
| compute alias or custom redirect for a url - returns falsy if none 302 redirects are temporary - browsers won't try to remember them 301 redirects are permanent - browsers will cache and avoid re-requesting | [
"compute",
"alias",
"or",
"custom",
"redirect",
"for",
"a",
"url",
"-",
"returns",
"falsy",
"if",
"none",
"302",
"redirects",
"are",
"temporary",
"-",
"browsers",
"won",
"t",
"try",
"to",
"remember",
"them",
"301",
"redirects",
"are",
"permanent",
"-",
"browsers",
"will",
"cache",
"and",
"avoid",
"re",
"-",
"requesting"
]
| 524081509921ac8cb897753142324d61e10afdf3 | https://github.com/jldec/pub-generator/blob/524081509921ac8cb897753142324d61e10afdf3/generator.js#L238-L251 |
45,250 | UNLOQIO/unloq-node-client | lib/api.js | UnloqApi | function UnloqApi(authObj) {
if(typeof authObj !== 'object' || authObj === null) {
throw new Error('Unloq.Api: First constructor argument must be an instance of unloq.Auth');
}
// If we receive only the object with configuration, we try and create the auth object.
if(authObj.__type !== 'auth') {
var AuthClass = Auth();
authObj = new AuthClass(authObj);
}
auth = authObj;
} | javascript | function UnloqApi(authObj) {
if(typeof authObj !== 'object' || authObj === null) {
throw new Error('Unloq.Api: First constructor argument must be an instance of unloq.Auth');
}
// If we receive only the object with configuration, we try and create the auth object.
if(authObj.__type !== 'auth') {
var AuthClass = Auth();
authObj = new AuthClass(authObj);
}
auth = authObj;
} | [
"function",
"UnloqApi",
"(",
"authObj",
")",
"{",
"if",
"(",
"typeof",
"authObj",
"!==",
"'object'",
"||",
"authObj",
"===",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unloq.Api: First constructor argument must be an instance of unloq.Auth'",
")",
";",
"}",
"// If we receive only the object with configuration, we try and create the auth object.",
"if",
"(",
"authObj",
".",
"__type",
"!==",
"'auth'",
")",
"{",
"var",
"AuthClass",
"=",
"Auth",
"(",
")",
";",
"authObj",
"=",
"new",
"AuthClass",
"(",
"authObj",
")",
";",
"}",
"auth",
"=",
"authObj",
";",
"}"
]
| this is an unloq.Auth instance. | [
"this",
"is",
"an",
"unloq",
".",
"Auth",
"instance",
"."
]
| f88adeb7f0d3c729c6b578bff4aa5f548b84133b | https://github.com/UNLOQIO/unloq-node-client/blob/f88adeb7f0d3c729c6b578bff4aa5f548b84133b/lib/api.js#L12-L22 |
45,251 | DScheglov/merest | lib/middlewares/register-api.js | registerApi | function registerApi(isApp, apiObject) {
if (isApp) {
return function (req, res, next) {
res.__api = apiObject;
return next();
};
};
return function (req, res, next) {
res.__modelAPI = apiObject;
return next();
};
} | javascript | function registerApi(isApp, apiObject) {
if (isApp) {
return function (req, res, next) {
res.__api = apiObject;
return next();
};
};
return function (req, res, next) {
res.__modelAPI = apiObject;
return next();
};
} | [
"function",
"registerApi",
"(",
"isApp",
",",
"apiObject",
")",
"{",
"if",
"(",
"isApp",
")",
"{",
"return",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"res",
".",
"__api",
"=",
"apiObject",
";",
"return",
"next",
"(",
")",
";",
"}",
";",
"}",
";",
"return",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"res",
".",
"__modelAPI",
"=",
"apiObject",
";",
"return",
"next",
"(",
")",
";",
"}",
";",
"}"
]
| registerApi - the factory for middleware that registers api in response object
@param {ModelAPIRouter|ModelAPIExpress} apiObject the ModelAPIRouter or ModelAPIRouter
@return {Function} description | [
"registerApi",
"-",
"the",
"factory",
"for",
"middleware",
"that",
"registers",
"api",
"in",
"response",
"object"
]
| d39e7ef0d56236247773467e9bfe83cb128ebc01 | https://github.com/DScheglov/merest/blob/d39e7ef0d56236247773467e9bfe83cb128ebc01/lib/middlewares/register-api.js#L10-L23 |
45,252 | vadr-vr/VR-Analytics-JSCore | js/timeManager.js | init | function init(){
frameUnixTime = utils.getUnixTimeInMilliseconds();
frameDuration = 0;
frameDurationClone = 0;
timeSinceStart = 0;
playTimeSinceStart = 0;
appActive = true;
appPlaying = true;
videoDuration = 0;
videoPlaying = false;
} | javascript | function init(){
frameUnixTime = utils.getUnixTimeInMilliseconds();
frameDuration = 0;
frameDurationClone = 0;
timeSinceStart = 0;
playTimeSinceStart = 0;
appActive = true;
appPlaying = true;
videoDuration = 0;
videoPlaying = false;
} | [
"function",
"init",
"(",
")",
"{",
"frameUnixTime",
"=",
"utils",
".",
"getUnixTimeInMilliseconds",
"(",
")",
";",
"frameDuration",
"=",
"0",
";",
"frameDurationClone",
"=",
"0",
";",
"timeSinceStart",
"=",
"0",
";",
"playTimeSinceStart",
"=",
"0",
";",
"appActive",
"=",
"true",
";",
"appPlaying",
"=",
"true",
";",
"videoDuration",
"=",
"0",
";",
"videoPlaying",
"=",
"false",
";",
"}"
]
| Init the time manager, sets frameUnixTime to current value
@memberof TimeManager | [
"Init",
"the",
"time",
"manager",
"sets",
"frameUnixTime",
"to",
"current",
"value"
]
| 7e4a493c824c2c1716360dcb6a3bfecfede5df3b | https://github.com/vadr-vr/VR-Analytics-JSCore/blob/7e4a493c824c2c1716360dcb6a3bfecfede5df3b/js/timeManager.js#L30-L42 |
45,253 | vadr-vr/VR-Analytics-JSCore | js/timeManager.js | tick | function tick(frameTime){
let newFrameUnixTime = utils.getUnixTimeInMilliseconds();
if (frameTime)
frameDuration = frameTime;
else
frameDuration = newFrameUnixTime - frameUnixTime;
// dont consider frame duration if app is not active
frameDurationClone = appActive ? frameDuration : 0;
frameUnixTime = newFrameUnixTime;
timeSinceStart += frameDurationClone;
if (appPlaying){
playTimeSinceStart += frameDurationClone;
}
if (videoPlaying){
videoDuration += utils.convertMillisecondsToSecondsFloat(frameDurationClone);
}
} | javascript | function tick(frameTime){
let newFrameUnixTime = utils.getUnixTimeInMilliseconds();
if (frameTime)
frameDuration = frameTime;
else
frameDuration = newFrameUnixTime - frameUnixTime;
// dont consider frame duration if app is not active
frameDurationClone = appActive ? frameDuration : 0;
frameUnixTime = newFrameUnixTime;
timeSinceStart += frameDurationClone;
if (appPlaying){
playTimeSinceStart += frameDurationClone;
}
if (videoPlaying){
videoDuration += utils.convertMillisecondsToSecondsFloat(frameDurationClone);
}
} | [
"function",
"tick",
"(",
"frameTime",
")",
"{",
"let",
"newFrameUnixTime",
"=",
"utils",
".",
"getUnixTimeInMilliseconds",
"(",
")",
";",
"if",
"(",
"frameTime",
")",
"frameDuration",
"=",
"frameTime",
";",
"else",
"frameDuration",
"=",
"newFrameUnixTime",
"-",
"frameUnixTime",
";",
"// dont consider frame duration if app is not active",
"frameDurationClone",
"=",
"appActive",
"?",
"frameDuration",
":",
"0",
";",
"frameUnixTime",
"=",
"newFrameUnixTime",
";",
"timeSinceStart",
"+=",
"frameDurationClone",
";",
"if",
"(",
"appPlaying",
")",
"{",
"playTimeSinceStart",
"+=",
"frameDurationClone",
";",
"}",
"if",
"(",
"videoPlaying",
")",
"{",
"videoDuration",
"+=",
"utils",
".",
"convertMillisecondsToSecondsFloat",
"(",
"frameDurationClone",
")",
";",
"}",
"}"
]
| Updates the application timings.
Calculates frameTime as the difference of current
frame time and the previous frame time. In case app was not active the previous frame,
sets the frame time to 0. Correspondingly calculates timeSinceStart and
playTimeSinceStart
@memberof TimeManager
@param {number} frameTime specify the frameDuration if known [optional] | [
"Updates",
"the",
"application",
"timings",
".",
"Calculates",
"frameTime",
"as",
"the",
"difference",
"of",
"current",
"frame",
"time",
"and",
"the",
"previous",
"frame",
"time",
".",
"In",
"case",
"app",
"was",
"not",
"active",
"the",
"previous",
"frame",
"sets",
"the",
"frame",
"time",
"to",
"0",
".",
"Correspondingly",
"calculates",
"timeSinceStart",
"and",
"playTimeSinceStart"
]
| 7e4a493c824c2c1716360dcb6a3bfecfede5df3b | https://github.com/vadr-vr/VR-Analytics-JSCore/blob/7e4a493c824c2c1716360dcb6a3bfecfede5df3b/js/timeManager.js#L53-L80 |
45,254 | OpenSmartEnvironment/ose | lib/field/wrap.js | init | function init(owner, field, layout, val, children) { // {{{2
/**
* Field wrapper constructor
*
* @param owner {Object} Owning wrap list
* @param field {Object} Field description object
* @param layout {Object} Layout
* @param val {*} Field value
*
* @method constructor
*/
this.owner = owner;
owner.fields.push(this);
this.field = field;
this.value = val;
if (layout) this.layout = layout;
if (children) this.children = children;
} | javascript | function init(owner, field, layout, val, children) { // {{{2
/**
* Field wrapper constructor
*
* @param owner {Object} Owning wrap list
* @param field {Object} Field description object
* @param layout {Object} Layout
* @param val {*} Field value
*
* @method constructor
*/
this.owner = owner;
owner.fields.push(this);
this.field = field;
this.value = val;
if (layout) this.layout = layout;
if (children) this.children = children;
} | [
"function",
"init",
"(",
"owner",
",",
"field",
",",
"layout",
",",
"val",
",",
"children",
")",
"{",
"// {{{2",
"/**\n * Field wrapper constructor\n *\n * @param owner {Object} Owning wrap list\n * @param field {Object} Field description object\n * @param layout {Object} Layout\n * @param val {*} Field value\n *\n * @method constructor\n */",
"this",
".",
"owner",
"=",
"owner",
";",
"owner",
".",
"fields",
".",
"push",
"(",
"this",
")",
";",
"this",
".",
"field",
"=",
"field",
";",
"this",
".",
"value",
"=",
"val",
";",
"if",
"(",
"layout",
")",
"this",
".",
"layout",
"=",
"layout",
";",
"if",
"(",
"children",
")",
"this",
".",
"children",
"=",
"children",
";",
"}"
]
| Optional error returned from field.unformat
@property editError
@type Object
Public {{{1 | [
"Optional",
"error",
"returned",
"from",
"field",
".",
"unformat"
]
| 2ab051d9db6e77341c40abb9cbdae6ce586917e0 | https://github.com/OpenSmartEnvironment/ose/blob/2ab051d9db6e77341c40abb9cbdae6ce586917e0/lib/field/wrap.js#L88-L108 |
45,255 | primus/condenseify | index.js | condenseify | function condenseify(file, options) {
if (/\.json$/.test(file)) return through();
var appendNewLine = true
, regex = /^[ \t]+$/
, isBlank = false
, eol ='\n';
options = options || {};
function transform(line, encoding, next) {
if (!line.length) {
isBlank = true;
return next();
}
line = line.toString();
if (!options['keep-non-empty'] && regex.test(line)) return next();
if (isBlank) {
isBlank = false;
this.push(eol);
}
appendNewLine = false;
this.push(line + eol);
next();
}
function flush(done) {
if (appendNewLine) this.push(eol);
done();
}
return pumpify(split(), through(transform, flush));
} | javascript | function condenseify(file, options) {
if (/\.json$/.test(file)) return through();
var appendNewLine = true
, regex = /^[ \t]+$/
, isBlank = false
, eol ='\n';
options = options || {};
function transform(line, encoding, next) {
if (!line.length) {
isBlank = true;
return next();
}
line = line.toString();
if (!options['keep-non-empty'] && regex.test(line)) return next();
if (isBlank) {
isBlank = false;
this.push(eol);
}
appendNewLine = false;
this.push(line + eol);
next();
}
function flush(done) {
if (appendNewLine) this.push(eol);
done();
}
return pumpify(split(), through(transform, flush));
} | [
"function",
"condenseify",
"(",
"file",
",",
"options",
")",
"{",
"if",
"(",
"/",
"\\.json$",
"/",
".",
"test",
"(",
"file",
")",
")",
"return",
"through",
"(",
")",
";",
"var",
"appendNewLine",
"=",
"true",
",",
"regex",
"=",
"/",
"^[ \\t]+$",
"/",
",",
"isBlank",
"=",
"false",
",",
"eol",
"=",
"'\\n'",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"function",
"transform",
"(",
"line",
",",
"encoding",
",",
"next",
")",
"{",
"if",
"(",
"!",
"line",
".",
"length",
")",
"{",
"isBlank",
"=",
"true",
";",
"return",
"next",
"(",
")",
";",
"}",
"line",
"=",
"line",
".",
"toString",
"(",
")",
";",
"if",
"(",
"!",
"options",
"[",
"'keep-non-empty'",
"]",
"&&",
"regex",
".",
"test",
"(",
"line",
")",
")",
"return",
"next",
"(",
")",
";",
"if",
"(",
"isBlank",
")",
"{",
"isBlank",
"=",
"false",
";",
"this",
".",
"push",
"(",
"eol",
")",
";",
"}",
"appendNewLine",
"=",
"false",
";",
"this",
".",
"push",
"(",
"line",
"+",
"eol",
")",
";",
"next",
"(",
")",
";",
"}",
"function",
"flush",
"(",
"done",
")",
"{",
"if",
"(",
"appendNewLine",
")",
"this",
".",
"push",
"(",
"eol",
")",
";",
"done",
"(",
")",
";",
"}",
"return",
"pumpify",
"(",
"split",
"(",
")",
",",
"through",
"(",
"transform",
",",
"flush",
")",
")",
";",
"}"
]
| Browserify transform to condense multiple blank lines
into a single blank line.
@param {String} file File name
@param {Object} [options] Options object
@returns {Stream} Transform stream
@api public | [
"Browserify",
"transform",
"to",
"condense",
"multiple",
"blank",
"lines",
"into",
"a",
"single",
"blank",
"line",
"."
]
| 1330ead68f7d5cdbcf4f08ad8fc4138920eb4c54 | https://github.com/primus/condenseify/blob/1330ead68f7d5cdbcf4f08ad8fc4138920eb4c54/index.js#L21-L55 |
45,256 | sembaye/numberconverter | index.js | removezeros | function removezeros(bin){
var i = 0;
while((i < bin.length) && (!bin[i])){i++;}
if(i == bin.length){
return filledarray(false, 1);
}else{
return bin.slice(i);
}
} | javascript | function removezeros(bin){
var i = 0;
while((i < bin.length) && (!bin[i])){i++;}
if(i == bin.length){
return filledarray(false, 1);
}else{
return bin.slice(i);
}
} | [
"function",
"removezeros",
"(",
"bin",
")",
"{",
"var",
"i",
"=",
"0",
";",
"while",
"(",
"(",
"i",
"<",
"bin",
".",
"length",
")",
"&&",
"(",
"!",
"bin",
"[",
"i",
"]",
")",
")",
"{",
"i",
"++",
";",
"}",
"if",
"(",
"i",
"==",
"bin",
".",
"length",
")",
"{",
"return",
"filledarray",
"(",
"false",
",",
"1",
")",
";",
"}",
"else",
"{",
"return",
"bin",
".",
"slice",
"(",
"i",
")",
";",
"}",
"}"
]
| Removes all prefixing zeros from the binary array. | [
"Removes",
"all",
"prefixing",
"zeros",
"from",
"the",
"binary",
"array",
"."
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L4-L12 |
45,257 | sembaye/numberconverter | index.js | decinputtobin | function decinputtobin(decinput){
var len = decinput.length;
if(len == 0){return filledarray(false, 1);}
var bin = new Array();
var digit = new Array(4);
for (var i = 0; i < len; i++){
switch (decinput[i]){
case '0': digit[0] = false; digit[1] = false; digit[2] = false; digit[3] = false; break;
case '1': digit[0] = false; digit[1] = false; digit[2] = false; digit[3] = true; break;
case '2': digit[0] = false; digit[1] = false; digit[2] = true; digit[3] = false; break;
case '3': digit[0] = false; digit[1] = false; digit[2] = true; digit[3] = true; break;
case '4': digit[0] = false; digit[1] = true; digit[2] = false; digit[3] = false; break;
case '5': digit[0] = false; digit[1] = true; digit[2] = false; digit[3] = true; break;
case '6': digit[0] = false; digit[1] = true; digit[2] = true; digit[3] = false; break;
case '7': digit[0] = false; digit[1] = true; digit[2] = true; digit[3] = true; break;
case '8': digit[0] = true; digit[1] = false; digit[2] = false; digit[3] = false; break;
case '9': digit[0] = true; digit[1] = false; digit[2] = false; digit[3] = true; break;
default: continue;
}
bin = binadd(binten(bin), digit);
}
return removezeros(bin);
} | javascript | function decinputtobin(decinput){
var len = decinput.length;
if(len == 0){return filledarray(false, 1);}
var bin = new Array();
var digit = new Array(4);
for (var i = 0; i < len; i++){
switch (decinput[i]){
case '0': digit[0] = false; digit[1] = false; digit[2] = false; digit[3] = false; break;
case '1': digit[0] = false; digit[1] = false; digit[2] = false; digit[3] = true; break;
case '2': digit[0] = false; digit[1] = false; digit[2] = true; digit[3] = false; break;
case '3': digit[0] = false; digit[1] = false; digit[2] = true; digit[3] = true; break;
case '4': digit[0] = false; digit[1] = true; digit[2] = false; digit[3] = false; break;
case '5': digit[0] = false; digit[1] = true; digit[2] = false; digit[3] = true; break;
case '6': digit[0] = false; digit[1] = true; digit[2] = true; digit[3] = false; break;
case '7': digit[0] = false; digit[1] = true; digit[2] = true; digit[3] = true; break;
case '8': digit[0] = true; digit[1] = false; digit[2] = false; digit[3] = false; break;
case '9': digit[0] = true; digit[1] = false; digit[2] = false; digit[3] = true; break;
default: continue;
}
bin = binadd(binten(bin), digit);
}
return removezeros(bin);
} | [
"function",
"decinputtobin",
"(",
"decinput",
")",
"{",
"var",
"len",
"=",
"decinput",
".",
"length",
";",
"if",
"(",
"len",
"==",
"0",
")",
"{",
"return",
"filledarray",
"(",
"false",
",",
"1",
")",
";",
"}",
"var",
"bin",
"=",
"new",
"Array",
"(",
")",
";",
"var",
"digit",
"=",
"new",
"Array",
"(",
"4",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"switch",
"(",
"decinput",
"[",
"i",
"]",
")",
"{",
"case",
"'0'",
":",
"digit",
"[",
"0",
"]",
"=",
"false",
";",
"digit",
"[",
"1",
"]",
"=",
"false",
";",
"digit",
"[",
"2",
"]",
"=",
"false",
";",
"digit",
"[",
"3",
"]",
"=",
"false",
";",
"break",
";",
"case",
"'1'",
":",
"digit",
"[",
"0",
"]",
"=",
"false",
";",
"digit",
"[",
"1",
"]",
"=",
"false",
";",
"digit",
"[",
"2",
"]",
"=",
"false",
";",
"digit",
"[",
"3",
"]",
"=",
"true",
";",
"break",
";",
"case",
"'2'",
":",
"digit",
"[",
"0",
"]",
"=",
"false",
";",
"digit",
"[",
"1",
"]",
"=",
"false",
";",
"digit",
"[",
"2",
"]",
"=",
"true",
";",
"digit",
"[",
"3",
"]",
"=",
"false",
";",
"break",
";",
"case",
"'3'",
":",
"digit",
"[",
"0",
"]",
"=",
"false",
";",
"digit",
"[",
"1",
"]",
"=",
"false",
";",
"digit",
"[",
"2",
"]",
"=",
"true",
";",
"digit",
"[",
"3",
"]",
"=",
"true",
";",
"break",
";",
"case",
"'4'",
":",
"digit",
"[",
"0",
"]",
"=",
"false",
";",
"digit",
"[",
"1",
"]",
"=",
"true",
";",
"digit",
"[",
"2",
"]",
"=",
"false",
";",
"digit",
"[",
"3",
"]",
"=",
"false",
";",
"break",
";",
"case",
"'5'",
":",
"digit",
"[",
"0",
"]",
"=",
"false",
";",
"digit",
"[",
"1",
"]",
"=",
"true",
";",
"digit",
"[",
"2",
"]",
"=",
"false",
";",
"digit",
"[",
"3",
"]",
"=",
"true",
";",
"break",
";",
"case",
"'6'",
":",
"digit",
"[",
"0",
"]",
"=",
"false",
";",
"digit",
"[",
"1",
"]",
"=",
"true",
";",
"digit",
"[",
"2",
"]",
"=",
"true",
";",
"digit",
"[",
"3",
"]",
"=",
"false",
";",
"break",
";",
"case",
"'7'",
":",
"digit",
"[",
"0",
"]",
"=",
"false",
";",
"digit",
"[",
"1",
"]",
"=",
"true",
";",
"digit",
"[",
"2",
"]",
"=",
"true",
";",
"digit",
"[",
"3",
"]",
"=",
"true",
";",
"break",
";",
"case",
"'8'",
":",
"digit",
"[",
"0",
"]",
"=",
"true",
";",
"digit",
"[",
"1",
"]",
"=",
"false",
";",
"digit",
"[",
"2",
"]",
"=",
"false",
";",
"digit",
"[",
"3",
"]",
"=",
"false",
";",
"break",
";",
"case",
"'9'",
":",
"digit",
"[",
"0",
"]",
"=",
"true",
";",
"digit",
"[",
"1",
"]",
"=",
"false",
";",
"digit",
"[",
"2",
"]",
"=",
"false",
";",
"digit",
"[",
"3",
"]",
"=",
"true",
";",
"break",
";",
"default",
":",
"continue",
";",
"}",
"bin",
"=",
"binadd",
"(",
"binten",
"(",
"bin",
")",
",",
"digit",
")",
";",
"}",
"return",
"removezeros",
"(",
"bin",
")",
";",
"}"
]
| Computes a binary array out of a decimal input string | [
"Computes",
"a",
"binary",
"array",
"out",
"of",
"a",
"decimal",
"input",
"string"
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L15-L37 |
45,258 | sembaye/numberconverter | index.js | bininputtobin | function bininputtobin(bininput){
var len = bininput.length;
if(len == 0){return filledarray(false, 1);}
var bin = new Array(len);
var j = 0;
for (var i = 0; i < len; i++){
switch (bininput[i]){
case '0': bin[j++] = false; break;
case '1': bin[j++] = true; break;
default: break;
}
}
return removezeros(bin.slice(0, j));
} | javascript | function bininputtobin(bininput){
var len = bininput.length;
if(len == 0){return filledarray(false, 1);}
var bin = new Array(len);
var j = 0;
for (var i = 0; i < len; i++){
switch (bininput[i]){
case '0': bin[j++] = false; break;
case '1': bin[j++] = true; break;
default: break;
}
}
return removezeros(bin.slice(0, j));
} | [
"function",
"bininputtobin",
"(",
"bininput",
")",
"{",
"var",
"len",
"=",
"bininput",
".",
"length",
";",
"if",
"(",
"len",
"==",
"0",
")",
"{",
"return",
"filledarray",
"(",
"false",
",",
"1",
")",
";",
"}",
"var",
"bin",
"=",
"new",
"Array",
"(",
"len",
")",
";",
"var",
"j",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"switch",
"(",
"bininput",
"[",
"i",
"]",
")",
"{",
"case",
"'0'",
":",
"bin",
"[",
"j",
"++",
"]",
"=",
"false",
";",
"break",
";",
"case",
"'1'",
":",
"bin",
"[",
"j",
"++",
"]",
"=",
"true",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"}",
"return",
"removezeros",
"(",
"bin",
".",
"slice",
"(",
"0",
",",
"j",
")",
")",
";",
"}"
]
| Computes a binary array out of a binary input string | [
"Computes",
"a",
"binary",
"array",
"out",
"of",
"a",
"binary",
"input",
"string"
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L70-L83 |
45,259 | sembaye/numberconverter | index.js | octinputtobin | function octinputtobin(octinput){
var len = octinput.length;
if(len == 0){return filledarray(false, 1);}
var bin = new Array(len * 3);
var j = 0;
for (var i = 0; i < len; i++){
switch (octinput[i]){
case '0': bin[j+0] = false; bin[j+1] = false; bin[j+2] = false; j+=3; break;
case '1': bin[j+0] = false; bin[j+1] = false; bin[j+2] = true; j+=3; break;
case '2': bin[j+0] = false; bin[j+1] = true; bin[j+2] = false; j+=3; break;
case '3': bin[j+0] = false; bin[j+1] = true; bin[j+2] = true; j+=3; break;
case '4': bin[j+0] = true; bin[j+1] = false; bin[j+2] = false; j+=3; break;
case '5': bin[j+0] = true; bin[j+1] = false; bin[j+2] = true; j+=3; break;
case '6': bin[j+0] = true; bin[j+1] = true; bin[j+2] = false; j+=3; break;
case '7': bin[j+0] = true; bin[j+1] = true; bin[j+2] = true; j+=3; break;
default: break;
}
}
return removezeros(bin.slice(0, j));
} | javascript | function octinputtobin(octinput){
var len = octinput.length;
if(len == 0){return filledarray(false, 1);}
var bin = new Array(len * 3);
var j = 0;
for (var i = 0; i < len; i++){
switch (octinput[i]){
case '0': bin[j+0] = false; bin[j+1] = false; bin[j+2] = false; j+=3; break;
case '1': bin[j+0] = false; bin[j+1] = false; bin[j+2] = true; j+=3; break;
case '2': bin[j+0] = false; bin[j+1] = true; bin[j+2] = false; j+=3; break;
case '3': bin[j+0] = false; bin[j+1] = true; bin[j+2] = true; j+=3; break;
case '4': bin[j+0] = true; bin[j+1] = false; bin[j+2] = false; j+=3; break;
case '5': bin[j+0] = true; bin[j+1] = false; bin[j+2] = true; j+=3; break;
case '6': bin[j+0] = true; bin[j+1] = true; bin[j+2] = false; j+=3; break;
case '7': bin[j+0] = true; bin[j+1] = true; bin[j+2] = true; j+=3; break;
default: break;
}
}
return removezeros(bin.slice(0, j));
} | [
"function",
"octinputtobin",
"(",
"octinput",
")",
"{",
"var",
"len",
"=",
"octinput",
".",
"length",
";",
"if",
"(",
"len",
"==",
"0",
")",
"{",
"return",
"filledarray",
"(",
"false",
",",
"1",
")",
";",
"}",
"var",
"bin",
"=",
"new",
"Array",
"(",
"len",
"*",
"3",
")",
";",
"var",
"j",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"switch",
"(",
"octinput",
"[",
"i",
"]",
")",
"{",
"case",
"'0'",
":",
"bin",
"[",
"j",
"+",
"0",
"]",
"=",
"false",
";",
"bin",
"[",
"j",
"+",
"1",
"]",
"=",
"false",
";",
"bin",
"[",
"j",
"+",
"2",
"]",
"=",
"false",
";",
"j",
"+=",
"3",
";",
"break",
";",
"case",
"'1'",
":",
"bin",
"[",
"j",
"+",
"0",
"]",
"=",
"false",
";",
"bin",
"[",
"j",
"+",
"1",
"]",
"=",
"false",
";",
"bin",
"[",
"j",
"+",
"2",
"]",
"=",
"true",
";",
"j",
"+=",
"3",
";",
"break",
";",
"case",
"'2'",
":",
"bin",
"[",
"j",
"+",
"0",
"]",
"=",
"false",
";",
"bin",
"[",
"j",
"+",
"1",
"]",
"=",
"true",
";",
"bin",
"[",
"j",
"+",
"2",
"]",
"=",
"false",
";",
"j",
"+=",
"3",
";",
"break",
";",
"case",
"'3'",
":",
"bin",
"[",
"j",
"+",
"0",
"]",
"=",
"false",
";",
"bin",
"[",
"j",
"+",
"1",
"]",
"=",
"true",
";",
"bin",
"[",
"j",
"+",
"2",
"]",
"=",
"true",
";",
"j",
"+=",
"3",
";",
"break",
";",
"case",
"'4'",
":",
"bin",
"[",
"j",
"+",
"0",
"]",
"=",
"true",
";",
"bin",
"[",
"j",
"+",
"1",
"]",
"=",
"false",
";",
"bin",
"[",
"j",
"+",
"2",
"]",
"=",
"false",
";",
"j",
"+=",
"3",
";",
"break",
";",
"case",
"'5'",
":",
"bin",
"[",
"j",
"+",
"0",
"]",
"=",
"true",
";",
"bin",
"[",
"j",
"+",
"1",
"]",
"=",
"false",
";",
"bin",
"[",
"j",
"+",
"2",
"]",
"=",
"true",
";",
"j",
"+=",
"3",
";",
"break",
";",
"case",
"'6'",
":",
"bin",
"[",
"j",
"+",
"0",
"]",
"=",
"true",
";",
"bin",
"[",
"j",
"+",
"1",
"]",
"=",
"true",
";",
"bin",
"[",
"j",
"+",
"2",
"]",
"=",
"false",
";",
"j",
"+=",
"3",
";",
"break",
";",
"case",
"'7'",
":",
"bin",
"[",
"j",
"+",
"0",
"]",
"=",
"true",
";",
"bin",
"[",
"j",
"+",
"1",
"]",
"=",
"true",
";",
"bin",
"[",
"j",
"+",
"2",
"]",
"=",
"true",
";",
"j",
"+=",
"3",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"}",
"return",
"removezeros",
"(",
"bin",
".",
"slice",
"(",
"0",
",",
"j",
")",
")",
";",
"}"
]
| Computes a binary array out of an octal input string | [
"Computes",
"a",
"binary",
"array",
"out",
"of",
"an",
"octal",
"input",
"string"
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L86-L105 |
45,260 | sembaye/numberconverter | index.js | bintodecoutput | function bintodecoutput(bin){
var len = bin.length;
var decoutput = String();
var work = new Array(len);
var outputlen = 0;
for(var i=0; i<len; i++){work[i] = bin[i];}
while(len){
// as long as a remaining value exists
var lead = false;
var bit0;
var bit1;
var bit2;
var bit3;
var value;
var i = 0;
while(i < len-3){
// walk through the remaining value
bit0 = work[i+3];
bit1 = work[i+2];
bit2 = work[i+1];
bit3 = work[i+0];
value = (bit3<<3) | (bit2<<2) | (bit1<<1) | (bit0<<0);
if(value >= 10){
// For nibbles greaterequal than 10, adjust the bits accordingly.
work[i+0] = true; work[i+1] = bit2 && bit1; work[i+2] = !bit1;
}else{
work[i+0] = lead;
if(lead){
// When the previous nibble was 8 or 9, adjust the bits accordingly
work[i+1] = !bit1; work[i+2] = !bit1;
lead = bit1;
}else{
// otherwise, just leave the bits as they are.
if(value >= 8){lead = true;}
}
}
i++;
}
// extract the decimal value of the remaining bits
if(len==1){
bit0 = work[0];
bit1 = false;
bit2 = false;
}else if(len==2){
bit0 = work[1];
bit1 = work[0];
bit2 = false;
}else{
bit0 = work[i + 2];
bit1 = work[i + 1];
bit2 = work[i + 0];
}
bit3 = lead;
var value = (bit3<<3) | (bit2<<2) | (bit1<<1) | (bit0<<0);
if(!(outputlen%3)){decoutput = ' ' + decoutput;}
decoutput = value + decoutput;
outputlen++;
len = i;
}
// Remove zeros
var i = 0;
outputlen = decoutput.length;
while((i < outputlen) && ((decoutput[i] == '0') || (decoutput[i] == ' '))){i++;}
if(i == outputlen){
return "0";
}else{
return decoutput.slice(i);
}
} | javascript | function bintodecoutput(bin){
var len = bin.length;
var decoutput = String();
var work = new Array(len);
var outputlen = 0;
for(var i=0; i<len; i++){work[i] = bin[i];}
while(len){
// as long as a remaining value exists
var lead = false;
var bit0;
var bit1;
var bit2;
var bit3;
var value;
var i = 0;
while(i < len-3){
// walk through the remaining value
bit0 = work[i+3];
bit1 = work[i+2];
bit2 = work[i+1];
bit3 = work[i+0];
value = (bit3<<3) | (bit2<<2) | (bit1<<1) | (bit0<<0);
if(value >= 10){
// For nibbles greaterequal than 10, adjust the bits accordingly.
work[i+0] = true; work[i+1] = bit2 && bit1; work[i+2] = !bit1;
}else{
work[i+0] = lead;
if(lead){
// When the previous nibble was 8 or 9, adjust the bits accordingly
work[i+1] = !bit1; work[i+2] = !bit1;
lead = bit1;
}else{
// otherwise, just leave the bits as they are.
if(value >= 8){lead = true;}
}
}
i++;
}
// extract the decimal value of the remaining bits
if(len==1){
bit0 = work[0];
bit1 = false;
bit2 = false;
}else if(len==2){
bit0 = work[1];
bit1 = work[0];
bit2 = false;
}else{
bit0 = work[i + 2];
bit1 = work[i + 1];
bit2 = work[i + 0];
}
bit3 = lead;
var value = (bit3<<3) | (bit2<<2) | (bit1<<1) | (bit0<<0);
if(!(outputlen%3)){decoutput = ' ' + decoutput;}
decoutput = value + decoutput;
outputlen++;
len = i;
}
// Remove zeros
var i = 0;
outputlen = decoutput.length;
while((i < outputlen) && ((decoutput[i] == '0') || (decoutput[i] == ' '))){i++;}
if(i == outputlen){
return "0";
}else{
return decoutput.slice(i);
}
} | [
"function",
"bintodecoutput",
"(",
"bin",
")",
"{",
"var",
"len",
"=",
"bin",
".",
"length",
";",
"var",
"decoutput",
"=",
"String",
"(",
")",
";",
"var",
"work",
"=",
"new",
"Array",
"(",
"len",
")",
";",
"var",
"outputlen",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"work",
"[",
"i",
"]",
"=",
"bin",
"[",
"i",
"]",
";",
"}",
"while",
"(",
"len",
")",
"{",
"// as long as a remaining value exists",
"var",
"lead",
"=",
"false",
";",
"var",
"bit0",
";",
"var",
"bit1",
";",
"var",
"bit2",
";",
"var",
"bit3",
";",
"var",
"value",
";",
"var",
"i",
"=",
"0",
";",
"while",
"(",
"i",
"<",
"len",
"-",
"3",
")",
"{",
"// walk through the remaining value",
"bit0",
"=",
"work",
"[",
"i",
"+",
"3",
"]",
";",
"bit1",
"=",
"work",
"[",
"i",
"+",
"2",
"]",
";",
"bit2",
"=",
"work",
"[",
"i",
"+",
"1",
"]",
";",
"bit3",
"=",
"work",
"[",
"i",
"+",
"0",
"]",
";",
"value",
"=",
"(",
"bit3",
"<<",
"3",
")",
"|",
"(",
"bit2",
"<<",
"2",
")",
"|",
"(",
"bit1",
"<<",
"1",
")",
"|",
"(",
"bit0",
"<<",
"0",
")",
";",
"if",
"(",
"value",
">=",
"10",
")",
"{",
"// For nibbles greaterequal than 10, adjust the bits accordingly.",
"work",
"[",
"i",
"+",
"0",
"]",
"=",
"true",
";",
"work",
"[",
"i",
"+",
"1",
"]",
"=",
"bit2",
"&&",
"bit1",
";",
"work",
"[",
"i",
"+",
"2",
"]",
"=",
"!",
"bit1",
";",
"}",
"else",
"{",
"work",
"[",
"i",
"+",
"0",
"]",
"=",
"lead",
";",
"if",
"(",
"lead",
")",
"{",
"// When the previous nibble was 8 or 9, adjust the bits accordingly",
"work",
"[",
"i",
"+",
"1",
"]",
"=",
"!",
"bit1",
";",
"work",
"[",
"i",
"+",
"2",
"]",
"=",
"!",
"bit1",
";",
"lead",
"=",
"bit1",
";",
"}",
"else",
"{",
"// otherwise, just leave the bits as they are.",
"if",
"(",
"value",
">=",
"8",
")",
"{",
"lead",
"=",
"true",
";",
"}",
"}",
"}",
"i",
"++",
";",
"}",
"// extract the decimal value of the remaining bits",
"if",
"(",
"len",
"==",
"1",
")",
"{",
"bit0",
"=",
"work",
"[",
"0",
"]",
";",
"bit1",
"=",
"false",
";",
"bit2",
"=",
"false",
";",
"}",
"else",
"if",
"(",
"len",
"==",
"2",
")",
"{",
"bit0",
"=",
"work",
"[",
"1",
"]",
";",
"bit1",
"=",
"work",
"[",
"0",
"]",
";",
"bit2",
"=",
"false",
";",
"}",
"else",
"{",
"bit0",
"=",
"work",
"[",
"i",
"+",
"2",
"]",
";",
"bit1",
"=",
"work",
"[",
"i",
"+",
"1",
"]",
";",
"bit2",
"=",
"work",
"[",
"i",
"+",
"0",
"]",
";",
"}",
"bit3",
"=",
"lead",
";",
"var",
"value",
"=",
"(",
"bit3",
"<<",
"3",
")",
"|",
"(",
"bit2",
"<<",
"2",
")",
"|",
"(",
"bit1",
"<<",
"1",
")",
"|",
"(",
"bit0",
"<<",
"0",
")",
";",
"if",
"(",
"!",
"(",
"outputlen",
"%",
"3",
")",
")",
"{",
"decoutput",
"=",
"' '",
"+",
"decoutput",
";",
"}",
"decoutput",
"=",
"value",
"+",
"decoutput",
";",
"outputlen",
"++",
";",
"len",
"=",
"i",
";",
"}",
"// Remove zeros",
"var",
"i",
"=",
"0",
";",
"outputlen",
"=",
"decoutput",
".",
"length",
";",
"while",
"(",
"(",
"i",
"<",
"outputlen",
")",
"&&",
"(",
"(",
"decoutput",
"[",
"i",
"]",
"==",
"'0'",
")",
"||",
"(",
"decoutput",
"[",
"i",
"]",
"==",
"' '",
")",
")",
")",
"{",
"i",
"++",
";",
"}",
"if",
"(",
"i",
"==",
"outputlen",
")",
"{",
"return",
"\"0\"",
";",
"}",
"else",
"{",
"return",
"decoutput",
".",
"slice",
"(",
"i",
")",
";",
"}",
"}"
]
| Formats the given binary array to a decimal output string | [
"Formats",
"the",
"given",
"binary",
"array",
"to",
"a",
"decimal",
"output",
"string"
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L108-L176 |
45,261 | sembaye/numberconverter | index.js | bintohexoutput | function bintohexoutput(bin){
var len = bin.length;
var hexoutput = String();
for(var i=0; i<len; i+=4){
if((i > 0) && !(i%8)){hexoutput = " " + hexoutput;}
var value = 0;
if(bin[len - 1 - i - 0]){value+=1;}
if(bin[len - 1 - i - 1]){value+=2;}
if(bin[len - 1 - i - 2]){value+=4;}
if(bin[len - 1 - i - 3]){value+=8;}
switch(value){
case 0: hexoutput = "0" + hexoutput; break;
case 1: hexoutput = "1" + hexoutput; break;
case 2: hexoutput = "2" + hexoutput; break;
case 3: hexoutput = "3" + hexoutput; break;
case 4: hexoutput = "4" + hexoutput; break;
case 5: hexoutput = "5" + hexoutput; break;
case 6: hexoutput = "6" + hexoutput; break;
case 7: hexoutput = "7" + hexoutput; break;
case 8: hexoutput = "8" + hexoutput; break;
case 9: hexoutput = "9" + hexoutput; break;
case 10: hexoutput = "a" + hexoutput; break;
case 11: hexoutput = "b" + hexoutput; break;
case 12: hexoutput = "c" + hexoutput; break;
case 13: hexoutput = "d" + hexoutput; break;
case 14: hexoutput = "e" + hexoutput; break;
case 15: hexoutput = "f" + hexoutput; break;
default: break;
}
}
// todo: make faster
return hexoutput;
} | javascript | function bintohexoutput(bin){
var len = bin.length;
var hexoutput = String();
for(var i=0; i<len; i+=4){
if((i > 0) && !(i%8)){hexoutput = " " + hexoutput;}
var value = 0;
if(bin[len - 1 - i - 0]){value+=1;}
if(bin[len - 1 - i - 1]){value+=2;}
if(bin[len - 1 - i - 2]){value+=4;}
if(bin[len - 1 - i - 3]){value+=8;}
switch(value){
case 0: hexoutput = "0" + hexoutput; break;
case 1: hexoutput = "1" + hexoutput; break;
case 2: hexoutput = "2" + hexoutput; break;
case 3: hexoutput = "3" + hexoutput; break;
case 4: hexoutput = "4" + hexoutput; break;
case 5: hexoutput = "5" + hexoutput; break;
case 6: hexoutput = "6" + hexoutput; break;
case 7: hexoutput = "7" + hexoutput; break;
case 8: hexoutput = "8" + hexoutput; break;
case 9: hexoutput = "9" + hexoutput; break;
case 10: hexoutput = "a" + hexoutput; break;
case 11: hexoutput = "b" + hexoutput; break;
case 12: hexoutput = "c" + hexoutput; break;
case 13: hexoutput = "d" + hexoutput; break;
case 14: hexoutput = "e" + hexoutput; break;
case 15: hexoutput = "f" + hexoutput; break;
default: break;
}
}
// todo: make faster
return hexoutput;
} | [
"function",
"bintohexoutput",
"(",
"bin",
")",
"{",
"var",
"len",
"=",
"bin",
".",
"length",
";",
"var",
"hexoutput",
"=",
"String",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"4",
")",
"{",
"if",
"(",
"(",
"i",
">",
"0",
")",
"&&",
"!",
"(",
"i",
"%",
"8",
")",
")",
"{",
"hexoutput",
"=",
"\" \"",
"+",
"hexoutput",
";",
"}",
"var",
"value",
"=",
"0",
";",
"if",
"(",
"bin",
"[",
"len",
"-",
"1",
"-",
"i",
"-",
"0",
"]",
")",
"{",
"value",
"+=",
"1",
";",
"}",
"if",
"(",
"bin",
"[",
"len",
"-",
"1",
"-",
"i",
"-",
"1",
"]",
")",
"{",
"value",
"+=",
"2",
";",
"}",
"if",
"(",
"bin",
"[",
"len",
"-",
"1",
"-",
"i",
"-",
"2",
"]",
")",
"{",
"value",
"+=",
"4",
";",
"}",
"if",
"(",
"bin",
"[",
"len",
"-",
"1",
"-",
"i",
"-",
"3",
"]",
")",
"{",
"value",
"+=",
"8",
";",
"}",
"switch",
"(",
"value",
")",
"{",
"case",
"0",
":",
"hexoutput",
"=",
"\"0\"",
"+",
"hexoutput",
";",
"break",
";",
"case",
"1",
":",
"hexoutput",
"=",
"\"1\"",
"+",
"hexoutput",
";",
"break",
";",
"case",
"2",
":",
"hexoutput",
"=",
"\"2\"",
"+",
"hexoutput",
";",
"break",
";",
"case",
"3",
":",
"hexoutput",
"=",
"\"3\"",
"+",
"hexoutput",
";",
"break",
";",
"case",
"4",
":",
"hexoutput",
"=",
"\"4\"",
"+",
"hexoutput",
";",
"break",
";",
"case",
"5",
":",
"hexoutput",
"=",
"\"5\"",
"+",
"hexoutput",
";",
"break",
";",
"case",
"6",
":",
"hexoutput",
"=",
"\"6\"",
"+",
"hexoutput",
";",
"break",
";",
"case",
"7",
":",
"hexoutput",
"=",
"\"7\"",
"+",
"hexoutput",
";",
"break",
";",
"case",
"8",
":",
"hexoutput",
"=",
"\"8\"",
"+",
"hexoutput",
";",
"break",
";",
"case",
"9",
":",
"hexoutput",
"=",
"\"9\"",
"+",
"hexoutput",
";",
"break",
";",
"case",
"10",
":",
"hexoutput",
"=",
"\"a\"",
"+",
"hexoutput",
";",
"break",
";",
"case",
"11",
":",
"hexoutput",
"=",
"\"b\"",
"+",
"hexoutput",
";",
"break",
";",
"case",
"12",
":",
"hexoutput",
"=",
"\"c\"",
"+",
"hexoutput",
";",
"break",
";",
"case",
"13",
":",
"hexoutput",
"=",
"\"d\"",
"+",
"hexoutput",
";",
"break",
";",
"case",
"14",
":",
"hexoutput",
"=",
"\"e\"",
"+",
"hexoutput",
";",
"break",
";",
"case",
"15",
":",
"hexoutput",
"=",
"\"f\"",
"+",
"hexoutput",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"}",
"// todo: make faster",
"return",
"hexoutput",
";",
"}"
]
| Formats the given binary array to a hexadecimal output string | [
"Formats",
"the",
"given",
"binary",
"array",
"to",
"a",
"hexadecimal",
"output",
"string"
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L179-L211 |
45,262 | sembaye/numberconverter | index.js | bintobinoutput | function bintobinoutput(bin){
var len = bin.length;
var binoutput = String();
for(var i=0; i<len; i++){
if((i > 0) && !(i%8)){binoutput = " " + binoutput;}
if(bin[len - 1 - i]){binoutput = "1" + binoutput;}else{binoutput = "0" + binoutput;}
}
// todo: make faster
return binoutput;
} | javascript | function bintobinoutput(bin){
var len = bin.length;
var binoutput = String();
for(var i=0; i<len; i++){
if((i > 0) && !(i%8)){binoutput = " " + binoutput;}
if(bin[len - 1 - i]){binoutput = "1" + binoutput;}else{binoutput = "0" + binoutput;}
}
// todo: make faster
return binoutput;
} | [
"function",
"bintobinoutput",
"(",
"bin",
")",
"{",
"var",
"len",
"=",
"bin",
".",
"length",
";",
"var",
"binoutput",
"=",
"String",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"(",
"i",
">",
"0",
")",
"&&",
"!",
"(",
"i",
"%",
"8",
")",
")",
"{",
"binoutput",
"=",
"\" \"",
"+",
"binoutput",
";",
"}",
"if",
"(",
"bin",
"[",
"len",
"-",
"1",
"-",
"i",
"]",
")",
"{",
"binoutput",
"=",
"\"1\"",
"+",
"binoutput",
";",
"}",
"else",
"{",
"binoutput",
"=",
"\"0\"",
"+",
"binoutput",
";",
"}",
"}",
"// todo: make faster",
"return",
"binoutput",
";",
"}"
]
| Formats the given binary array to a binary output string | [
"Formats",
"the",
"given",
"binary",
"array",
"to",
"a",
"binary",
"output",
"string"
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L214-L223 |
45,263 | sembaye/numberconverter | index.js | bintooctoutput | function bintooctoutput(bin){
var len = bin.length;
var octoutput = String();
for(var i=0; i<len; i+=3){
if((i > 0) && !(i%24)){octoutput = " " + octoutput;}
var value = 0;
if(bin[len - 1 - i - 0]){value+=1;}
if(bin[len - 1 - i - 1]){value+=2;}
if(bin[len - 1 - i - 2]){value+=4;}
switch(value){
case 0: octoutput = "0" + octoutput; break;
case 1: octoutput = "1" + octoutput; break;
case 2: octoutput = "2" + octoutput; break;
case 3: octoutput = "3" + octoutput; break;
case 4: octoutput = "4" + octoutput; break;
case 5: octoutput = "5" + octoutput; break;
case 6: octoutput = "6" + octoutput; break;
case 7: octoutput = "7" + octoutput; break;
default: break;
}
}
// todo: make faster
return octoutput;
} | javascript | function bintooctoutput(bin){
var len = bin.length;
var octoutput = String();
for(var i=0; i<len; i+=3){
if((i > 0) && !(i%24)){octoutput = " " + octoutput;}
var value = 0;
if(bin[len - 1 - i - 0]){value+=1;}
if(bin[len - 1 - i - 1]){value+=2;}
if(bin[len - 1 - i - 2]){value+=4;}
switch(value){
case 0: octoutput = "0" + octoutput; break;
case 1: octoutput = "1" + octoutput; break;
case 2: octoutput = "2" + octoutput; break;
case 3: octoutput = "3" + octoutput; break;
case 4: octoutput = "4" + octoutput; break;
case 5: octoutput = "5" + octoutput; break;
case 6: octoutput = "6" + octoutput; break;
case 7: octoutput = "7" + octoutput; break;
default: break;
}
}
// todo: make faster
return octoutput;
} | [
"function",
"bintooctoutput",
"(",
"bin",
")",
"{",
"var",
"len",
"=",
"bin",
".",
"length",
";",
"var",
"octoutput",
"=",
"String",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"3",
")",
"{",
"if",
"(",
"(",
"i",
">",
"0",
")",
"&&",
"!",
"(",
"i",
"%",
"24",
")",
")",
"{",
"octoutput",
"=",
"\" \"",
"+",
"octoutput",
";",
"}",
"var",
"value",
"=",
"0",
";",
"if",
"(",
"bin",
"[",
"len",
"-",
"1",
"-",
"i",
"-",
"0",
"]",
")",
"{",
"value",
"+=",
"1",
";",
"}",
"if",
"(",
"bin",
"[",
"len",
"-",
"1",
"-",
"i",
"-",
"1",
"]",
")",
"{",
"value",
"+=",
"2",
";",
"}",
"if",
"(",
"bin",
"[",
"len",
"-",
"1",
"-",
"i",
"-",
"2",
"]",
")",
"{",
"value",
"+=",
"4",
";",
"}",
"switch",
"(",
"value",
")",
"{",
"case",
"0",
":",
"octoutput",
"=",
"\"0\"",
"+",
"octoutput",
";",
"break",
";",
"case",
"1",
":",
"octoutput",
"=",
"\"1\"",
"+",
"octoutput",
";",
"break",
";",
"case",
"2",
":",
"octoutput",
"=",
"\"2\"",
"+",
"octoutput",
";",
"break",
";",
"case",
"3",
":",
"octoutput",
"=",
"\"3\"",
"+",
"octoutput",
";",
"break",
";",
"case",
"4",
":",
"octoutput",
"=",
"\"4\"",
"+",
"octoutput",
";",
"break",
";",
"case",
"5",
":",
"octoutput",
"=",
"\"5\"",
"+",
"octoutput",
";",
"break",
";",
"case",
"6",
":",
"octoutput",
"=",
"\"6\"",
"+",
"octoutput",
";",
"break",
";",
"case",
"7",
":",
"octoutput",
"=",
"\"7\"",
"+",
"octoutput",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"}",
"// todo: make faster",
"return",
"octoutput",
";",
"}"
]
| Formats the given binary array to a octal output string | [
"Formats",
"the",
"given",
"binary",
"array",
"to",
"a",
"octal",
"output",
"string"
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L226-L249 |
45,264 | sembaye/numberconverter | index.js | filledarray | function filledarray(value, size){
var a = new Array(size);
for(var i=0; i<size; i++){a[i] = value;}
return a;
} | javascript | function filledarray(value, size){
var a = new Array(size);
for(var i=0; i<size; i++){a[i] = value;}
return a;
} | [
"function",
"filledarray",
"(",
"value",
",",
"size",
")",
"{",
"var",
"a",
"=",
"new",
"Array",
"(",
"size",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"size",
";",
"i",
"++",
")",
"{",
"a",
"[",
"i",
"]",
"=",
"value",
";",
"}",
"return",
"a",
";",
"}"
]
| Returns an array of a given size filled with the given value. | [
"Returns",
"an",
"array",
"of",
"a",
"given",
"size",
"filled",
"with",
"the",
"given",
"value",
"."
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L252-L256 |
45,265 | sembaye/numberconverter | index.js | binadd | function binadd(bin1, bin2){
var i1 = bin1.length;
var i2 = bin2.length;
var i3 = (i1 > i2) ? (i1 + 1) : (i2 + 1);
var result = new Array(i3);
var c = 0;
// Add the two arrays as long as there exist elements in the arrays
while((i1 > 0) && (i2 > 0)){
i1--;
i2--;
i3--;
if(bin1[i1]){c++;}
if(bin2[i2]){c++;}
result[i3] = (c%2) ? true : false;
c >>= 1;
}
// copy the remaining elements
if(i1){
for(var i=0; i<i1; i++){result[i+1] = bin1[i];}
}else{
for(var i=0; i<i2; i++){result[i+1] = bin2[i];}
}
// add the remaining carry
var carry = c ? true : false;
while(c && (i3 > 1)){
i3--;
result[i3] = !result[i3];
c = !result[i3];
}
// Return result with carry if necessary
if (c==1){
result[0] = true;
return result;
}else{
return result.slice(1);
}
} | javascript | function binadd(bin1, bin2){
var i1 = bin1.length;
var i2 = bin2.length;
var i3 = (i1 > i2) ? (i1 + 1) : (i2 + 1);
var result = new Array(i3);
var c = 0;
// Add the two arrays as long as there exist elements in the arrays
while((i1 > 0) && (i2 > 0)){
i1--;
i2--;
i3--;
if(bin1[i1]){c++;}
if(bin2[i2]){c++;}
result[i3] = (c%2) ? true : false;
c >>= 1;
}
// copy the remaining elements
if(i1){
for(var i=0; i<i1; i++){result[i+1] = bin1[i];}
}else{
for(var i=0; i<i2; i++){result[i+1] = bin2[i];}
}
// add the remaining carry
var carry = c ? true : false;
while(c && (i3 > 1)){
i3--;
result[i3] = !result[i3];
c = !result[i3];
}
// Return result with carry if necessary
if (c==1){
result[0] = true;
return result;
}else{
return result.slice(1);
}
} | [
"function",
"binadd",
"(",
"bin1",
",",
"bin2",
")",
"{",
"var",
"i1",
"=",
"bin1",
".",
"length",
";",
"var",
"i2",
"=",
"bin2",
".",
"length",
";",
"var",
"i3",
"=",
"(",
"i1",
">",
"i2",
")",
"?",
"(",
"i1",
"+",
"1",
")",
":",
"(",
"i2",
"+",
"1",
")",
";",
"var",
"result",
"=",
"new",
"Array",
"(",
"i3",
")",
";",
"var",
"c",
"=",
"0",
";",
"// Add the two arrays as long as there exist elements in the arrays",
"while",
"(",
"(",
"i1",
">",
"0",
")",
"&&",
"(",
"i2",
">",
"0",
")",
")",
"{",
"i1",
"--",
";",
"i2",
"--",
";",
"i3",
"--",
";",
"if",
"(",
"bin1",
"[",
"i1",
"]",
")",
"{",
"c",
"++",
";",
"}",
"if",
"(",
"bin2",
"[",
"i2",
"]",
")",
"{",
"c",
"++",
";",
"}",
"result",
"[",
"i3",
"]",
"=",
"(",
"c",
"%",
"2",
")",
"?",
"true",
":",
"false",
";",
"c",
">>=",
"1",
";",
"}",
"// copy the remaining elements",
"if",
"(",
"i1",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"i1",
";",
"i",
"++",
")",
"{",
"result",
"[",
"i",
"+",
"1",
"]",
"=",
"bin1",
"[",
"i",
"]",
";",
"}",
"}",
"else",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"i2",
";",
"i",
"++",
")",
"{",
"result",
"[",
"i",
"+",
"1",
"]",
"=",
"bin2",
"[",
"i",
"]",
";",
"}",
"}",
"// add the remaining carry",
"var",
"carry",
"=",
"c",
"?",
"true",
":",
"false",
";",
"while",
"(",
"c",
"&&",
"(",
"i3",
">",
"1",
")",
")",
"{",
"i3",
"--",
";",
"result",
"[",
"i3",
"]",
"=",
"!",
"result",
"[",
"i3",
"]",
";",
"c",
"=",
"!",
"result",
"[",
"i3",
"]",
";",
"}",
"// Return result with carry if necessary",
"if",
"(",
"c",
"==",
"1",
")",
"{",
"result",
"[",
"0",
"]",
"=",
"true",
";",
"return",
"result",
";",
"}",
"else",
"{",
"return",
"result",
".",
"slice",
"(",
"1",
")",
";",
"}",
"}"
]
| Addition of two binary arrays | [
"Addition",
"of",
"two",
"binary",
"arrays"
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L259-L295 |
45,266 | sembaye/numberconverter | index.js | binaddone | function binaddone(bin){
var len = bin.length;
var result = new Array(len + 1);
var c = true; // carry bit
var i = len; // i points at the bit in bin one after the untouched bit
while(c && (i > 0)){
i--;
c = bin[i];
result[i+1] = !c;
}
if(i){
// Return remaining untouched bin concatenated with the touched bits
return bin.slice(0, i).concat(result.slice(i+1));
}else{
if(c){
// Return full result with carry as prefix
result[0] = true;
return result;
}else{
// Return result without carry
return result.slice(1);
}
}
} | javascript | function binaddone(bin){
var len = bin.length;
var result = new Array(len + 1);
var c = true; // carry bit
var i = len; // i points at the bit in bin one after the untouched bit
while(c && (i > 0)){
i--;
c = bin[i];
result[i+1] = !c;
}
if(i){
// Return remaining untouched bin concatenated with the touched bits
return bin.slice(0, i).concat(result.slice(i+1));
}else{
if(c){
// Return full result with carry as prefix
result[0] = true;
return result;
}else{
// Return result without carry
return result.slice(1);
}
}
} | [
"function",
"binaddone",
"(",
"bin",
")",
"{",
"var",
"len",
"=",
"bin",
".",
"length",
";",
"var",
"result",
"=",
"new",
"Array",
"(",
"len",
"+",
"1",
")",
";",
"var",
"c",
"=",
"true",
";",
"// carry bit",
"var",
"i",
"=",
"len",
";",
"// i points at the bit in bin one after the untouched bit",
"while",
"(",
"c",
"&&",
"(",
"i",
">",
"0",
")",
")",
"{",
"i",
"--",
";",
"c",
"=",
"bin",
"[",
"i",
"]",
";",
"result",
"[",
"i",
"+",
"1",
"]",
"=",
"!",
"c",
";",
"}",
"if",
"(",
"i",
")",
"{",
"// Return remaining untouched bin concatenated with the touched bits",
"return",
"bin",
".",
"slice",
"(",
"0",
",",
"i",
")",
".",
"concat",
"(",
"result",
".",
"slice",
"(",
"i",
"+",
"1",
")",
")",
";",
"}",
"else",
"{",
"if",
"(",
"c",
")",
"{",
"// Return full result with carry as prefix",
"result",
"[",
"0",
"]",
"=",
"true",
";",
"return",
"result",
";",
"}",
"else",
"{",
"// Return result without carry",
"return",
"result",
".",
"slice",
"(",
"1",
")",
";",
"}",
"}",
"}"
]
| Addition of 1 to a binary array | [
"Addition",
"of",
"1",
"to",
"a",
"binary",
"array"
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L298-L321 |
45,267 | sembaye/numberconverter | index.js | bintruncate | function bintruncate(bin, size){
var len = bin.length;
if(len < size){
return filledarray(false, size-len).concat(bin);
}else{
return bin.slice(len - size);
}
} | javascript | function bintruncate(bin, size){
var len = bin.length;
if(len < size){
return filledarray(false, size-len).concat(bin);
}else{
return bin.slice(len - size);
}
} | [
"function",
"bintruncate",
"(",
"bin",
",",
"size",
")",
"{",
"var",
"len",
"=",
"bin",
".",
"length",
";",
"if",
"(",
"len",
"<",
"size",
")",
"{",
"return",
"filledarray",
"(",
"false",
",",
"size",
"-",
"len",
")",
".",
"concat",
"(",
"bin",
")",
";",
"}",
"else",
"{",
"return",
"bin",
".",
"slice",
"(",
"len",
"-",
"size",
")",
";",
"}",
"}"
]
| Either truncates the binary array or fills the MSBs with 0 to fit the size. | [
"Either",
"truncates",
"the",
"binary",
"array",
"or",
"fills",
"the",
"MSBs",
"with",
"0",
"to",
"fit",
"the",
"size",
"."
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L353-L360 |
45,268 | sembaye/numberconverter | index.js | onescomplement | function onescomplement(bin){
var len = bin.length;
var onebin = new Array(len);
for (var i=0; i<len; i++){onebin[i] = !bin[i];}
return onebin;
} | javascript | function onescomplement(bin){
var len = bin.length;
var onebin = new Array(len);
for (var i=0; i<len; i++){onebin[i] = !bin[i];}
return onebin;
} | [
"function",
"onescomplement",
"(",
"bin",
")",
"{",
"var",
"len",
"=",
"bin",
".",
"length",
";",
"var",
"onebin",
"=",
"new",
"Array",
"(",
"len",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"onebin",
"[",
"i",
"]",
"=",
"!",
"bin",
"[",
"i",
"]",
";",
"}",
"return",
"onebin",
";",
"}"
]
| Computes the one's complement of the binary number | [
"Computes",
"the",
"one",
"s",
"complement",
"of",
"the",
"binary",
"number"
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L363-L368 |
45,269 | sembaye/numberconverter | index.js | updatedec | function updatedec(){
var dec = decinputfield;
if(decinputvalue != dec){
updateall(decinputtobin(dec));
clearallinputs();
decinputfield = dec;
decinputvalue = dec;
}
} | javascript | function updatedec(){
var dec = decinputfield;
if(decinputvalue != dec){
updateall(decinputtobin(dec));
clearallinputs();
decinputfield = dec;
decinputvalue = dec;
}
} | [
"function",
"updatedec",
"(",
")",
"{",
"var",
"dec",
"=",
"decinputfield",
";",
"if",
"(",
"decinputvalue",
"!=",
"dec",
")",
"{",
"updateall",
"(",
"decinputtobin",
"(",
"dec",
")",
")",
";",
"clearallinputs",
"(",
")",
";",
"decinputfield",
"=",
"dec",
";",
"decinputvalue",
"=",
"dec",
";",
"}",
"}"
]
| The decimal input field has been changed | [
"The",
"decimal",
"input",
"field",
"has",
"been",
"changed"
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L388-L396 |
45,270 | sembaye/numberconverter | index.js | updatehex | function updatehex(){
var hex = hexinputfield;
if(hexinputvalue != hex){
updateall(hexinputtobin(hex));
clearallinputs();
hexinputfield = hex;
hexinputvalue = hex;
}
} | javascript | function updatehex(){
var hex = hexinputfield;
if(hexinputvalue != hex){
updateall(hexinputtobin(hex));
clearallinputs();
hexinputfield = hex;
hexinputvalue = hex;
}
} | [
"function",
"updatehex",
"(",
")",
"{",
"var",
"hex",
"=",
"hexinputfield",
";",
"if",
"(",
"hexinputvalue",
"!=",
"hex",
")",
"{",
"updateall",
"(",
"hexinputtobin",
"(",
"hex",
")",
")",
";",
"clearallinputs",
"(",
")",
";",
"hexinputfield",
"=",
"hex",
";",
"hexinputvalue",
"=",
"hex",
";",
"}",
"}"
]
| The hexadecimal input field has been changed | [
"The",
"hexadecimal",
"input",
"field",
"has",
"been",
"changed"
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L399-L407 |
45,271 | sembaye/numberconverter | index.js | updatebin | function updatebin(){
var bin = bininputfield;
if(bininputvalue != bin){
updateall(bininputtobin(bin));
clearallinputs();
bininputfield = bin;
bininputvalue = bin;
}
} | javascript | function updatebin(){
var bin = bininputfield;
if(bininputvalue != bin){
updateall(bininputtobin(bin));
clearallinputs();
bininputfield = bin;
bininputvalue = bin;
}
} | [
"function",
"updatebin",
"(",
")",
"{",
"var",
"bin",
"=",
"bininputfield",
";",
"if",
"(",
"bininputvalue",
"!=",
"bin",
")",
"{",
"updateall",
"(",
"bininputtobin",
"(",
"bin",
")",
")",
";",
"clearallinputs",
"(",
")",
";",
"bininputfield",
"=",
"bin",
";",
"bininputvalue",
"=",
"bin",
";",
"}",
"}"
]
| The binary input field has been changed | [
"The",
"binary",
"input",
"field",
"has",
"been",
"changed"
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L410-L418 |
45,272 | sembaye/numberconverter | index.js | updateoct | function updateoct(){
var oct = octinputfield;
if(octinputvalue != oct){
updateall(octinputtobin(oct));
clearallinputs();
octinputfield = oct;
octinputvalue = oct;
}
} | javascript | function updateoct(){
var oct = octinputfield;
if(octinputvalue != oct){
updateall(octinputtobin(oct));
clearallinputs();
octinputfield = oct;
octinputvalue = oct;
}
} | [
"function",
"updateoct",
"(",
")",
"{",
"var",
"oct",
"=",
"octinputfield",
";",
"if",
"(",
"octinputvalue",
"!=",
"oct",
")",
"{",
"updateall",
"(",
"octinputtobin",
"(",
"oct",
")",
")",
";",
"clearallinputs",
"(",
")",
";",
"octinputfield",
"=",
"oct",
";",
"octinputvalue",
"=",
"oct",
";",
"}",
"}"
]
| The octal input field has been changed | [
"The",
"octal",
"input",
"field",
"has",
"been",
"changed"
]
| c3cd4c0c567e520354e0e4fb60a669fd5f07877a | https://github.com/sembaye/numberconverter/blob/c3cd4c0c567e520354e0e4fb60a669fd5f07877a/index.js#L421-L429 |
45,273 | ryb73/dealers-choice-meta | packages/front-end/src/components/dc-game-canvas/animation-throttler.js | AnimationThrottler | function AnimationThrottler(delay) {
if(!delay) delay = DELAY;
// Anim is considered active if it's running or queued
var currentDelay = 0;
// func: Function that takes no params and returns a promise
function requestAnim(func) {
var result = q.delay(currentDelay)
.thenResolve(func)
.then(start);
currentDelay += delay;
return result;
}
this.requestAnim = requestAnim;
function start(func) {
return func()
.catch(animFailed)
.tap(animFinished);
}
function animFailed(error) {
animFinished();
throw error;
}
function animFinished() {
currentDelay -= delay;
}
} | javascript | function AnimationThrottler(delay) {
if(!delay) delay = DELAY;
// Anim is considered active if it's running or queued
var currentDelay = 0;
// func: Function that takes no params and returns a promise
function requestAnim(func) {
var result = q.delay(currentDelay)
.thenResolve(func)
.then(start);
currentDelay += delay;
return result;
}
this.requestAnim = requestAnim;
function start(func) {
return func()
.catch(animFailed)
.tap(animFinished);
}
function animFailed(error) {
animFinished();
throw error;
}
function animFinished() {
currentDelay -= delay;
}
} | [
"function",
"AnimationThrottler",
"(",
"delay",
")",
"{",
"if",
"(",
"!",
"delay",
")",
"delay",
"=",
"DELAY",
";",
"// Anim is considered active if it's running or queued",
"var",
"currentDelay",
"=",
"0",
";",
"// func: Function that takes no params and returns a promise",
"function",
"requestAnim",
"(",
"func",
")",
"{",
"var",
"result",
"=",
"q",
".",
"delay",
"(",
"currentDelay",
")",
".",
"thenResolve",
"(",
"func",
")",
".",
"then",
"(",
"start",
")",
";",
"currentDelay",
"+=",
"delay",
";",
"return",
"result",
";",
"}",
"this",
".",
"requestAnim",
"=",
"requestAnim",
";",
"function",
"start",
"(",
"func",
")",
"{",
"return",
"func",
"(",
")",
".",
"catch",
"(",
"animFailed",
")",
".",
"tap",
"(",
"animFinished",
")",
";",
"}",
"function",
"animFailed",
"(",
"error",
")",
"{",
"animFinished",
"(",
")",
";",
"throw",
"error",
";",
"}",
"function",
"animFinished",
"(",
")",
"{",
"currentDelay",
"-=",
"delay",
";",
"}",
"}"
]
| Manges a queue of pending animates so that, if many are requested, not all of them run at once. An example of a situation where many animations would be requested at once is at the beginning of the game when cards are being dealt. | [
"Manges",
"a",
"queue",
"of",
"pending",
"animates",
"so",
"that",
"if",
"many",
"are",
"requested",
"not",
"all",
"of",
"them",
"run",
"at",
"once",
".",
"An",
"example",
"of",
"a",
"situation",
"where",
"many",
"animations",
"would",
"be",
"requested",
"at",
"once",
"is",
"at",
"the",
"beginning",
"of",
"the",
"game",
"when",
"cards",
"are",
"being",
"dealt",
"."
]
| 4632e8897c832b01d944a340cf87d5c807809925 | https://github.com/ryb73/dealers-choice-meta/blob/4632e8897c832b01d944a340cf87d5c807809925/packages/front-end/src/components/dc-game-canvas/animation-throttler.js#L14-L44 |
45,274 | chapmanu/hb | lib/hummingbird.js | function(service, credentials) {
Services.load(service);
process.nextTick(function() {
Services.boot(service, credentials);
}.bind(this));
} | javascript | function(service, credentials) {
Services.load(service);
process.nextTick(function() {
Services.boot(service, credentials);
}.bind(this));
} | [
"function",
"(",
"service",
",",
"credentials",
")",
"{",
"Services",
".",
"load",
"(",
"service",
")",
";",
"process",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"Services",
".",
"boot",
"(",
"service",
",",
"credentials",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
]
| Add a service to be streamed
@param {string} service - identifier of service, 'twitter', 'instagram', etc.
@param {object} credentials - API credentials for the service | [
"Add",
"a",
"service",
"to",
"be",
"streamed"
]
| 5edd8de89c7c5fdffc3df0c627513889220f7d51 | https://github.com/chapmanu/hb/blob/5edd8de89c7c5fdffc3df0c627513889220f7d51/lib/hummingbird.js#L38-L43 |
|
45,275 | DScheglov/merest | lib/controllers/update.js | update | function update(req, res, next) {
res.__apiMethod = 'update';
const self = this;
const id = req.params.id;
let filter = this.option('update', 'filter');
const fields = this.option('update', 'fields');
const populate = this.option('update', 'populate');
const readonly = this.option('update', 'readonly');
if (filter instanceof Function) filter = filter.call(this, req);
const query = Object.assign({ }, filter, { _id: id });
const method = self.option('update', 'method');
let data = helpers.flat(
(method !== 'get') ? req.body : req.query
);
try {
if (readonly) {
data = helpers.validateReadonly(data, readonly);
}
data = helpers.validateReadonly(data, [{ name: '_id', path: /^_id$/ }]);
} catch(e) {
return next(e)
}
let dbQuery = this.model.findOneAndUpdate(
query,
{ $set: data },
{
new: true,
fields: fields,
runValidators: true
}
);
if (populate) {
dbQuery = dbQuery.populate(populate);
}
dbQuery.exec(function(err, obj) {
if (err) {
if (err.name && err.name == "ValidationError") {
return next(new ModelAPIError(422, err));
}
return next(err);
};
if (!obj) return next(new ModelAPIError(
404, `The ${self.nameSingle} was not found by ${id}`
));
res.status(200);
res.json(obj);
});
} | javascript | function update(req, res, next) {
res.__apiMethod = 'update';
const self = this;
const id = req.params.id;
let filter = this.option('update', 'filter');
const fields = this.option('update', 'fields');
const populate = this.option('update', 'populate');
const readonly = this.option('update', 'readonly');
if (filter instanceof Function) filter = filter.call(this, req);
const query = Object.assign({ }, filter, { _id: id });
const method = self.option('update', 'method');
let data = helpers.flat(
(method !== 'get') ? req.body : req.query
);
try {
if (readonly) {
data = helpers.validateReadonly(data, readonly);
}
data = helpers.validateReadonly(data, [{ name: '_id', path: /^_id$/ }]);
} catch(e) {
return next(e)
}
let dbQuery = this.model.findOneAndUpdate(
query,
{ $set: data },
{
new: true,
fields: fields,
runValidators: true
}
);
if (populate) {
dbQuery = dbQuery.populate(populate);
}
dbQuery.exec(function(err, obj) {
if (err) {
if (err.name && err.name == "ValidationError") {
return next(new ModelAPIError(422, err));
}
return next(err);
};
if (!obj) return next(new ModelAPIError(
404, `The ${self.nameSingle} was not found by ${id}`
));
res.status(200);
res.json(obj);
});
} | [
"function",
"update",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"res",
".",
"__apiMethod",
"=",
"'update'",
";",
"const",
"self",
"=",
"this",
";",
"const",
"id",
"=",
"req",
".",
"params",
".",
"id",
";",
"let",
"filter",
"=",
"this",
".",
"option",
"(",
"'update'",
",",
"'filter'",
")",
";",
"const",
"fields",
"=",
"this",
".",
"option",
"(",
"'update'",
",",
"'fields'",
")",
";",
"const",
"populate",
"=",
"this",
".",
"option",
"(",
"'update'",
",",
"'populate'",
")",
";",
"const",
"readonly",
"=",
"this",
".",
"option",
"(",
"'update'",
",",
"'readonly'",
")",
";",
"if",
"(",
"filter",
"instanceof",
"Function",
")",
"filter",
"=",
"filter",
".",
"call",
"(",
"this",
",",
"req",
")",
";",
"const",
"query",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"filter",
",",
"{",
"_id",
":",
"id",
"}",
")",
";",
"const",
"method",
"=",
"self",
".",
"option",
"(",
"'update'",
",",
"'method'",
")",
";",
"let",
"data",
"=",
"helpers",
".",
"flat",
"(",
"(",
"method",
"!==",
"'get'",
")",
"?",
"req",
".",
"body",
":",
"req",
".",
"query",
")",
";",
"try",
"{",
"if",
"(",
"readonly",
")",
"{",
"data",
"=",
"helpers",
".",
"validateReadonly",
"(",
"data",
",",
"readonly",
")",
";",
"}",
"data",
"=",
"helpers",
".",
"validateReadonly",
"(",
"data",
",",
"[",
"{",
"name",
":",
"'_id'",
",",
"path",
":",
"/",
"^_id$",
"/",
"}",
"]",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"next",
"(",
"e",
")",
"}",
"let",
"dbQuery",
"=",
"this",
".",
"model",
".",
"findOneAndUpdate",
"(",
"query",
",",
"{",
"$set",
":",
"data",
"}",
",",
"{",
"new",
":",
"true",
",",
"fields",
":",
"fields",
",",
"runValidators",
":",
"true",
"}",
")",
";",
"if",
"(",
"populate",
")",
"{",
"dbQuery",
"=",
"dbQuery",
".",
"populate",
"(",
"populate",
")",
";",
"}",
"dbQuery",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"obj",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"name",
"&&",
"err",
".",
"name",
"==",
"\"ValidationError\"",
")",
"{",
"return",
"next",
"(",
"new",
"ModelAPIError",
"(",
"422",
",",
"err",
")",
")",
";",
"}",
"return",
"next",
"(",
"err",
")",
";",
"}",
";",
"if",
"(",
"!",
"obj",
")",
"return",
"next",
"(",
"new",
"ModelAPIError",
"(",
"404",
",",
"`",
"${",
"self",
".",
"nameSingle",
"}",
"${",
"id",
"}",
"`",
")",
")",
";",
"res",
".",
"status",
"(",
"200",
")",
";",
"res",
".",
"json",
"(",
"obj",
")",
";",
"}",
")",
";",
"}"
]
| update - controller that updates a model instance
@param {express.Request} req Request
@param {express.Response} res Response
@param {Function} next Callback to pass a thrown exception
@throws ModelAPIError(404, '...')
@throws ModelAPIError(422, '...')
@memberof ModelAPIRouter | [
"update",
"-",
"controller",
"that",
"updates",
"a",
"model",
"instance"
]
| d39e7ef0d56236247773467e9bfe83cb128ebc01 | https://github.com/DScheglov/merest/blob/d39e7ef0d56236247773467e9bfe83cb128ebc01/lib/controllers/update.js#L18-L71 |
45,276 | cheminfo-js/peaks-similarity | src/index.js | getOverlapTrapezoid | function getOverlapTrapezoid(x1, y1, x2, y2) {
var factor = 2 / (widthTop + widthBottom); // correction for surface=1
if (y1 === 0 || y2 === 0) return 0;
if (x1 === x2) { // they have the same position
return Math.min(y1, y2);
}
var diff = Math.abs(x1 - x2);
if (diff >= widthBottom) return 0;
if (y1 === y2) { // do they have the same height ???
// we need to find the common length
if (diff <= widthTop) {
return (((widthTop + widthBottom) / 2 - diff) * y1) * factor;
} else if (diff <= widthBottom) {
return (widthBottom - diff) * y1 / 2 * (diff - widthTop) / (widthBottom - widthTop) * factor;
}
return 0;
} else { // the height are different and not the same position ...
// we need to consider only one segment to find its intersection
var small = Math.min(y1, y2);
var big = Math.max(y1, y2);
var targets = [
[[0, 0], [widthSlope, small]],
[[widthSlope, small], [widthSlope + widthTop, small]],
[[widthTop + widthSlope, small], [widthBottom, 0]]
];
var segment;
if ((x1 > x2 && y1 > y2) || (x1 < x2 && y1 < y2)) {
segment = [[diff, 0], [diff + widthSlope, big]];
} else {
segment = [[diff + widthSlope, big], [diff, 0]];
}
for (var i = 0; i < 3; i++) {
var intersection = getIntersection(targets[i], segment);
if (intersection) {
switch (i) {
case 0:
return small - ((diff * intersection.y / 2)) * factor;
case 1: // to simplify ...
// console.log(" ",widthSlope,small,big,intersection.x)
return ((widthSlope * small / (2 * big)) * small +
(widthTop + widthSlope - intersection.x) * small +
widthSlope * small / 2) * factor;
case 2:
return ((widthBottom - diff) * intersection.y / 2) * factor;
default:
throw new Error(`unexpected intersection value: ${i}`);
}
}
}
}
return NaN;
} | javascript | function getOverlapTrapezoid(x1, y1, x2, y2) {
var factor = 2 / (widthTop + widthBottom); // correction for surface=1
if (y1 === 0 || y2 === 0) return 0;
if (x1 === x2) { // they have the same position
return Math.min(y1, y2);
}
var diff = Math.abs(x1 - x2);
if (diff >= widthBottom) return 0;
if (y1 === y2) { // do they have the same height ???
// we need to find the common length
if (diff <= widthTop) {
return (((widthTop + widthBottom) / 2 - diff) * y1) * factor;
} else if (diff <= widthBottom) {
return (widthBottom - diff) * y1 / 2 * (diff - widthTop) / (widthBottom - widthTop) * factor;
}
return 0;
} else { // the height are different and not the same position ...
// we need to consider only one segment to find its intersection
var small = Math.min(y1, y2);
var big = Math.max(y1, y2);
var targets = [
[[0, 0], [widthSlope, small]],
[[widthSlope, small], [widthSlope + widthTop, small]],
[[widthTop + widthSlope, small], [widthBottom, 0]]
];
var segment;
if ((x1 > x2 && y1 > y2) || (x1 < x2 && y1 < y2)) {
segment = [[diff, 0], [diff + widthSlope, big]];
} else {
segment = [[diff + widthSlope, big], [diff, 0]];
}
for (var i = 0; i < 3; i++) {
var intersection = getIntersection(targets[i], segment);
if (intersection) {
switch (i) {
case 0:
return small - ((diff * intersection.y / 2)) * factor;
case 1: // to simplify ...
// console.log(" ",widthSlope,small,big,intersection.x)
return ((widthSlope * small / (2 * big)) * small +
(widthTop + widthSlope - intersection.x) * small +
widthSlope * small / 2) * factor;
case 2:
return ((widthBottom - diff) * intersection.y / 2) * factor;
default:
throw new Error(`unexpected intersection value: ${i}`);
}
}
}
}
return NaN;
} | [
"function",
"getOverlapTrapezoid",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")",
"{",
"var",
"factor",
"=",
"2",
"/",
"(",
"widthTop",
"+",
"widthBottom",
")",
";",
"// correction for surface=1",
"if",
"(",
"y1",
"===",
"0",
"||",
"y2",
"===",
"0",
")",
"return",
"0",
";",
"if",
"(",
"x1",
"===",
"x2",
")",
"{",
"// they have the same position",
"return",
"Math",
".",
"min",
"(",
"y1",
",",
"y2",
")",
";",
"}",
"var",
"diff",
"=",
"Math",
".",
"abs",
"(",
"x1",
"-",
"x2",
")",
";",
"if",
"(",
"diff",
">=",
"widthBottom",
")",
"return",
"0",
";",
"if",
"(",
"y1",
"===",
"y2",
")",
"{",
"// do they have the same height ???",
"// we need to find the common length",
"if",
"(",
"diff",
"<=",
"widthTop",
")",
"{",
"return",
"(",
"(",
"(",
"widthTop",
"+",
"widthBottom",
")",
"/",
"2",
"-",
"diff",
")",
"*",
"y1",
")",
"*",
"factor",
";",
"}",
"else",
"if",
"(",
"diff",
"<=",
"widthBottom",
")",
"{",
"return",
"(",
"widthBottom",
"-",
"diff",
")",
"*",
"y1",
"/",
"2",
"*",
"(",
"diff",
"-",
"widthTop",
")",
"/",
"(",
"widthBottom",
"-",
"widthTop",
")",
"*",
"factor",
";",
"}",
"return",
"0",
";",
"}",
"else",
"{",
"// the height are different and not the same position ...",
"// we need to consider only one segment to find its intersection",
"var",
"small",
"=",
"Math",
".",
"min",
"(",
"y1",
",",
"y2",
")",
";",
"var",
"big",
"=",
"Math",
".",
"max",
"(",
"y1",
",",
"y2",
")",
";",
"var",
"targets",
"=",
"[",
"[",
"[",
"0",
",",
"0",
"]",
",",
"[",
"widthSlope",
",",
"small",
"]",
"]",
",",
"[",
"[",
"widthSlope",
",",
"small",
"]",
",",
"[",
"widthSlope",
"+",
"widthTop",
",",
"small",
"]",
"]",
",",
"[",
"[",
"widthTop",
"+",
"widthSlope",
",",
"small",
"]",
",",
"[",
"widthBottom",
",",
"0",
"]",
"]",
"]",
";",
"var",
"segment",
";",
"if",
"(",
"(",
"x1",
">",
"x2",
"&&",
"y1",
">",
"y2",
")",
"||",
"(",
"x1",
"<",
"x2",
"&&",
"y1",
"<",
"y2",
")",
")",
"{",
"segment",
"=",
"[",
"[",
"diff",
",",
"0",
"]",
",",
"[",
"diff",
"+",
"widthSlope",
",",
"big",
"]",
"]",
";",
"}",
"else",
"{",
"segment",
"=",
"[",
"[",
"diff",
"+",
"widthSlope",
",",
"big",
"]",
",",
"[",
"diff",
",",
"0",
"]",
"]",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"3",
";",
"i",
"++",
")",
"{",
"var",
"intersection",
"=",
"getIntersection",
"(",
"targets",
"[",
"i",
"]",
",",
"segment",
")",
";",
"if",
"(",
"intersection",
")",
"{",
"switch",
"(",
"i",
")",
"{",
"case",
"0",
":",
"return",
"small",
"-",
"(",
"(",
"diff",
"*",
"intersection",
".",
"y",
"/",
"2",
")",
")",
"*",
"factor",
";",
"case",
"1",
":",
"// to simplify ...",
"// console.log(\" \",widthSlope,small,big,intersection.x)",
"return",
"(",
"(",
"widthSlope",
"*",
"small",
"/",
"(",
"2",
"*",
"big",
")",
")",
"*",
"small",
"+",
"(",
"widthTop",
"+",
"widthSlope",
"-",
"intersection",
".",
"x",
")",
"*",
"small",
"+",
"widthSlope",
"*",
"small",
"/",
"2",
")",
"*",
"factor",
";",
"case",
"2",
":",
"return",
"(",
"(",
"widthBottom",
"-",
"diff",
")",
"*",
"intersection",
".",
"y",
"/",
"2",
")",
"*",
"factor",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"`",
"${",
"i",
"}",
"`",
")",
";",
"}",
"}",
"}",
"}",
"return",
"NaN",
";",
"}"
]
| This is the old trapezoid similarity | [
"This",
"is",
"the",
"old",
"trapezoid",
"similarity"
]
| d1b011072c953458f05d3aa1f18d420a67cf717f | https://github.com/cheminfo-js/peaks-similarity/blob/d1b011072c953458f05d3aa1f18d420a67cf717f/src/index.js#L157-L213 |
45,277 | cheminfo-js/peaks-similarity | src/index.js | calculateDiff | function calculateDiff() {
// we need to take 2 pointers
// and travel progressively between them ...
var newFirst = [
[].concat(array1Extract[0]),
[].concat(array1Extract[1])
];
var newSecond = [
[].concat(array2Extract[0]),
[].concat(array2Extract[1])
];
var array1Length = array1Extract[0] ? array1Extract[0].length : 0;
var array2Length = array2Extract[0] ? array2Extract[0].length : 0;
var pos1 = 0;
var pos2 = 0;
var previous2 = 0;
while (pos1 < array1Length) {
var diff = newFirst[0][pos1] - array2Extract[0][pos2];
if (Math.abs(diff) < widthBottom) { // there is some overlap
var overlap;
if (options.trapezoid) {
overlap = getOverlapTrapezoid(newFirst[0][pos1], newFirst[1][pos1], newSecond[0][pos2], newSecond[1][pos2], widthTop, widthBottom);
} else {
overlap = getOverlap(newFirst[0][pos1], newFirst[1][pos1], newSecond[0][pos2], newSecond[1][pos2], widthTop, widthBottom);
}
newFirst[1][pos1] -= overlap;
newSecond[1][pos2] -= overlap;
if (pos2 < (array2Length - 1)) {
pos2++;
} else {
pos1++;
pos2 = previous2;
}
} else {
if (diff > 0 && pos2 < (array2Length - 1)) {
pos2++;
previous2 = pos2;
} else {
pos1++;
pos2 = previous2;
}
}
}
return newSecond;
} | javascript | function calculateDiff() {
// we need to take 2 pointers
// and travel progressively between them ...
var newFirst = [
[].concat(array1Extract[0]),
[].concat(array1Extract[1])
];
var newSecond = [
[].concat(array2Extract[0]),
[].concat(array2Extract[1])
];
var array1Length = array1Extract[0] ? array1Extract[0].length : 0;
var array2Length = array2Extract[0] ? array2Extract[0].length : 0;
var pos1 = 0;
var pos2 = 0;
var previous2 = 0;
while (pos1 < array1Length) {
var diff = newFirst[0][pos1] - array2Extract[0][pos2];
if (Math.abs(diff) < widthBottom) { // there is some overlap
var overlap;
if (options.trapezoid) {
overlap = getOverlapTrapezoid(newFirst[0][pos1], newFirst[1][pos1], newSecond[0][pos2], newSecond[1][pos2], widthTop, widthBottom);
} else {
overlap = getOverlap(newFirst[0][pos1], newFirst[1][pos1], newSecond[0][pos2], newSecond[1][pos2], widthTop, widthBottom);
}
newFirst[1][pos1] -= overlap;
newSecond[1][pos2] -= overlap;
if (pos2 < (array2Length - 1)) {
pos2++;
} else {
pos1++;
pos2 = previous2;
}
} else {
if (diff > 0 && pos2 < (array2Length - 1)) {
pos2++;
previous2 = pos2;
} else {
pos1++;
pos2 = previous2;
}
}
}
return newSecond;
} | [
"function",
"calculateDiff",
"(",
")",
"{",
"// we need to take 2 pointers",
"// and travel progressively between them ...",
"var",
"newFirst",
"=",
"[",
"[",
"]",
".",
"concat",
"(",
"array1Extract",
"[",
"0",
"]",
")",
",",
"[",
"]",
".",
"concat",
"(",
"array1Extract",
"[",
"1",
"]",
")",
"]",
";",
"var",
"newSecond",
"=",
"[",
"[",
"]",
".",
"concat",
"(",
"array2Extract",
"[",
"0",
"]",
")",
",",
"[",
"]",
".",
"concat",
"(",
"array2Extract",
"[",
"1",
"]",
")",
"]",
";",
"var",
"array1Length",
"=",
"array1Extract",
"[",
"0",
"]",
"?",
"array1Extract",
"[",
"0",
"]",
".",
"length",
":",
"0",
";",
"var",
"array2Length",
"=",
"array2Extract",
"[",
"0",
"]",
"?",
"array2Extract",
"[",
"0",
"]",
".",
"length",
":",
"0",
";",
"var",
"pos1",
"=",
"0",
";",
"var",
"pos2",
"=",
"0",
";",
"var",
"previous2",
"=",
"0",
";",
"while",
"(",
"pos1",
"<",
"array1Length",
")",
"{",
"var",
"diff",
"=",
"newFirst",
"[",
"0",
"]",
"[",
"pos1",
"]",
"-",
"array2Extract",
"[",
"0",
"]",
"[",
"pos2",
"]",
";",
"if",
"(",
"Math",
".",
"abs",
"(",
"diff",
")",
"<",
"widthBottom",
")",
"{",
"// there is some overlap",
"var",
"overlap",
";",
"if",
"(",
"options",
".",
"trapezoid",
")",
"{",
"overlap",
"=",
"getOverlapTrapezoid",
"(",
"newFirst",
"[",
"0",
"]",
"[",
"pos1",
"]",
",",
"newFirst",
"[",
"1",
"]",
"[",
"pos1",
"]",
",",
"newSecond",
"[",
"0",
"]",
"[",
"pos2",
"]",
",",
"newSecond",
"[",
"1",
"]",
"[",
"pos2",
"]",
",",
"widthTop",
",",
"widthBottom",
")",
";",
"}",
"else",
"{",
"overlap",
"=",
"getOverlap",
"(",
"newFirst",
"[",
"0",
"]",
"[",
"pos1",
"]",
",",
"newFirst",
"[",
"1",
"]",
"[",
"pos1",
"]",
",",
"newSecond",
"[",
"0",
"]",
"[",
"pos2",
"]",
",",
"newSecond",
"[",
"1",
"]",
"[",
"pos2",
"]",
",",
"widthTop",
",",
"widthBottom",
")",
";",
"}",
"newFirst",
"[",
"1",
"]",
"[",
"pos1",
"]",
"-=",
"overlap",
";",
"newSecond",
"[",
"1",
"]",
"[",
"pos2",
"]",
"-=",
"overlap",
";",
"if",
"(",
"pos2",
"<",
"(",
"array2Length",
"-",
"1",
")",
")",
"{",
"pos2",
"++",
";",
"}",
"else",
"{",
"pos1",
"++",
";",
"pos2",
"=",
"previous2",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"diff",
">",
"0",
"&&",
"pos2",
"<",
"(",
"array2Length",
"-",
"1",
")",
")",
"{",
"pos2",
"++",
";",
"previous2",
"=",
"pos2",
";",
"}",
"else",
"{",
"pos1",
"++",
";",
"pos2",
"=",
"previous2",
";",
"}",
"}",
"}",
"return",
"newSecond",
";",
"}"
]
| this method calculates the total diff. The sum of positive value will yield to overlap | [
"this",
"method",
"calculates",
"the",
"total",
"diff",
".",
"The",
"sum",
"of",
"positive",
"value",
"will",
"yield",
"to",
"overlap"
]
| d1b011072c953458f05d3aa1f18d420a67cf717f | https://github.com/cheminfo-js/peaks-similarity/blob/d1b011072c953458f05d3aa1f18d420a67cf717f/src/index.js#L217-L262 |
45,278 | cheminfo-js/peaks-similarity | src/index.js | commonExtractAndNormalize | function commonExtractAndNormalize(array1, array2, width, from, to, common) {
if (!(Array.isArray(array1)) || !(Array.isArray(array2))) {
return {
info: undefined,
data: undefined
};
}
var extract1 = extract(array1, from, to);
var extract2 = extract(array2, from, to);
var common1, common2, info1, info2;
if (common & COMMON_SECOND) {
common1 = getCommonArray(extract1, extract2, width);
info1 = normalize(common1);
} else {
common1 = extract1;
info1 = normalize(common1);
}
if (common & COMMON_FIRST) {
common2 = getCommonArray(extract2, extract1, width);
info2 = normalize(common2);
} else {
common2 = extract2;
info2 = normalize(common2);
}
return {
info1: info1,
info2: info2,
data1: common1,
data2: common2
};
} | javascript | function commonExtractAndNormalize(array1, array2, width, from, to, common) {
if (!(Array.isArray(array1)) || !(Array.isArray(array2))) {
return {
info: undefined,
data: undefined
};
}
var extract1 = extract(array1, from, to);
var extract2 = extract(array2, from, to);
var common1, common2, info1, info2;
if (common & COMMON_SECOND) {
common1 = getCommonArray(extract1, extract2, width);
info1 = normalize(common1);
} else {
common1 = extract1;
info1 = normalize(common1);
}
if (common & COMMON_FIRST) {
common2 = getCommonArray(extract2, extract1, width);
info2 = normalize(common2);
} else {
common2 = extract2;
info2 = normalize(common2);
}
return {
info1: info1,
info2: info2,
data1: common1,
data2: common2
};
} | [
"function",
"commonExtractAndNormalize",
"(",
"array1",
",",
"array2",
",",
"width",
",",
"from",
",",
"to",
",",
"common",
")",
"{",
"if",
"(",
"!",
"(",
"Array",
".",
"isArray",
"(",
"array1",
")",
")",
"||",
"!",
"(",
"Array",
".",
"isArray",
"(",
"array2",
")",
")",
")",
"{",
"return",
"{",
"info",
":",
"undefined",
",",
"data",
":",
"undefined",
"}",
";",
"}",
"var",
"extract1",
"=",
"extract",
"(",
"array1",
",",
"from",
",",
"to",
")",
";",
"var",
"extract2",
"=",
"extract",
"(",
"array2",
",",
"from",
",",
"to",
")",
";",
"var",
"common1",
",",
"common2",
",",
"info1",
",",
"info2",
";",
"if",
"(",
"common",
"&",
"COMMON_SECOND",
")",
"{",
"common1",
"=",
"getCommonArray",
"(",
"extract1",
",",
"extract2",
",",
"width",
")",
";",
"info1",
"=",
"normalize",
"(",
"common1",
")",
";",
"}",
"else",
"{",
"common1",
"=",
"extract1",
";",
"info1",
"=",
"normalize",
"(",
"common1",
")",
";",
"}",
"if",
"(",
"common",
"&",
"COMMON_FIRST",
")",
"{",
"common2",
"=",
"getCommonArray",
"(",
"extract2",
",",
"extract1",
",",
"width",
")",
";",
"info2",
"=",
"normalize",
"(",
"common2",
")",
";",
"}",
"else",
"{",
"common2",
"=",
"extract2",
";",
"info2",
"=",
"normalize",
"(",
"common2",
")",
";",
"}",
"return",
"{",
"info1",
":",
"info1",
",",
"info2",
":",
"info2",
",",
"data1",
":",
"common1",
",",
"data2",
":",
"common2",
"}",
";",
"}"
]
| this method will systematically take care of both array | [
"this",
"method",
"will",
"systematically",
"take",
"care",
"of",
"both",
"array"
]
| d1b011072c953458f05d3aa1f18d420a67cf717f | https://github.com/cheminfo-js/peaks-similarity/blob/d1b011072c953458f05d3aa1f18d420a67cf717f/src/index.js#L396-L427 |
45,279 | henrytseng/angular-state-router | src/services/state-router.js | function(nameParams) {
if(nameParams && nameParams.match(/^[a-zA-Z0-9_\.]*\(.*\)$/)) {
var npart = nameParams.substring(0, nameParams.indexOf('('));
var ppart = Parameters( nameParams.substring(nameParams.indexOf('(')+1, nameParams.lastIndexOf(')')) );
return {
name: npart,
params: ppart
};
} else {
return {
name: nameParams,
params: null
};
}
} | javascript | function(nameParams) {
if(nameParams && nameParams.match(/^[a-zA-Z0-9_\.]*\(.*\)$/)) {
var npart = nameParams.substring(0, nameParams.indexOf('('));
var ppart = Parameters( nameParams.substring(nameParams.indexOf('(')+1, nameParams.lastIndexOf(')')) );
return {
name: npart,
params: ppart
};
} else {
return {
name: nameParams,
params: null
};
}
} | [
"function",
"(",
"nameParams",
")",
"{",
"if",
"(",
"nameParams",
"&&",
"nameParams",
".",
"match",
"(",
"/",
"^[a-zA-Z0-9_\\.]*\\(.*\\)$",
"/",
")",
")",
"{",
"var",
"npart",
"=",
"nameParams",
".",
"substring",
"(",
"0",
",",
"nameParams",
".",
"indexOf",
"(",
"'('",
")",
")",
";",
"var",
"ppart",
"=",
"Parameters",
"(",
"nameParams",
".",
"substring",
"(",
"nameParams",
".",
"indexOf",
"(",
"'('",
")",
"+",
"1",
",",
"nameParams",
".",
"lastIndexOf",
"(",
"')'",
")",
")",
")",
";",
"return",
"{",
"name",
":",
"npart",
",",
"params",
":",
"ppart",
"}",
";",
"}",
"else",
"{",
"return",
"{",
"name",
":",
"nameParams",
",",
"params",
":",
"null",
"}",
";",
"}",
"}"
]
| Parse state notation name-params.
Assume all parameter values are strings
@param {String} nameParams A name-params string
@return {Object} A name string and param Object | [
"Parse",
"state",
"notation",
"name",
"-",
"params",
"."
]
| 5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b | https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/src/services/state-router.js#L33-L49 |
|
45,280 | henrytseng/angular-state-router | src/services/state-router.js | function(name) {
name = name || '';
// TODO optimize with RegExp
var nameChain = name.split('.');
for(var i=0; i<nameChain.length; i++) {
if(!nameChain[i].match(/[a-zA-Z0-9_]+/)) {
return false;
}
}
return true;
} | javascript | function(name) {
name = name || '';
// TODO optimize with RegExp
var nameChain = name.split('.');
for(var i=0; i<nameChain.length; i++) {
if(!nameChain[i].match(/[a-zA-Z0-9_]+/)) {
return false;
}
}
return true;
} | [
"function",
"(",
"name",
")",
"{",
"name",
"=",
"name",
"||",
"''",
";",
"// TODO optimize with RegExp",
"var",
"nameChain",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"nameChain",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"nameChain",
"[",
"i",
"]",
".",
"match",
"(",
"/",
"[a-zA-Z0-9_]+",
"/",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
]
| Validate state name
@param {String} name A unique identifier for the state; using dot-notation
@return {Boolean} True if name is valid, false if not | [
"Validate",
"state",
"name"
]
| 5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b | https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/src/services/state-router.js#L70-L83 |
|
45,281 | henrytseng/angular-state-router | src/services/state-router.js | function(query) {
query = query || '';
// TODO optimize with RegExp
var nameChain = query.split('.');
for(var i=0; i<nameChain.length; i++) {
if(!nameChain[i].match(/(\*(\*)?|[a-zA-Z0-9_]+)/)) {
return false;
}
}
return true;
} | javascript | function(query) {
query = query || '';
// TODO optimize with RegExp
var nameChain = query.split('.');
for(var i=0; i<nameChain.length; i++) {
if(!nameChain[i].match(/(\*(\*)?|[a-zA-Z0-9_]+)/)) {
return false;
}
}
return true;
} | [
"function",
"(",
"query",
")",
"{",
"query",
"=",
"query",
"||",
"''",
";",
"// TODO optimize with RegExp",
"var",
"nameChain",
"=",
"query",
".",
"split",
"(",
"'.'",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"nameChain",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"nameChain",
"[",
"i",
"]",
".",
"match",
"(",
"/",
"(\\*(\\*)?|[a-zA-Z0-9_]+)",
"/",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
]
| Validate state query
@param {String} query A query for the state; using dot-notation
@return {Boolean} True if name is valid, false if not | [
"Validate",
"state",
"query"
]
| 5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b | https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/src/services/state-router.js#L91-L104 |
|
45,282 | henrytseng/angular-state-router | src/services/state-router.js | function(a, b) {
a = a || {};
b = b || {};
return a.name === b.name && angular.equals(a.params, b.params);
} | javascript | function(a, b) {
a = a || {};
b = b || {};
return a.name === b.name && angular.equals(a.params, b.params);
} | [
"function",
"(",
"a",
",",
"b",
")",
"{",
"a",
"=",
"a",
"||",
"{",
"}",
";",
"b",
"=",
"b",
"||",
"{",
"}",
";",
"return",
"a",
".",
"name",
"===",
"b",
".",
"name",
"&&",
"angular",
".",
"equals",
"(",
"a",
".",
"params",
",",
"b",
".",
"params",
")",
";",
"}"
]
| Compare two states, compares values.
@return {Boolean} True if states are the same, false if states are different | [
"Compare",
"two",
"states",
"compares",
"values",
"."
]
| 5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b | https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/src/services/state-router.js#L111-L115 |
|
45,283 | henrytseng/angular-state-router | src/services/state-router.js | function(name) {
var nameList = name.split('.');
return nameList
.map(function(item, i, list) {
return list.slice(0, i+1).join('.');
})
.filter(function(item) {
return item !== null;
});
} | javascript | function(name) {
var nameList = name.split('.');
return nameList
.map(function(item, i, list) {
return list.slice(0, i+1).join('.');
})
.filter(function(item) {
return item !== null;
});
} | [
"function",
"(",
"name",
")",
"{",
"var",
"nameList",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
";",
"return",
"nameList",
".",
"map",
"(",
"function",
"(",
"item",
",",
"i",
",",
"list",
")",
"{",
"return",
"list",
".",
"slice",
"(",
"0",
",",
"i",
"+",
"1",
")",
".",
"join",
"(",
"'.'",
")",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"item",
")",
"{",
"return",
"item",
"!==",
"null",
";",
"}",
")",
";",
"}"
]
| Get a list of parent states
@param {String} name A unique identifier for the state; using dot-notation
@return {Array} An Array of parent states | [
"Get",
"a",
"list",
"of",
"parent",
"states"
]
| 5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b | https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/src/services/state-router.js#L123-L133 |
|
45,284 | henrytseng/angular-state-router | src/services/state-router.js | function(name) {
name = name || '';
var state = null;
// Only use valid state queries
if(!_validateStateName(name)) {
return null;
// Use cache if exists
} else if(_stateCache[name]) {
return _stateCache[name];
}
var nameChain = _getNameChain(name);
var stateChain = nameChain
.map(function(name, i) {
var item = angular.copy(_stateLibrary[name]);
return item;
})
.filter(function(parent) {
return !!parent;
});
// Walk up checking inheritance
for(var i=stateChain.length-1; i>=0; i--) {
if(stateChain[i]) {
var nextState = stateChain[i];
state = angular.merge(nextState, state || {});
}
if(state && state.inherit === false) break;
}
// Store in cache
_stateCache[name] = state;
return state;
} | javascript | function(name) {
name = name || '';
var state = null;
// Only use valid state queries
if(!_validateStateName(name)) {
return null;
// Use cache if exists
} else if(_stateCache[name]) {
return _stateCache[name];
}
var nameChain = _getNameChain(name);
var stateChain = nameChain
.map(function(name, i) {
var item = angular.copy(_stateLibrary[name]);
return item;
})
.filter(function(parent) {
return !!parent;
});
// Walk up checking inheritance
for(var i=stateChain.length-1; i>=0; i--) {
if(stateChain[i]) {
var nextState = stateChain[i];
state = angular.merge(nextState, state || {});
}
if(state && state.inherit === false) break;
}
// Store in cache
_stateCache[name] = state;
return state;
} | [
"function",
"(",
"name",
")",
"{",
"name",
"=",
"name",
"||",
"''",
";",
"var",
"state",
"=",
"null",
";",
"// Only use valid state queries",
"if",
"(",
"!",
"_validateStateName",
"(",
"name",
")",
")",
"{",
"return",
"null",
";",
"// Use cache if exists",
"}",
"else",
"if",
"(",
"_stateCache",
"[",
"name",
"]",
")",
"{",
"return",
"_stateCache",
"[",
"name",
"]",
";",
"}",
"var",
"nameChain",
"=",
"_getNameChain",
"(",
"name",
")",
";",
"var",
"stateChain",
"=",
"nameChain",
".",
"map",
"(",
"function",
"(",
"name",
",",
"i",
")",
"{",
"var",
"item",
"=",
"angular",
".",
"copy",
"(",
"_stateLibrary",
"[",
"name",
"]",
")",
";",
"return",
"item",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"parent",
")",
"{",
"return",
"!",
"!",
"parent",
";",
"}",
")",
";",
"// Walk up checking inheritance",
"for",
"(",
"var",
"i",
"=",
"stateChain",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"if",
"(",
"stateChain",
"[",
"i",
"]",
")",
"{",
"var",
"nextState",
"=",
"stateChain",
"[",
"i",
"]",
";",
"state",
"=",
"angular",
".",
"merge",
"(",
"nextState",
",",
"state",
"||",
"{",
"}",
")",
";",
"}",
"if",
"(",
"state",
"&&",
"state",
".",
"inherit",
"===",
"false",
")",
"break",
";",
"}",
"// Store in cache",
"_stateCache",
"[",
"name",
"]",
"=",
"state",
";",
"return",
"state",
";",
"}"
]
| Internal method to crawl library heirarchy
@param {String} name A unique identifier for the state; using state-notation
@return {Object} A state data Object | [
"Internal",
"method",
"to",
"crawl",
"library",
"heirarchy"
]
| 5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b | https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/src/services/state-router.js#L141-L179 |
|
45,285 | henrytseng/angular-state-router | src/services/state-router.js | function(name, data) {
if(name === null || typeof name === 'undefined') {
throw new Error('Name cannot be null.');
// Only use valid state names
} else if(!_validateStateName(name)) {
throw new Error('Invalid state name.');
}
// Create state
var state = angular.copy(data);
// Use defaults
_setStateDefaults(state);
// Named state
state.name = name;
// Set definition
_stateLibrary[name] = state;
// Reset cache
_stateCache = {};
// URL mapping
if(state.url) {
_urlDictionary.add(state.url, state);
}
return data;
} | javascript | function(name, data) {
if(name === null || typeof name === 'undefined') {
throw new Error('Name cannot be null.');
// Only use valid state names
} else if(!_validateStateName(name)) {
throw new Error('Invalid state name.');
}
// Create state
var state = angular.copy(data);
// Use defaults
_setStateDefaults(state);
// Named state
state.name = name;
// Set definition
_stateLibrary[name] = state;
// Reset cache
_stateCache = {};
// URL mapping
if(state.url) {
_urlDictionary.add(state.url, state);
}
return data;
} | [
"function",
"(",
"name",
",",
"data",
")",
"{",
"if",
"(",
"name",
"===",
"null",
"||",
"typeof",
"name",
"===",
"'undefined'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Name cannot be null.'",
")",
";",
"// Only use valid state names",
"}",
"else",
"if",
"(",
"!",
"_validateStateName",
"(",
"name",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid state name.'",
")",
";",
"}",
"// Create state",
"var",
"state",
"=",
"angular",
".",
"copy",
"(",
"data",
")",
";",
"// Use defaults",
"_setStateDefaults",
"(",
"state",
")",
";",
"// Named state",
"state",
".",
"name",
"=",
"name",
";",
"// Set definition",
"_stateLibrary",
"[",
"name",
"]",
"=",
"state",
";",
"// Reset cache",
"_stateCache",
"=",
"{",
"}",
";",
"// URL mapping",
"if",
"(",
"state",
".",
"url",
")",
"{",
"_urlDictionary",
".",
"add",
"(",
"state",
".",
"url",
",",
"state",
")",
";",
"}",
"return",
"data",
";",
"}"
]
| Internal method to store a state definition. Parameters should be included in data Object not state name.
@param {String} name A unique identifier for the state; using state-notation
@param {Object} data A state definition data Object
@return {Object} A state data Object | [
"Internal",
"method",
"to",
"store",
"a",
"state",
"definition",
".",
"Parameters",
"should",
"be",
"included",
"in",
"data",
"Object",
"not",
"state",
"name",
"."
]
| 5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b | https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/src/services/state-router.js#L188-L218 |
|
45,286 | henrytseng/angular-state-router | src/services/state-router.js | function(data) {
// Keep the last n states (e.g. - defaults 5)
var historyLength = _options.historyLength || 5;
if(data) {
_history.push(data);
}
// Update length
if(_history.length > historyLength) {
_history.splice(0, _history.length - historyLength);
}
} | javascript | function(data) {
// Keep the last n states (e.g. - defaults 5)
var historyLength = _options.historyLength || 5;
if(data) {
_history.push(data);
}
// Update length
if(_history.length > historyLength) {
_history.splice(0, _history.length - historyLength);
}
} | [
"function",
"(",
"data",
")",
"{",
"// Keep the last n states (e.g. - defaults 5)",
"var",
"historyLength",
"=",
"_options",
".",
"historyLength",
"||",
"5",
";",
"if",
"(",
"data",
")",
"{",
"_history",
".",
"push",
"(",
"data",
")",
";",
"}",
"// Update length",
"if",
"(",
"_history",
".",
"length",
">",
"historyLength",
")",
"{",
"_history",
".",
"splice",
"(",
"0",
",",
"_history",
".",
"length",
"-",
"historyLength",
")",
";",
"}",
"}"
]
| Internal method to add history and correct length
@param {Object} data An Object | [
"Internal",
"method",
"to",
"add",
"history",
"and",
"correct",
"length"
]
| 5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b | https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/src/services/state-router.js#L290-L302 |
|
45,287 | henrytseng/angular-state-router | src/services/state-router.js | function(name, params) {
return _changeState(name, params).then(function() {
$rootScope.$broadcast('$stateChangeComplete', null, _current);
}, function(err) {
$rootScope.$broadcast('$stateChangeComplete', err, _current);
});
} | javascript | function(name, params) {
return _changeState(name, params).then(function() {
$rootScope.$broadcast('$stateChangeComplete', null, _current);
}, function(err) {
$rootScope.$broadcast('$stateChangeComplete', err, _current);
});
} | [
"function",
"(",
"name",
",",
"params",
")",
"{",
"return",
"_changeState",
"(",
"name",
",",
"params",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"$rootScope",
".",
"$broadcast",
"(",
"'$stateChangeComplete'",
",",
"null",
",",
"_current",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"$rootScope",
".",
"$broadcast",
"(",
"'$stateChangeComplete'",
",",
"err",
",",
"_current",
")",
";",
"}",
")",
";",
"}"
]
| Internal method to change to state and broadcast completion
@param {String} name A unique identifier for the state; using state-notation including optional parameters
@param {Object} params A data object of params
@return {Promise} A promise fulfilled when state change occurs | [
"Internal",
"method",
"to",
"change",
"to",
"state",
"and",
"broadcast",
"completion"
]
| 5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b | https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/src/services/state-router.js#L414-L420 |
|
45,288 | henrytseng/angular-state-router | src/services/state-router.js | function() {
var deferred = $q.defer();
$rootScope.$evalAsync(function() {
var n = _current.name;
var p = angular.copy(_current.params);
if(!_current.params) {
_current.params = {};
}
_current.params.deprecated = true;
// Notify
$rootScope.$broadcast('$stateReload', null, _current);
_changeStateAndBroadcastComplete(n, p).then(function() {
deferred.resolve();
}, function(err) {
deferred.reject(err);
});
});
return deferred.promise;
} | javascript | function() {
var deferred = $q.defer();
$rootScope.$evalAsync(function() {
var n = _current.name;
var p = angular.copy(_current.params);
if(!_current.params) {
_current.params = {};
}
_current.params.deprecated = true;
// Notify
$rootScope.$broadcast('$stateReload', null, _current);
_changeStateAndBroadcastComplete(n, p).then(function() {
deferred.resolve();
}, function(err) {
deferred.reject(err);
});
});
return deferred.promise;
} | [
"function",
"(",
")",
"{",
"var",
"deferred",
"=",
"$q",
".",
"defer",
"(",
")",
";",
"$rootScope",
".",
"$evalAsync",
"(",
"function",
"(",
")",
"{",
"var",
"n",
"=",
"_current",
".",
"name",
";",
"var",
"p",
"=",
"angular",
".",
"copy",
"(",
"_current",
".",
"params",
")",
";",
"if",
"(",
"!",
"_current",
".",
"params",
")",
"{",
"_current",
".",
"params",
"=",
"{",
"}",
";",
"}",
"_current",
".",
"params",
".",
"deprecated",
"=",
"true",
";",
"// Notify",
"$rootScope",
".",
"$broadcast",
"(",
"'$stateReload'",
",",
"null",
",",
"_current",
")",
";",
"_changeStateAndBroadcastComplete",
"(",
"n",
",",
"p",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"deferred",
".",
"resolve",
"(",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
]
| Reloads the current state
@return {Promise} A promise fulfilled when state change occurs | [
"Reloads",
"the",
"current",
"state"
]
| 5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b | https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/src/services/state-router.js#L427-L449 |
|
45,289 | henrytseng/angular-state-router | src/services/state-router.js | function(handler, priority) {
if(typeof handler !== 'function') {
throw new Error('Middleware must be a function.');
}
if(typeof priority !== 'undefined') handler.priority = priority;
_layerList.push(handler);
return _inst;
} | javascript | function(handler, priority) {
if(typeof handler !== 'function') {
throw new Error('Middleware must be a function.');
}
if(typeof priority !== 'undefined') handler.priority = priority;
_layerList.push(handler);
return _inst;
} | [
"function",
"(",
"handler",
",",
"priority",
")",
"{",
"if",
"(",
"typeof",
"handler",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Middleware must be a function.'",
")",
";",
"}",
"if",
"(",
"typeof",
"priority",
"!==",
"'undefined'",
")",
"handler",
".",
"priority",
"=",
"priority",
";",
"_layerList",
".",
"push",
"(",
"handler",
")",
";",
"return",
"_inst",
";",
"}"
]
| Internal method to add middleware; called during state transition
@param {Function} handler A callback, function(request, next)
@param {Number} priority A number denoting priority
@return {$state} Itself; chainable | [
"Internal",
"method",
"to",
"add",
"middleware",
";",
"called",
"during",
"state",
"transition"
]
| 5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b | https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/src/services/state-router.js#L496-L504 |
|
45,290 | henrytseng/angular-state-router | src/services/state-router.js | function(query, params) {
query = query || '';
// No state
if(!_current) {
return false;
// Use RegExp matching
} else if(query instanceof RegExp) {
return !!_current.name.match(query);
// String; state dot-notation
} else if(typeof query === 'string') {
// Cast string to RegExp
if(query.match(/^\/.*\/$/)) {
var casted = query.substr(1, query.length-2);
return !!_current.name.match(new RegExp(casted));
// Transform to state notation
} else {
var transformed = query
.split('.')
.map(function(item) {
if(item === '*') {
return '[a-zA-Z0-9_]*';
} else if(item === '**') {
return '[a-zA-Z0-9_\\.]*';
} else {
return item;
}
})
.join('\\.');
return !!_current.name.match(new RegExp(transformed));
}
}
// Non-matching
return false;
} | javascript | function(query, params) {
query = query || '';
// No state
if(!_current) {
return false;
// Use RegExp matching
} else if(query instanceof RegExp) {
return !!_current.name.match(query);
// String; state dot-notation
} else if(typeof query === 'string') {
// Cast string to RegExp
if(query.match(/^\/.*\/$/)) {
var casted = query.substr(1, query.length-2);
return !!_current.name.match(new RegExp(casted));
// Transform to state notation
} else {
var transformed = query
.split('.')
.map(function(item) {
if(item === '*') {
return '[a-zA-Z0-9_]*';
} else if(item === '**') {
return '[a-zA-Z0-9_\\.]*';
} else {
return item;
}
})
.join('\\.');
return !!_current.name.match(new RegExp(transformed));
}
}
// Non-matching
return false;
} | [
"function",
"(",
"query",
",",
"params",
")",
"{",
"query",
"=",
"query",
"||",
"''",
";",
"// No state",
"if",
"(",
"!",
"_current",
")",
"{",
"return",
"false",
";",
"// Use RegExp matching",
"}",
"else",
"if",
"(",
"query",
"instanceof",
"RegExp",
")",
"{",
"return",
"!",
"!",
"_current",
".",
"name",
".",
"match",
"(",
"query",
")",
";",
"// String; state dot-notation",
"}",
"else",
"if",
"(",
"typeof",
"query",
"===",
"'string'",
")",
"{",
"// Cast string to RegExp",
"if",
"(",
"query",
".",
"match",
"(",
"/",
"^\\/.*\\/$",
"/",
")",
")",
"{",
"var",
"casted",
"=",
"query",
".",
"substr",
"(",
"1",
",",
"query",
".",
"length",
"-",
"2",
")",
";",
"return",
"!",
"!",
"_current",
".",
"name",
".",
"match",
"(",
"new",
"RegExp",
"(",
"casted",
")",
")",
";",
"// Transform to state notation",
"}",
"else",
"{",
"var",
"transformed",
"=",
"query",
".",
"split",
"(",
"'.'",
")",
".",
"map",
"(",
"function",
"(",
"item",
")",
"{",
"if",
"(",
"item",
"===",
"'*'",
")",
"{",
"return",
"'[a-zA-Z0-9_]*'",
";",
"}",
"else",
"if",
"(",
"item",
"===",
"'**'",
")",
"{",
"return",
"'[a-zA-Z0-9_\\\\.]*'",
";",
"}",
"else",
"{",
"return",
"item",
";",
"}",
"}",
")",
".",
"join",
"(",
"'\\\\.'",
")",
";",
"return",
"!",
"!",
"_current",
".",
"name",
".",
"match",
"(",
"new",
"RegExp",
"(",
"transformed",
")",
")",
";",
"}",
"}",
"// Non-matching",
"return",
"false",
";",
"}"
]
| Check query against current state
@param {Mixed} query A string using state notation or a RegExp
@param {Object} params A parameters data object
@return {Boolean} A true if state is parent to current state | [
"Check",
"query",
"against",
"current",
"state"
]
| 5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b | https://github.com/henrytseng/angular-state-router/blob/5b8147d5f5fe8a8e8453dddf61fe0b01fe5b5e9b/src/services/state-router.js#L635-L675 |
|
45,291 | bikejs/bike | src/bike.js | support | function support (name) {
try {
return BIKE.require(BIKEname + '-' + name);
}
catch (e) {
return BIKE.require(name);
}
} | javascript | function support (name) {
try {
return BIKE.require(BIKEname + '-' + name);
}
catch (e) {
return BIKE.require(name);
}
} | [
"function",
"support",
"(",
"name",
")",
"{",
"try",
"{",
"return",
"BIKE",
".",
"require",
"(",
"BIKEname",
"+",
"'-'",
"+",
"name",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"BIKE",
".",
"require",
"(",
"name",
")",
";",
"}",
"}"
]
| Retreive a submodule
@param {String} name Submodule's name
@return {Mixied} Found object | [
"Retreive",
"a",
"submodule"
]
| 90c014b7a2cf8f8b92c945b934db526c2ae7e37c | https://github.com/bikejs/bike/blob/90c014b7a2cf8f8b92c945b934db526c2ae7e37c/src/bike.js#L20-L27 |
45,292 | nodejitsu/contour | pagelets/button.js | define | function define() {
var type = this.data.type || this.defaults.type
, collection = this.collection;
this.data.use = collection[type].class;
this.data.text = this.data.text || collection[type].text;
this.data.href = this.data.href || collection[type].href;
return this;
} | javascript | function define() {
var type = this.data.type || this.defaults.type
, collection = this.collection;
this.data.use = collection[type].class;
this.data.text = this.data.text || collection[type].text;
this.data.href = this.data.href || collection[type].href;
return this;
} | [
"function",
"define",
"(",
")",
"{",
"var",
"type",
"=",
"this",
".",
"data",
".",
"type",
"||",
"this",
".",
"defaults",
".",
"type",
",",
"collection",
"=",
"this",
".",
"collection",
";",
"this",
".",
"data",
".",
"use",
"=",
"collection",
"[",
"type",
"]",
".",
"class",
";",
"this",
".",
"data",
".",
"text",
"=",
"this",
".",
"data",
".",
"text",
"||",
"collection",
"[",
"type",
"]",
".",
"text",
";",
"this",
".",
"data",
".",
"href",
"=",
"this",
".",
"data",
".",
"href",
"||",
"collection",
"[",
"type",
"]",
".",
"href",
";",
"return",
"this",
";",
"}"
]
| Define the class and text that are on the button. Called by set on default.
@returns {Pagelet}
@api private | [
"Define",
"the",
"class",
"and",
"text",
"that",
"are",
"on",
"the",
"button",
".",
"Called",
"by",
"set",
"on",
"default",
"."
]
| 0828e9bd25ef1eeb97ea231c447118d9867021b6 | https://github.com/nodejitsu/contour/blob/0828e9bd25ef1eeb97ea231c447118d9867021b6/pagelets/button.js#L62-L71 |
45,293 | chapmanu/hb | lib/services/wordpress/stream.js | function(service, credentials, accounts, keywords) {
Stream.call(this, service, credentials, accounts, keywords);
// Initialize responder
this.responder = new Responder();
} | javascript | function(service, credentials, accounts, keywords) {
Stream.call(this, service, credentials, accounts, keywords);
// Initialize responder
this.responder = new Responder();
} | [
"function",
"(",
"service",
",",
"credentials",
",",
"accounts",
",",
"keywords",
")",
"{",
"Stream",
".",
"call",
"(",
"this",
",",
"service",
",",
"credentials",
",",
"accounts",
",",
"keywords",
")",
";",
"// Initialize responder",
"this",
".",
"responder",
"=",
"new",
"Responder",
"(",
")",
";",
"}"
]
| Manages the streaming connection to Wordpress
@constructor
@extends Stream | [
"Manages",
"the",
"streaming",
"connection",
"to",
"Wordpress"
]
| 5edd8de89c7c5fdffc3df0c627513889220f7d51 | https://github.com/chapmanu/hb/blob/5edd8de89c7c5fdffc3df0c627513889220f7d51/lib/services/wordpress/stream.js#L13-L19 |
|
45,294 | feilaoda/power | public/javascripts/vendor/javascripts/moment.js | getLangDefinition | function getLangDefinition(m) {
var langKey = (typeof m === 'string') && m ||
m && m._lang ||
null;
return langKey ? (languages[langKey] || loadLang(langKey)) : moment;
} | javascript | function getLangDefinition(m) {
var langKey = (typeof m === 'string') && m ||
m && m._lang ||
null;
return langKey ? (languages[langKey] || loadLang(langKey)) : moment;
} | [
"function",
"getLangDefinition",
"(",
"m",
")",
"{",
"var",
"langKey",
"=",
"(",
"typeof",
"m",
"===",
"'string'",
")",
"&&",
"m",
"||",
"m",
"&&",
"m",
".",
"_lang",
"||",
"null",
";",
"return",
"langKey",
"?",
"(",
"languages",
"[",
"langKey",
"]",
"||",
"loadLang",
"(",
"langKey",
")",
")",
":",
"moment",
";",
"}"
]
| Determines which language definition to use and returns it. With no parameters, it will return the global language. If you pass in a language key, such as 'en', it will return the definition for 'en', so long as 'en' has already been loaded using moment.lang. If you pass in a moment or duration instance, it will decide the language based on that, or default to the global language. | [
"Determines",
"which",
"language",
"definition",
"to",
"use",
"and",
"returns",
"it",
".",
"With",
"no",
"parameters",
"it",
"will",
"return",
"the",
"global",
"language",
".",
"If",
"you",
"pass",
"in",
"a",
"language",
"key",
"such",
"as",
"en",
"it",
"will",
"return",
"the",
"definition",
"for",
"en",
"so",
"long",
"as",
"en",
"has",
"already",
"been",
"loaded",
"using",
"moment",
".",
"lang",
".",
"If",
"you",
"pass",
"in",
"a",
"moment",
"or",
"duration",
"instance",
"it",
"will",
"decide",
"the",
"language",
"based",
"on",
"that",
"or",
"default",
"to",
"the",
"global",
"language",
"."
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/moment.js#L414-L420 |
45,295 | godaddy/node-gd-assets | lib/config.js | _flatten | function _flatten(groups, groupName, alreadySeen)
{
alreadySeen = alreadySeen || [];
var ret = {};
// Intialize each key to empty so we don't have to check if they exist later
HANDLER_KEYS.forEach(function(key) {
ret[key] = [];
});
var thisGroup = groups[groupName];
if ( !thisGroup )
throw new Error('Unknown group: ' + groupName);
// If this group includes other groups, add them first
if ( thisGroup.include )
{
thisGroup.include.forEach(function(subGroupName) {
if ( alreadySeen.indexOf(subGroupName) >= 0 )
{
// Circular dependency and this group has already been included elsewhere
return;
}
else
{
alreadySeen.push(subGroupName);
}
var subGroup = _flatten(groups, subGroupName, alreadySeen);
if ( !subGroup )
throw new Error('Unknown subgroup:' +subGroupName);
HANDLER_KEYS.forEach(function(key) {
if ( subGroup[key] )
{
_mergeArrayInPlace(ret[key], subGroup[key]);
}
});
});
}
// Then add the individual files for this group at the end
HANDLER_KEYS.forEach(function(key) {
if ( thisGroup[key] )
{
_mergeArrayInPlace( ret[key], thisGroup[key] );
}
});
return ret;
} | javascript | function _flatten(groups, groupName, alreadySeen)
{
alreadySeen = alreadySeen || [];
var ret = {};
// Intialize each key to empty so we don't have to check if they exist later
HANDLER_KEYS.forEach(function(key) {
ret[key] = [];
});
var thisGroup = groups[groupName];
if ( !thisGroup )
throw new Error('Unknown group: ' + groupName);
// If this group includes other groups, add them first
if ( thisGroup.include )
{
thisGroup.include.forEach(function(subGroupName) {
if ( alreadySeen.indexOf(subGroupName) >= 0 )
{
// Circular dependency and this group has already been included elsewhere
return;
}
else
{
alreadySeen.push(subGroupName);
}
var subGroup = _flatten(groups, subGroupName, alreadySeen);
if ( !subGroup )
throw new Error('Unknown subgroup:' +subGroupName);
HANDLER_KEYS.forEach(function(key) {
if ( subGroup[key] )
{
_mergeArrayInPlace(ret[key], subGroup[key]);
}
});
});
}
// Then add the individual files for this group at the end
HANDLER_KEYS.forEach(function(key) {
if ( thisGroup[key] )
{
_mergeArrayInPlace( ret[key], thisGroup[key] );
}
});
return ret;
} | [
"function",
"_flatten",
"(",
"groups",
",",
"groupName",
",",
"alreadySeen",
")",
"{",
"alreadySeen",
"=",
"alreadySeen",
"||",
"[",
"]",
";",
"var",
"ret",
"=",
"{",
"}",
";",
"// Intialize each key to empty so we don't have to check if they exist later",
"HANDLER_KEYS",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"ret",
"[",
"key",
"]",
"=",
"[",
"]",
";",
"}",
")",
";",
"var",
"thisGroup",
"=",
"groups",
"[",
"groupName",
"]",
";",
"if",
"(",
"!",
"thisGroup",
")",
"throw",
"new",
"Error",
"(",
"'Unknown group: '",
"+",
"groupName",
")",
";",
"// If this group includes other groups, add them first",
"if",
"(",
"thisGroup",
".",
"include",
")",
"{",
"thisGroup",
".",
"include",
".",
"forEach",
"(",
"function",
"(",
"subGroupName",
")",
"{",
"if",
"(",
"alreadySeen",
".",
"indexOf",
"(",
"subGroupName",
")",
">=",
"0",
")",
"{",
"// Circular dependency and this group has already been included elsewhere",
"return",
";",
"}",
"else",
"{",
"alreadySeen",
".",
"push",
"(",
"subGroupName",
")",
";",
"}",
"var",
"subGroup",
"=",
"_flatten",
"(",
"groups",
",",
"subGroupName",
",",
"alreadySeen",
")",
";",
"if",
"(",
"!",
"subGroup",
")",
"throw",
"new",
"Error",
"(",
"'Unknown subgroup:'",
"+",
"subGroupName",
")",
";",
"HANDLER_KEYS",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"subGroup",
"[",
"key",
"]",
")",
"{",
"_mergeArrayInPlace",
"(",
"ret",
"[",
"key",
"]",
",",
"subGroup",
"[",
"key",
"]",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
"// Then add the individual files for this group at the end",
"HANDLER_KEYS",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"thisGroup",
"[",
"key",
"]",
")",
"{",
"_mergeArrayInPlace",
"(",
"ret",
"[",
"key",
"]",
",",
"thisGroup",
"[",
"key",
"]",
")",
";",
"}",
"}",
")",
";",
"return",
"ret",
";",
"}"
]
| Flatten a single group into a list of files required for it | [
"Flatten",
"a",
"single",
"group",
"into",
"a",
"list",
"of",
"files",
"required",
"for",
"it"
]
| 14723940592090855b95ea5d20abe6291f1a5696 | https://github.com/godaddy/node-gd-assets/blob/14723940592090855b95ea5d20abe6291f1a5696/lib/config.js#L117-L168 |
45,296 | godaddy/node-gd-assets | lib/config.js | resolveFile | function resolveFile(baseDirs, addType, fileName, type, cb)
{
// The label this file will have in the output
// For hbs views, this is the name that it will be save as into the template array.
var label = pathlib.basename(fileName);
// Label can be overridden with entries of the form: "label:file-name-or-path"
var idx = fileName.indexOf(':');
if ( idx > 0 )
{
label = fileName.substr(0,idx);
fileName = fileName.substr(idx+1);
}
// Construct a list of paths to check
var paths = [];
baseDirs.forEach(function(baseDir) {
if ( addType )
baseDir += '/'+type;
// Search for exact filename
paths.push(pathlib.resolve(baseDir,fileName));
// And with the type as an extension
paths.push(pathlib.resolve(baseDir,fileName+'.'+type));
// Special case 'view' because it used to mean hbs
if ( type == 'view' )
{
VIEW_TYPES.forEach(function(altType) {
paths.push(pathlib.resolve(baseDir,fileName+'.'+altType));
});
}
});
// Async
if ( cb )
{
async.detectSeries(paths, fs.exists, function(result) {
if ( result )
return cb(undefined, label+':'+result);
else
return cb(new Error(errStr));
});
}
else
{
// Sync
for ( i=0 ; i < paths.length ; i++ )
{
if ( fs.existsSync(paths[i]) )
{
return label+':'+paths[i];
}
}
throw new Error('Unable to find source ' + type + ' file for ' + fileName + ' in ' + paths.join(', '));
}
} | javascript | function resolveFile(baseDirs, addType, fileName, type, cb)
{
// The label this file will have in the output
// For hbs views, this is the name that it will be save as into the template array.
var label = pathlib.basename(fileName);
// Label can be overridden with entries of the form: "label:file-name-or-path"
var idx = fileName.indexOf(':');
if ( idx > 0 )
{
label = fileName.substr(0,idx);
fileName = fileName.substr(idx+1);
}
// Construct a list of paths to check
var paths = [];
baseDirs.forEach(function(baseDir) {
if ( addType )
baseDir += '/'+type;
// Search for exact filename
paths.push(pathlib.resolve(baseDir,fileName));
// And with the type as an extension
paths.push(pathlib.resolve(baseDir,fileName+'.'+type));
// Special case 'view' because it used to mean hbs
if ( type == 'view' )
{
VIEW_TYPES.forEach(function(altType) {
paths.push(pathlib.resolve(baseDir,fileName+'.'+altType));
});
}
});
// Async
if ( cb )
{
async.detectSeries(paths, fs.exists, function(result) {
if ( result )
return cb(undefined, label+':'+result);
else
return cb(new Error(errStr));
});
}
else
{
// Sync
for ( i=0 ; i < paths.length ; i++ )
{
if ( fs.existsSync(paths[i]) )
{
return label+':'+paths[i];
}
}
throw new Error('Unable to find source ' + type + ' file for ' + fileName + ' in ' + paths.join(', '));
}
} | [
"function",
"resolveFile",
"(",
"baseDirs",
",",
"addType",
",",
"fileName",
",",
"type",
",",
"cb",
")",
"{",
"// The label this file will have in the output",
"// For hbs views, this is the name that it will be save as into the template array.",
"var",
"label",
"=",
"pathlib",
".",
"basename",
"(",
"fileName",
")",
";",
"// Label can be overridden with entries of the form: \"label:file-name-or-path\"",
"var",
"idx",
"=",
"fileName",
".",
"indexOf",
"(",
"':'",
")",
";",
"if",
"(",
"idx",
">",
"0",
")",
"{",
"label",
"=",
"fileName",
".",
"substr",
"(",
"0",
",",
"idx",
")",
";",
"fileName",
"=",
"fileName",
".",
"substr",
"(",
"idx",
"+",
"1",
")",
";",
"}",
"// Construct a list of paths to check",
"var",
"paths",
"=",
"[",
"]",
";",
"baseDirs",
".",
"forEach",
"(",
"function",
"(",
"baseDir",
")",
"{",
"if",
"(",
"addType",
")",
"baseDir",
"+=",
"'/'",
"+",
"type",
";",
"// Search for exact filename",
"paths",
".",
"push",
"(",
"pathlib",
".",
"resolve",
"(",
"baseDir",
",",
"fileName",
")",
")",
";",
"// And with the type as an extension",
"paths",
".",
"push",
"(",
"pathlib",
".",
"resolve",
"(",
"baseDir",
",",
"fileName",
"+",
"'.'",
"+",
"type",
")",
")",
";",
"// Special case 'view' because it used to mean hbs",
"if",
"(",
"type",
"==",
"'view'",
")",
"{",
"VIEW_TYPES",
".",
"forEach",
"(",
"function",
"(",
"altType",
")",
"{",
"paths",
".",
"push",
"(",
"pathlib",
".",
"resolve",
"(",
"baseDir",
",",
"fileName",
"+",
"'.'",
"+",
"altType",
")",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"// Async",
"if",
"(",
"cb",
")",
"{",
"async",
".",
"detectSeries",
"(",
"paths",
",",
"fs",
".",
"exists",
",",
"function",
"(",
"result",
")",
"{",
"if",
"(",
"result",
")",
"return",
"cb",
"(",
"undefined",
",",
"label",
"+",
"':'",
"+",
"result",
")",
";",
"else",
"return",
"cb",
"(",
"new",
"Error",
"(",
"errStr",
")",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"// Sync",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"paths",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"paths",
"[",
"i",
"]",
")",
")",
"{",
"return",
"label",
"+",
"':'",
"+",
"paths",
"[",
"i",
"]",
";",
"}",
"}",
"throw",
"new",
"Error",
"(",
"'Unable to find source '",
"+",
"type",
"+",
"' file for '",
"+",
"fileName",
"+",
"' in '",
"+",
"paths",
".",
"join",
"(",
"', '",
")",
")",
";",
"}",
"}"
]
| Resolve a file name into an absolute path Async if called with a cb, synchronous if not | [
"Resolve",
"a",
"file",
"name",
"into",
"an",
"absolute",
"path",
"Async",
"if",
"called",
"with",
"a",
"cb",
"synchronous",
"if",
"not"
]
| 14723940592090855b95ea5d20abe6291f1a5696 | https://github.com/godaddy/node-gd-assets/blob/14723940592090855b95ea5d20abe6291f1a5696/lib/config.js#L184-L242 |
45,297 | Krinkle/node-colorfactory | src/ColorHelper.js | makeStrProtoFn | function makeStrProtoFn(method) {
return function () {
// Convert `arguments` into an array (usually empty or has 1 parameter)
var args = slice.call(arguments, 0);
// Add the current string as the first argument
args.unshift(this);
return ColorHelper[method].apply(ColorHelper, args);
};
} | javascript | function makeStrProtoFn(method) {
return function () {
// Convert `arguments` into an array (usually empty or has 1 parameter)
var args = slice.call(arguments, 0);
// Add the current string as the first argument
args.unshift(this);
return ColorHelper[method].apply(ColorHelper, args);
};
} | [
"function",
"makeStrProtoFn",
"(",
"method",
")",
"{",
"return",
"function",
"(",
")",
"{",
"// Convert `arguments` into an array (usually empty or has 1 parameter)",
"var",
"args",
"=",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
";",
"// Add the current string as the first argument",
"args",
".",
"unshift",
"(",
"this",
")",
";",
"return",
"ColorHelper",
"[",
"method",
"]",
".",
"apply",
"(",
"ColorHelper",
",",
"args",
")",
";",
"}",
";",
"}"
]
| Can't be used inline in the for-loop, because of variable scope.
Otherwise all methods would be pointing to the method as put in
the variable that lives on until after the loop itself. | [
"Can",
"t",
"be",
"used",
"inline",
"in",
"the",
"for",
"-",
"loop",
"because",
"of",
"variable",
"scope",
".",
"Otherwise",
"all",
"methods",
"would",
"be",
"pointing",
"to",
"the",
"method",
"as",
"put",
"in",
"the",
"variable",
"that",
"lives",
"on",
"until",
"after",
"the",
"loop",
"itself",
"."
]
| 4c9cec8f3f8e95a3fa402233ceef2dd9c2b040b0 | https://github.com/Krinkle/node-colorfactory/blob/4c9cec8f3f8e95a3fa402233ceef2dd9c2b040b0/src/ColorHelper.js#L208-L216 |
45,298 | naomiaro/fade-curves | index.js | sCurve | function sCurve(length, rotation) {
var curve = new Float32Array(length),
i,
phase = rotation > 0 ? Math.PI / 2 : -(Math.PI / 2);
for (i = 0; i < length; ++i) {
curve[i] = Math.sin(Math.PI * i / length - phase) / 2 + 0.5;
}
return curve;
} | javascript | function sCurve(length, rotation) {
var curve = new Float32Array(length),
i,
phase = rotation > 0 ? Math.PI / 2 : -(Math.PI / 2);
for (i = 0; i < length; ++i) {
curve[i] = Math.sin(Math.PI * i / length - phase) / 2 + 0.5;
}
return curve;
} | [
"function",
"sCurve",
"(",
"length",
",",
"rotation",
")",
"{",
"var",
"curve",
"=",
"new",
"Float32Array",
"(",
"length",
")",
",",
"i",
",",
"phase",
"=",
"rotation",
">",
"0",
"?",
"Math",
".",
"PI",
"/",
"2",
":",
"-",
"(",
"Math",
".",
"PI",
"/",
"2",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"++",
"i",
")",
"{",
"curve",
"[",
"i",
"]",
"=",
"Math",
".",
"sin",
"(",
"Math",
".",
"PI",
"*",
"i",
"/",
"length",
"-",
"phase",
")",
"/",
"2",
"+",
"0.5",
";",
"}",
"return",
"curve",
";",
"}"
]
| creating a curve to simulate an S-curve with setValueCurveAtTime. | [
"creating",
"a",
"curve",
"to",
"simulate",
"an",
"S",
"-",
"curve",
"with",
"setValueCurveAtTime",
"."
]
| 795ed73fe0cbc110287c2d48a01afdb6b4a49512 | https://github.com/naomiaro/fade-curves/blob/795ed73fe0cbc110287c2d48a01afdb6b4a49512/index.js#L47-L56 |
45,299 | naomiaro/fade-curves | index.js | logarithmic | function logarithmic(length, base, rotation) {
var curve = new Float32Array(length),
index,
x = 0,
i;
for (i = 0; i < length; i++) {
//index for the curve array.
index = rotation > 0 ? i : length - 1 - i;
x = i / length;
curve[index] = Math.log(1 + base * x) / Math.log(1 + base);
}
return curve;
} | javascript | function logarithmic(length, base, rotation) {
var curve = new Float32Array(length),
index,
x = 0,
i;
for (i = 0; i < length; i++) {
//index for the curve array.
index = rotation > 0 ? i : length - 1 - i;
x = i / length;
curve[index] = Math.log(1 + base * x) / Math.log(1 + base);
}
return curve;
} | [
"function",
"logarithmic",
"(",
"length",
",",
"base",
",",
"rotation",
")",
"{",
"var",
"curve",
"=",
"new",
"Float32Array",
"(",
"length",
")",
",",
"index",
",",
"x",
"=",
"0",
",",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"//index for the curve array.",
"index",
"=",
"rotation",
">",
"0",
"?",
"i",
":",
"length",
"-",
"1",
"-",
"i",
";",
"x",
"=",
"i",
"/",
"length",
";",
"curve",
"[",
"index",
"]",
"=",
"Math",
".",
"log",
"(",
"1",
"+",
"base",
"*",
"x",
")",
"/",
"Math",
".",
"log",
"(",
"1",
"+",
"base",
")",
";",
"}",
"return",
"curve",
";",
"}"
]
| creating a curve to simulate a logarithmic curve with setValueCurveAtTime. | [
"creating",
"a",
"curve",
"to",
"simulate",
"a",
"logarithmic",
"curve",
"with",
"setValueCurveAtTime",
"."
]
| 795ed73fe0cbc110287c2d48a01afdb6b4a49512 | https://github.com/naomiaro/fade-curves/blob/795ed73fe0cbc110287c2d48a01afdb6b4a49512/index.js#L59-L74 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.