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
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
C2FO/comb
|
lib/base/string.js
|
format
|
function format(str, obj) {
if (obj instanceof Array) {
var i = 0, len = obj.length;
//find the matches
return str.replace(FORMAT_REGEX, function (m, format, type) {
var replacer, ret;
if (i < len) {
replacer = obj[i++];
} else {
//we are out of things to replace with so
//just return the match?
return m;
}
if (m === "%s" || m === "%d" || m === "%D") {
//fast path!
ret = replacer + "";
} else if (m === "%Z") {
ret = replacer.toUTCString();
} else if (m === "%j") {
try {
ret = JSON.stringify(replacer);
} catch (e) {
throw new Error("comb.string.format : Unable to parse json from ", replacer);
}
} else {
format = format.replace(/^\[|\]$/g, "");
switch (type) {
case "s":
ret = formatString(replacer, format);
break;
case "d":
ret = formatNumber(replacer, format);
break;
case "j":
ret = formatObject(replacer, format);
break;
case "D":
ret = getDate().date.format(replacer, format);
break;
case "Z":
ret = getDate().date.format(replacer, format, true);
break;
}
}
return ret;
});
} else if (isHash(obj)) {
return str.replace(INTERP_REGEX, function (m, format, value) {
value = obj[value];
if (!misc.isUndefined(value)) {
if (format) {
if (comb.isString(value)) {
return formatString(value, format);
} else if (typeof value === "number") {
return formatNumber(value, format);
} else if (getDate().isDate(value)) {
return getDate().date.format(value, format);
} else if (typeof value === "object") {
return formatObject(value, format);
}
} else {
return "" + value;
}
}
return m;
});
} else {
var args = pSlice.call(arguments).slice(1);
return format(str, args);
}
}
|
javascript
|
function format(str, obj) {
if (obj instanceof Array) {
var i = 0, len = obj.length;
//find the matches
return str.replace(FORMAT_REGEX, function (m, format, type) {
var replacer, ret;
if (i < len) {
replacer = obj[i++];
} else {
//we are out of things to replace with so
//just return the match?
return m;
}
if (m === "%s" || m === "%d" || m === "%D") {
//fast path!
ret = replacer + "";
} else if (m === "%Z") {
ret = replacer.toUTCString();
} else if (m === "%j") {
try {
ret = JSON.stringify(replacer);
} catch (e) {
throw new Error("comb.string.format : Unable to parse json from ", replacer);
}
} else {
format = format.replace(/^\[|\]$/g, "");
switch (type) {
case "s":
ret = formatString(replacer, format);
break;
case "d":
ret = formatNumber(replacer, format);
break;
case "j":
ret = formatObject(replacer, format);
break;
case "D":
ret = getDate().date.format(replacer, format);
break;
case "Z":
ret = getDate().date.format(replacer, format, true);
break;
}
}
return ret;
});
} else if (isHash(obj)) {
return str.replace(INTERP_REGEX, function (m, format, value) {
value = obj[value];
if (!misc.isUndefined(value)) {
if (format) {
if (comb.isString(value)) {
return formatString(value, format);
} else if (typeof value === "number") {
return formatNumber(value, format);
} else if (getDate().isDate(value)) {
return getDate().date.format(value, format);
} else if (typeof value === "object") {
return formatObject(value, format);
}
} else {
return "" + value;
}
}
return m;
});
} else {
var args = pSlice.call(arguments).slice(1);
return format(str, args);
}
}
|
[
"function",
"format",
"(",
"str",
",",
"obj",
")",
"{",
"if",
"(",
"obj",
"instanceof",
"Array",
")",
"{",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"obj",
".",
"length",
";",
"return",
"str",
".",
"replace",
"(",
"FORMAT_REGEX",
",",
"function",
"(",
"m",
",",
"format",
",",
"type",
")",
"{",
"var",
"replacer",
",",
"ret",
";",
"if",
"(",
"i",
"<",
"len",
")",
"{",
"replacer",
"=",
"obj",
"[",
"i",
"++",
"]",
";",
"}",
"else",
"{",
"return",
"m",
";",
"}",
"if",
"(",
"m",
"===",
"\"%s\"",
"||",
"m",
"===",
"\"%d\"",
"||",
"m",
"===",
"\"%D\"",
")",
"{",
"ret",
"=",
"replacer",
"+",
"\"\"",
";",
"}",
"else",
"if",
"(",
"m",
"===",
"\"%Z\"",
")",
"{",
"ret",
"=",
"replacer",
".",
"toUTCString",
"(",
")",
";",
"}",
"else",
"if",
"(",
"m",
"===",
"\"%j\"",
")",
"{",
"try",
"{",
"ret",
"=",
"JSON",
".",
"stringify",
"(",
"replacer",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"comb.string.format : Unable to parse json from \"",
",",
"replacer",
")",
";",
"}",
"}",
"else",
"{",
"format",
"=",
"format",
".",
"replace",
"(",
"/",
"^\\[|\\]$",
"/",
"g",
",",
"\"\"",
")",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"\"s\"",
":",
"ret",
"=",
"formatString",
"(",
"replacer",
",",
"format",
")",
";",
"break",
";",
"case",
"\"d\"",
":",
"ret",
"=",
"formatNumber",
"(",
"replacer",
",",
"format",
")",
";",
"break",
";",
"case",
"\"j\"",
":",
"ret",
"=",
"formatObject",
"(",
"replacer",
",",
"format",
")",
";",
"break",
";",
"case",
"\"D\"",
":",
"ret",
"=",
"getDate",
"(",
")",
".",
"date",
".",
"format",
"(",
"replacer",
",",
"format",
")",
";",
"break",
";",
"case",
"\"Z\"",
":",
"ret",
"=",
"getDate",
"(",
")",
".",
"date",
".",
"format",
"(",
"replacer",
",",
"format",
",",
"true",
")",
";",
"break",
";",
"}",
"}",
"return",
"ret",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"isHash",
"(",
"obj",
")",
")",
"{",
"return",
"str",
".",
"replace",
"(",
"INTERP_REGEX",
",",
"function",
"(",
"m",
",",
"format",
",",
"value",
")",
"{",
"value",
"=",
"obj",
"[",
"value",
"]",
";",
"if",
"(",
"!",
"misc",
".",
"isUndefined",
"(",
"value",
")",
")",
"{",
"if",
"(",
"format",
")",
"{",
"if",
"(",
"comb",
".",
"isString",
"(",
"value",
")",
")",
"{",
"return",
"formatString",
"(",
"value",
",",
"format",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"value",
"===",
"\"number\"",
")",
"{",
"return",
"formatNumber",
"(",
"value",
",",
"format",
")",
";",
"}",
"else",
"if",
"(",
"getDate",
"(",
")",
".",
"isDate",
"(",
"value",
")",
")",
"{",
"return",
"getDate",
"(",
")",
".",
"date",
".",
"format",
"(",
"value",
",",
"format",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"value",
"===",
"\"object\"",
")",
"{",
"return",
"formatObject",
"(",
"value",
",",
"format",
")",
";",
"}",
"}",
"else",
"{",
"return",
"\"\"",
"+",
"value",
";",
"}",
"}",
"return",
"m",
";",
"}",
")",
";",
"}",
"else",
"{",
"var",
"args",
"=",
"pSlice",
".",
"call",
"(",
"arguments",
")",
".",
"slice",
"(",
"1",
")",
";",
"return",
"format",
"(",
"str",
",",
"args",
")",
";",
"}",
"}"
] |
Formats a string with the specified format
Format `String`s
```
comb.string.format("%s", "Hello"); // "Hello"
comb.string.format("%10s", "Hello"); // " Hello"
comb.string.format("%-10s", "Hello"); // ""Hello ""
comb.string.format('%.10s', "Hello"); //".....Hello"
comb.string.format('%-!10s', "Hello"); //"Hello!!!!!"
comb.string.format("%-.10s%s!", "Hello", "World"); //"Hello.....World!"
```
Formatting Numbers
```
comb.string.format('%d', 10); //"10"
//setting precision
comb.string.format('%.2d', 10); //"10.00"
//specifying width
comb.string.format('%5d', 10); //" 10"
//Signed
comb.string.format('%+d', 10); //"+10"
comb.string.format('%+d', -10); //"-10"
comb.string.format('% d', 10); //" 10"
comb.string.format('% d', -10); //"-10"
//width
comb.string.format('%5d', 10); //" 10"
//width and precision
comb.string.format('%6.2d', 10); //" 10.00"
//signed, width and precision
comb.string.format('%+ 7.2d', 10); //" +10.00"
comb.string.format('%+ 7.2d', -10); //" -10.00"
comb.string.format('%+07.2d', 10); //"+010.00"
comb.string.format('%+07.2d', -10); //"-010.00"
comb.string.format('% 7.2d', 10); //" 10.00"
comb.string.format('% 7.2d', -10); //" -10.00"
comb.string.format('% 7.2d', 10); //" 10.00"
comb.string.format('% 7.2d', -10); //" -10.00"
//use a 0 as padding
comb.string.format('%010d', 10); //"0000000010"
//use an ! as padding
comb.string.format('%!10d', 10); //"!!!!!!!!10"
//left justify signed ! as padding and a width of 10
comb.string.format('%-+!10d', 10); //"+10!!!!!!!"
```
Formatting dates
```
comb.string.format("%[h:mm a]D", new Date(2014, 05, 04, 7,6,1)); // 7:06 AM - local -
comb.string.format("%[h:mm a]Z", new Date(2014, 05, 04, 7,6,1)); //12:06 PM - UTC
comb.string.format("%[yyyy-MM-dd]D", new Date(2014, 05, 04, 7,6,1)); // 2014-06-04 - local
comb.string.format("%[yyyy-MM-dd]Z", new Date(2014, 05, 04, 7,6,1)); // 2014-06-04 - UTC
```
Formatting Objects
```
//When using object formats they must be in an array otherwise
//format will try to interpolate the properties into the string.
comb.string.format("%j", [{a : "b"}]) // '{"a":"b"}'
//Specifying spacing
comb.string.format("%4j", [{a : "b"}]) // '{\n "a": "b"\n}'
```
String interpolation
```
comb.string.format("{hello}, {world}", {hello : "Hello", world : "World"); //"Hello, World";
comb.string.format("{[.2]min}...{[.2]max}", {min: 1, max: 10}); //"1.00...10.00"
```
@param {String} str the string to format, if you want to use a spacing character as padding (other than \\s) then put your format in brackets.
<ol>
<li>String Formats %[options]s</li>
<ul>
<li>- : left justified</li>
<li>Char : padding character <b>Excludes d,j,s</b></li>
<li>Number : width</li>
</ul>
</li>
<li>Number Formats %[options]d</li>
<ul>
<li>`-` : left justified</li>
<li>`+` or `<space>` : signed number if space is used the number will use a extra `<space>` instead of a `+`</li>
<li>`<Char>` : padding character <b>Excludes d,j,s</b></li>
<li>`Number` : width</li>
<li>`.Number`: specify the precision of the number</li>
</ul>
</li>
<li>Object Formats %[options]j</li>
<ul>
<li>Number : spacing for object properties.</li>
</ul>
</li>
</ol>
@param {Object|Array|Arguments...} obj the parameters to replace in the string
if an array is passed then the array is used sequentially
if an object is passed then the object keys are used
if a variable number of args are passed then they are used like an array
@returns {String} the formatted string
@memberOf comb.string
@static
|
[
"Formats",
"a",
"string",
"with",
"the",
"specified",
"format"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/string.js#L326-L397
|
train
|
C2FO/comb
|
lib/base/string.js
|
style
|
function style(str, options) {
var ret = str;
if (options) {
if (ret instanceof Array) {
ret = ret.map(function (s) {
return style(s, options);
});
} else if (options instanceof Array) {
options.forEach(function (option) {
ret = style(ret, option);
});
} else if (options in styles) {
ret = '\x1B[' + styles[options] + 'm' + str + '\x1B[0m';
}
}
return ret;
}
|
javascript
|
function style(str, options) {
var ret = str;
if (options) {
if (ret instanceof Array) {
ret = ret.map(function (s) {
return style(s, options);
});
} else if (options instanceof Array) {
options.forEach(function (option) {
ret = style(ret, option);
});
} else if (options in styles) {
ret = '\x1B[' + styles[options] + 'm' + str + '\x1B[0m';
}
}
return ret;
}
|
[
"function",
"style",
"(",
"str",
",",
"options",
")",
"{",
"var",
"ret",
"=",
"str",
";",
"if",
"(",
"options",
")",
"{",
"if",
"(",
"ret",
"instanceof",
"Array",
")",
"{",
"ret",
"=",
"ret",
".",
"map",
"(",
"function",
"(",
"s",
")",
"{",
"return",
"style",
"(",
"s",
",",
"options",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"options",
"instanceof",
"Array",
")",
"{",
"options",
".",
"forEach",
"(",
"function",
"(",
"option",
")",
"{",
"ret",
"=",
"style",
"(",
"ret",
",",
"option",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"options",
"in",
"styles",
")",
"{",
"ret",
"=",
"'\\x1B['",
"+",
"\\x1B",
"+",
"styles",
"[",
"options",
"]",
"+",
"'m'",
"+",
"str",
";",
"}",
"}",
"'\\x1B[0m'",
"}"
] |
Styles a string according to the specified styles.
@example
//style a string red
comb.string.style('myStr', 'red');
//style a string red and bold
comb.string.style('myStr', ['red', bold]);
@param {String} str The string to style.
@param {String|Array} styles the style or styles to apply to a string.
options include :
<ul>
<li>bold</li>
<li>bright</li>
<li>italic</li>
<li>underline</li>
<li>inverse</li>
<li>crossedOut</li>
<li>blink</li>
<li>red</li>
<li>green</li>
<li>yellow</li>
<li>blue</li>
<li>magenta</li>
<li>cyan</li>
<li>white</li>
<li>redBackground</li>
<li>greenBackground</li>
<li>yellowBackground</li>
<li>blueBackground</li>
<li>magentaBackground</li>
<li>cyanBackground</li>
<li>whiteBackground</li>
<li>grey</li>
<li>black</li>
</ul>
@memberOf comb.string
@static
|
[
"Styles",
"a",
"string",
"according",
"to",
"the",
"specified",
"styles",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/string.js#L473-L489
|
train
|
C2FO/comb
|
lib/base/functions.js
|
applyFirst
|
function applyFirst(method, args) {
args = Array.prototype.slice.call(arguments).slice(1);
if (!isString(method) && !isFunction(method)) {
throw new Error(method + " must be the name of a property or function to execute");
}
if (isString(method)) {
return function () {
var scopeArgs = Array.prototype.slice.call(arguments), scope = scopeArgs.shift();
var func = scope[method];
if (isFunction(func)) {
scopeArgs = args.concat(scopeArgs);
return spreadArgs(func, scopeArgs, scope);
} else {
return func;
}
};
} else {
return function () {
var scopeArgs = Array.prototype.slice.call(arguments), scope = scopeArgs.shift();
scopeArgs = args.concat(scopeArgs);
return spreadArgs(method, scopeArgs, scope);
};
}
}
|
javascript
|
function applyFirst(method, args) {
args = Array.prototype.slice.call(arguments).slice(1);
if (!isString(method) && !isFunction(method)) {
throw new Error(method + " must be the name of a property or function to execute");
}
if (isString(method)) {
return function () {
var scopeArgs = Array.prototype.slice.call(arguments), scope = scopeArgs.shift();
var func = scope[method];
if (isFunction(func)) {
scopeArgs = args.concat(scopeArgs);
return spreadArgs(func, scopeArgs, scope);
} else {
return func;
}
};
} else {
return function () {
var scopeArgs = Array.prototype.slice.call(arguments), scope = scopeArgs.shift();
scopeArgs = args.concat(scopeArgs);
return spreadArgs(method, scopeArgs, scope);
};
}
}
|
[
"function",
"applyFirst",
"(",
"method",
",",
"args",
")",
"{",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
".",
"slice",
"(",
"1",
")",
";",
"if",
"(",
"!",
"isString",
"(",
"method",
")",
"&&",
"!",
"isFunction",
"(",
"method",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"method",
"+",
"\" must be the name of a property or function to execute\"",
")",
";",
"}",
"if",
"(",
"isString",
"(",
"method",
")",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"scopeArgs",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
",",
"scope",
"=",
"scopeArgs",
".",
"shift",
"(",
")",
";",
"var",
"func",
"=",
"scope",
"[",
"method",
"]",
";",
"if",
"(",
"isFunction",
"(",
"func",
")",
")",
"{",
"scopeArgs",
"=",
"args",
".",
"concat",
"(",
"scopeArgs",
")",
";",
"return",
"spreadArgs",
"(",
"func",
",",
"scopeArgs",
",",
"scope",
")",
";",
"}",
"else",
"{",
"return",
"func",
";",
"}",
"}",
";",
"}",
"else",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"scopeArgs",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
",",
"scope",
"=",
"scopeArgs",
".",
"shift",
"(",
")",
";",
"scopeArgs",
"=",
"args",
".",
"concat",
"(",
"scopeArgs",
")",
";",
"return",
"spreadArgs",
"(",
"method",
",",
"scopeArgs",
",",
"scope",
")",
";",
"}",
";",
"}",
"}"
] |
Binds a method to the scope of the first argument.
This is useful if you have async actions and you just want to run a method or retrieve a property on the object.
```
var arr = [], push = comb.applyFirst("push"), length = comb.applyFirst("length");
push(arr, 1, 2,3,4);
console.log(length(arr)); //4
console.log(arr); //1,2,3,4
```
@static
@memberOf comb
@param {String|Function} method the method to invoke in the scope of the first arument.
@param [args] optional args to pass to the callback
@returns {Function} a function that will execute the method in the scope of the first argument.
|
[
"Binds",
"a",
"method",
"to",
"the",
"scope",
"of",
"the",
"first",
"argument",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/functions.js#L97-L120
|
train
|
julesfern/spahql
|
doc-html/src/javascripts/pdoc/prototype.js
|
each
|
function each(iterator) {
for (var i = 0, length = this.length; i < length; i++)
iterator(this[i]);
}
|
javascript
|
function each(iterator) {
for (var i = 0, length = this.length; i < length; i++)
iterator(this[i]);
}
|
[
"function",
"each",
"(",
"iterator",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"length",
"=",
"this",
".",
"length",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"iterator",
"(",
"this",
"[",
"i",
"]",
")",
";",
"}"
] |
use native browser JS 1.6 implementation if available
|
[
"use",
"native",
"browser",
"JS",
"1",
".",
"6",
"implementation",
"if",
"available"
] |
f2eff34e59f5af2e6a48f11f59f99c223b4a2be8
|
https://github.com/julesfern/spahql/blob/f2eff34e59f5af2e6a48f11f59f99c223b4a2be8/doc-html/src/javascripts/pdoc/prototype.js#L968-L971
|
train
|
C2FO/comb
|
lib/async.js
|
asyncForEach
|
function asyncForEach(promise, iterator, scope, limit) {
return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) {
return results.arr;
}));
}
|
javascript
|
function asyncForEach(promise, iterator, scope, limit) {
return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) {
return results.arr;
}));
}
|
[
"function",
"asyncForEach",
"(",
"promise",
",",
"iterator",
",",
"scope",
",",
"limit",
")",
"{",
"return",
"asyncArray",
"(",
"asyncLoop",
"(",
"promise",
",",
"iterator",
",",
"scope",
",",
"limit",
")",
".",
"chain",
"(",
"function",
"(",
"results",
")",
"{",
"return",
"results",
".",
"arr",
";",
"}",
")",
")",
";",
"}"
] |
Loops through the results of an promise. The promise can return an array or just a single item.
```
function asyncArr(){
var ret = new comb.Promise();
process.nextTick(ret.callback.bind(ret, [1,2,3,4,5]);
return ret.promise;
}
comb.async.forEach(asyncArr(), function(){
//do something with it
}).then(function(arr){
console.log(arr); //[1,2,3,4,5];
});
```
You may also return a promise from the iterator block.
```
var myNewArr = [];
comb.async.forEach(asyncArr(), function(item, index){
var ret = new comb.Promise();
process.nextTick(function(){
myNewArr.push([item, index]);
ret.callback();
});
return ret.promise();
}).then(function(){
console.log(myNewArr) //[[1,0], [2,1], [3,2], [4,3], [5,4]]
});
```
@param {comb.Promise|Array} promise the promise or array to loop through
@param {Function} iterator a function to invoke for each item
@param [scope] optional scope to execute the function in.
@return {comb.Promise} a promise that is resolved with the original array.
@static
@memberof comb.async
@name forEach
|
[
"Loops",
"through",
"the",
"results",
"of",
"an",
"promise",
".",
"The",
"promise",
"can",
"return",
"an",
"array",
"or",
"just",
"a",
"single",
"item",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/async.js#L160-L164
|
train
|
C2FO/comb
|
lib/async.js
|
asyncMap
|
function asyncMap(promise, iterator, scope, limit) {
return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) {
return results.loopResults;
}));
}
|
javascript
|
function asyncMap(promise, iterator, scope, limit) {
return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) {
return results.loopResults;
}));
}
|
[
"function",
"asyncMap",
"(",
"promise",
",",
"iterator",
",",
"scope",
",",
"limit",
")",
"{",
"return",
"asyncArray",
"(",
"asyncLoop",
"(",
"promise",
",",
"iterator",
",",
"scope",
",",
"limit",
")",
".",
"chain",
"(",
"function",
"(",
"results",
")",
"{",
"return",
"results",
".",
"loopResults",
";",
"}",
")",
")",
";",
"}"
] |
Loops through the results of an promise resolving with the return value of the iterator function.
The promise can return an array or just a single item.
```
function asyncArr(){
var ret = new comb.Promise();
process.nextTick(ret.callback.bind(ret, [1,2,3,4,5]);
return ret.promise;
}
comb.async.map(asyncArr(), function(item){
return item * 2;
}).then(function(arr){
console.log(arr); //[2,4,6,8,10];
});
```
You may also return a promise from the iterator block.
```
comb.async.map(asyncArr(), function(item, index){
var ret = new comb.Promise();
process.nextTick(function(){
ret.callback(item * 2);
});
return ret.promise();
}).then(function(){
console.log(myNewArr) //[2,4,6,8,10];
});
```
@param {comb.Promise|Array} promise the promise or array to loop through
@param {Function} iterator a function to invoke for each item
@param [scope] optional scope to execute the function in.
@return {comb.Promise} a promise that is resolved with the mapped array.
@static
@memberof comb.async
@name map
|
[
"Loops",
"through",
"the",
"results",
"of",
"an",
"promise",
"resolving",
"with",
"the",
"return",
"value",
"of",
"the",
"iterator",
"function",
".",
"The",
"promise",
"can",
"return",
"an",
"array",
"or",
"just",
"a",
"single",
"item",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/async.js#L209-L213
|
train
|
C2FO/comb
|
lib/async.js
|
asyncFilter
|
function asyncFilter(promise, iterator, scope, limit) {
return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) {
var loopResults = results.loopResults, resultArr = results.arr;
return (isArray(resultArr) ? resultArr : [resultArr]).filter(function (res, i) {
return loopResults[i];
});
}));
}
|
javascript
|
function asyncFilter(promise, iterator, scope, limit) {
return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) {
var loopResults = results.loopResults, resultArr = results.arr;
return (isArray(resultArr) ? resultArr : [resultArr]).filter(function (res, i) {
return loopResults[i];
});
}));
}
|
[
"function",
"asyncFilter",
"(",
"promise",
",",
"iterator",
",",
"scope",
",",
"limit",
")",
"{",
"return",
"asyncArray",
"(",
"asyncLoop",
"(",
"promise",
",",
"iterator",
",",
"scope",
",",
"limit",
")",
".",
"chain",
"(",
"function",
"(",
"results",
")",
"{",
"var",
"loopResults",
"=",
"results",
".",
"loopResults",
",",
"resultArr",
"=",
"results",
".",
"arr",
";",
"return",
"(",
"isArray",
"(",
"resultArr",
")",
"?",
"resultArr",
":",
"[",
"resultArr",
"]",
")",
".",
"filter",
"(",
"function",
"(",
"res",
",",
"i",
")",
"{",
"return",
"loopResults",
"[",
"i",
"]",
";",
"}",
")",
";",
"}",
")",
")",
";",
"}"
] |
Loops through the results of an promise resolving with the filtered array.
The promise can return an array or just a single item.
```
function asyncArr(){
var ret = new comb.Promise();
process.nextTick(ret.callback.bind(ret, [1,2,3,4,5]);
return ret.promise;
}
comb.async.filter(asyncArr(), function(item){
return item % 2;
}).then(function(arr){
console.log(arr); //[1,3,5];
});
```
You may also return a promise from the iterator block.
```
comb.async.filter(asyncArr(), function(item, index){
var ret = new comb.Promise();
process.nextTick(function(){
ret.callback(item % 2);
});
return ret.promise();
}).then(function(){
console.log(myNewArr) //[1,3,5];
})
```
@param {comb.Promise|Array} promise the promise or array to loop through
@param {Function} iterator a function to invoke for each item
@param [scope] optional scope to execute the function in.
@return {comb.Promise} a promise that is resolved with the filtered array.
@static
@memberof comb.async
@name filter
|
[
"Loops",
"through",
"the",
"results",
"of",
"an",
"promise",
"resolving",
"with",
"the",
"filtered",
"array",
".",
"The",
"promise",
"can",
"return",
"an",
"array",
"or",
"just",
"a",
"single",
"item",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/async.js#L258-L265
|
train
|
C2FO/comb
|
lib/async.js
|
asyncEvery
|
function asyncEvery(promise, iterator, scope, limit) {
return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) {
return results.loopResults.every(function (res) {
return !!res;
});
}));
}
|
javascript
|
function asyncEvery(promise, iterator, scope, limit) {
return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) {
return results.loopResults.every(function (res) {
return !!res;
});
}));
}
|
[
"function",
"asyncEvery",
"(",
"promise",
",",
"iterator",
",",
"scope",
",",
"limit",
")",
"{",
"return",
"asyncArray",
"(",
"asyncLoop",
"(",
"promise",
",",
"iterator",
",",
"scope",
",",
"limit",
")",
".",
"chain",
"(",
"function",
"(",
"results",
")",
"{",
"return",
"results",
".",
"loopResults",
".",
"every",
"(",
"function",
"(",
"res",
")",
"{",
"return",
"!",
"!",
"res",
";",
"}",
")",
";",
"}",
")",
")",
";",
"}"
] |
Loops through the results of an promise resolving with true if every item passed, false otherwise.
The promise can return an array or just a single item.
```
function asyncArr(){
var ret = new comb.Promise();
process.nextTick(ret.callback.bind(ret, [1,2,3,4,5]);
return ret.promise;
}
comb.async.every(asyncArr(), function(item){
return item <= 5;
}).then(function(every){
console.log(every); //true
});
```
You may also return a promise from the iterator block.
```
comb.async.every(asyncArr(), function(item, index){
var ret = new comb.Promise();
process.nextTick(function(){
ret.callback(item == 1);
});
return ret.promise();
}).then(function(){
console.log(myNewArr) //false;
})
```
@param {comb.Promise|Array} promise the promise or array to loop through
@param {Function} iterator a function to invoke for each item
@param [scope] optional scope to execute the function in.
@return {comb.Promise} a promise that is resolved true if every item passed false otherwise.
@static
@memberof comb.async
@name every
|
[
"Loops",
"through",
"the",
"results",
"of",
"an",
"promise",
"resolving",
"with",
"true",
"if",
"every",
"item",
"passed",
"false",
"otherwise",
".",
"The",
"promise",
"can",
"return",
"an",
"array",
"or",
"just",
"a",
"single",
"item",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/async.js#L310-L316
|
train
|
C2FO/comb
|
lib/async.js
|
asyncSome
|
function asyncSome(promise, iterator, scope, limit) {
return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) {
return results.loopResults.some(function (res) {
return !!res;
});
}));
}
|
javascript
|
function asyncSome(promise, iterator, scope, limit) {
return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) {
return results.loopResults.some(function (res) {
return !!res;
});
}));
}
|
[
"function",
"asyncSome",
"(",
"promise",
",",
"iterator",
",",
"scope",
",",
"limit",
")",
"{",
"return",
"asyncArray",
"(",
"asyncLoop",
"(",
"promise",
",",
"iterator",
",",
"scope",
",",
"limit",
")",
".",
"chain",
"(",
"function",
"(",
"results",
")",
"{",
"return",
"results",
".",
"loopResults",
".",
"some",
"(",
"function",
"(",
"res",
")",
"{",
"return",
"!",
"!",
"res",
";",
"}",
")",
";",
"}",
")",
")",
";",
"}"
] |
Loops through the results of an promise resolving with true if some items passed, false otherwise.
The promise can return an array or just a single item.
```
function asyncArr(){
var ret = new comb.Promise();
process.nextTick(ret.callback.bind(ret, [1,2,3,4,5]);
return ret.promise;
}
comb.async.some(asyncArr(), function(item){
return item == 1;
}).then(function(every){
console.log(every); //true
});
```
You may also return a promise from the iterator block.
```
comb.async.some(asyncArr(), function(item, index){
var ret = new comb.Promise();
process.nextTick(function(){
ret.callback(item > 5);
});
return ret.promise();
}).then(function(){
console.log(myNewArr) //false;
})
```
@param {comb.Promise|Array} promise the promise or array to loop through
@param {Function} iterator a function to invoke for each item
@param [scope] optional scope to execute the function in.
@return {comb.Promise} a promise that is resolved with true if some items passed false otherwise.
@static
@memberof comb.async
@name some
|
[
"Loops",
"through",
"the",
"results",
"of",
"an",
"promise",
"resolving",
"with",
"true",
"if",
"some",
"items",
"passed",
"false",
"otherwise",
".",
"The",
"promise",
"can",
"return",
"an",
"array",
"or",
"just",
"a",
"single",
"item",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/async.js#L360-L366
|
train
|
C2FO/comb
|
lib/async.js
|
asyncZip
|
function asyncZip() {
return asyncArray(when.apply(null, argsToArray(arguments)).chain(function (result) {
return zip.apply(array, normalizeResult(result).map(function (arg) {
return isArray(arg) ? arg : [arg];
}));
}));
}
|
javascript
|
function asyncZip() {
return asyncArray(when.apply(null, argsToArray(arguments)).chain(function (result) {
return zip.apply(array, normalizeResult(result).map(function (arg) {
return isArray(arg) ? arg : [arg];
}));
}));
}
|
[
"function",
"asyncZip",
"(",
")",
"{",
"return",
"asyncArray",
"(",
"when",
".",
"apply",
"(",
"null",
",",
"argsToArray",
"(",
"arguments",
")",
")",
".",
"chain",
"(",
"function",
"(",
"result",
")",
"{",
"return",
"zip",
".",
"apply",
"(",
"array",
",",
"normalizeResult",
"(",
"result",
")",
".",
"map",
"(",
"function",
"(",
"arg",
")",
"{",
"return",
"isArray",
"(",
"arg",
")",
"?",
"arg",
":",
"[",
"arg",
"]",
";",
"}",
")",
")",
";",
"}",
")",
")",
";",
"}"
] |
Zips results from promises into an array.
```
function asyncArr(){
var ret = new comb.Promise();
process.nextTick(ret.callback.bind(ret, [1,2,3,4,5]);
return ret.promise;
}
comb.async.zip(asyncArr(), asyncArr()).then(function(zipped){
console.log(zipped); //[[1,1],[2,2],[3,3], [4,4], [5,5]]
});
comb.async.array(asyncArr()).zip(asyncArr()).then(function(zipped){
console.log(zipped); //[[1,1],[2,2],[3,3], [4,4], [5,5]]
});
```
@return {comb.Promise} an array with all the arrays zipped together.
@static
@memberof comb.async
@name zip
|
[
"Zips",
"results",
"from",
"promises",
"into",
"an",
"array",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/async.js#L394-L400
|
train
|
peerlibrary/node-xml4js
|
lib/validator.js
|
function (namespaces, defaultNamespace, name) {
var self = this;
assert(namespaces);
assert(name);
if (/^\{.+\}/.test(name)) {
return name;
}
else if (/:/.test(name)) {
var parts = name.split(':');
assert(parts.length === 2, parts);
if (!namespaces[parts[0]]) {
throw new xml2js.ValidationError("Unknown namespace " + parts[0] + ", name: " + name + ", known namespaces: " + util.inspect(namespaces, false, null));
}
return '{' + namespaces[parts[0]] + '}' + parts[1];
}
else if (defaultNamespace) {
return '{' + defaultNamespace + '}' + name;
}
else {
throw new xml2js.ValidationError("Unqualified name and no default namespace: " + name);
}
}
|
javascript
|
function (namespaces, defaultNamespace, name) {
var self = this;
assert(namespaces);
assert(name);
if (/^\{.+\}/.test(name)) {
return name;
}
else if (/:/.test(name)) {
var parts = name.split(':');
assert(parts.length === 2, parts);
if (!namespaces[parts[0]]) {
throw new xml2js.ValidationError("Unknown namespace " + parts[0] + ", name: " + name + ", known namespaces: " + util.inspect(namespaces, false, null));
}
return '{' + namespaces[parts[0]] + '}' + parts[1];
}
else if (defaultNamespace) {
return '{' + defaultNamespace + '}' + name;
}
else {
throw new xml2js.ValidationError("Unqualified name and no default namespace: " + name);
}
}
|
[
"function",
"(",
"namespaces",
",",
"defaultNamespace",
",",
"name",
")",
"{",
"var",
"self",
"=",
"this",
";",
"assert",
"(",
"namespaces",
")",
";",
"assert",
"(",
"name",
")",
";",
"if",
"(",
"/",
"^\\{.+\\}",
"/",
".",
"test",
"(",
"name",
")",
")",
"{",
"return",
"name",
";",
"}",
"else",
"if",
"(",
"/",
":",
"/",
".",
"test",
"(",
"name",
")",
")",
"{",
"var",
"parts",
"=",
"name",
".",
"split",
"(",
"':'",
")",
";",
"assert",
"(",
"parts",
".",
"length",
"===",
"2",
",",
"parts",
")",
";",
"if",
"(",
"!",
"namespaces",
"[",
"parts",
"[",
"0",
"]",
"]",
")",
"{",
"throw",
"new",
"xml2js",
".",
"ValidationError",
"(",
"\"Unknown namespace \"",
"+",
"parts",
"[",
"0",
"]",
"+",
"\", name: \"",
"+",
"name",
"+",
"\", known namespaces: \"",
"+",
"util",
".",
"inspect",
"(",
"namespaces",
",",
"false",
",",
"null",
")",
")",
";",
"}",
"return",
"'{'",
"+",
"namespaces",
"[",
"parts",
"[",
"0",
"]",
"]",
"+",
"'}'",
"+",
"parts",
"[",
"1",
"]",
";",
"}",
"else",
"if",
"(",
"defaultNamespace",
")",
"{",
"return",
"'{'",
"+",
"defaultNamespace",
"+",
"'}'",
"+",
"name",
";",
"}",
"else",
"{",
"throw",
"new",
"xml2js",
".",
"ValidationError",
"(",
"\"Unqualified name and no default namespace: \"",
"+",
"name",
")",
";",
"}",
"}"
] |
Similar to XsdSchema.namespacedName, just using arguments
|
[
"Similar",
"to",
"XsdSchema",
".",
"namespacedName",
"just",
"using",
"arguments"
] |
fe24c3105c3a22e7285443af364fab9dea2d7ed8
|
https://github.com/peerlibrary/node-xml4js/blob/fe24c3105c3a22e7285443af364fab9dea2d7ed8/lib/validator.js#L266-L288
|
train
|
|
PatrickJS/angular-intercom
|
angular-intercom.js
|
createScript
|
function createScript(url, appID) {
if (!document) { return; }
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = url+appID;
// Attach the script tag to the document head
var s = document.getElementsByTagName('head')[0];
s.appendChild(script);
}
|
javascript
|
function createScript(url, appID) {
if (!document) { return; }
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = url+appID;
// Attach the script tag to the document head
var s = document.getElementsByTagName('head')[0];
s.appendChild(script);
}
|
[
"function",
"createScript",
"(",
"url",
",",
"appID",
")",
"{",
"if",
"(",
"!",
"document",
")",
"{",
"return",
";",
"}",
"var",
"script",
"=",
"document",
".",
"createElement",
"(",
"'script'",
")",
";",
"script",
".",
"type",
"=",
"'text/javascript'",
";",
"script",
".",
"async",
"=",
"true",
";",
"script",
".",
"src",
"=",
"url",
"+",
"appID",
";",
"var",
"s",
"=",
"document",
".",
"getElementsByTagName",
"(",
"'head'",
")",
"[",
"0",
"]",
";",
"s",
".",
"appendChild",
"(",
"script",
")",
";",
"}"
] |
Create a script tag with moment as the source and call our onScriptLoad callback when it has been loaded
|
[
"Create",
"a",
"script",
"tag",
"with",
"moment",
"as",
"the",
"source",
"and",
"call",
"our",
"onScriptLoad",
"callback",
"when",
"it",
"has",
"been",
"loaded"
] |
60198a6c5abb1a388a3582e43b0255e9c6b3666e
|
https://github.com/PatrickJS/angular-intercom/blob/60198a6c5abb1a388a3582e43b0255e9c6b3666e/angular-intercom.js#L62-L71
|
train
|
ClickerMonkey/SemanticUI-Angular
|
angular-semantic-ui.js
|
function() {
if ( !(scope.model instanceof Array) ) {
scope.model = scope.model ? [ scope.model ] : [];
}
return scope.model;
}
|
javascript
|
function() {
if ( !(scope.model instanceof Array) ) {
scope.model = scope.model ? [ scope.model ] : [];
}
return scope.model;
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"!",
"(",
"scope",
".",
"model",
"instanceof",
"Array",
")",
")",
"{",
"scope",
".",
"model",
"=",
"scope",
".",
"model",
"?",
"[",
"scope",
".",
"model",
"]",
":",
"[",
"]",
";",
"}",
"return",
"scope",
".",
"model",
";",
"}"
] |
Returns the model on the scope, converting it to an array if it's not one.
|
[
"Returns",
"the",
"model",
"on",
"the",
"scope",
"converting",
"it",
"to",
"an",
"array",
"if",
"it",
"s",
"not",
"one",
"."
] |
b4b89a288535e56d61c3c8e86e47b84495d5d76d
|
https://github.com/ClickerMonkey/SemanticUI-Angular/blob/b4b89a288535e56d61c3c8e86e47b84495d5d76d/angular-semantic-ui.js#L1328-L1333
|
train
|
|
ClickerMonkey/SemanticUI-Angular
|
angular-semantic-ui.js
|
SemanticPopup
|
function SemanticPopup(SemanticPopupLink)
{
return {
restrict: 'A',
scope: {
/* Required */
smPopup: '=',
/* Optional */
smPopupTitle: '=',
smPopupHtml: '=',
smPopupPosition: '@',
smPopupVariation: '@',
smPopupSettings: '=',
smPopupOnInit: '=',
/* Events */
smPopupOnCreate: '=',
smPopupOnRemove: '=',
smPopupOnShow: '=',
smPopupOnVisible: '=',
smPopupOnHide: '=',
smPopupOnHidden: '='
},
link: SemanticPopupLink
};
}
|
javascript
|
function SemanticPopup(SemanticPopupLink)
{
return {
restrict: 'A',
scope: {
/* Required */
smPopup: '=',
/* Optional */
smPopupTitle: '=',
smPopupHtml: '=',
smPopupPosition: '@',
smPopupVariation: '@',
smPopupSettings: '=',
smPopupOnInit: '=',
/* Events */
smPopupOnCreate: '=',
smPopupOnRemove: '=',
smPopupOnShow: '=',
smPopupOnVisible: '=',
smPopupOnHide: '=',
smPopupOnHidden: '='
},
link: SemanticPopupLink
};
}
|
[
"function",
"SemanticPopup",
"(",
"SemanticPopupLink",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"scope",
":",
"{",
"smPopup",
":",
"'='",
",",
"smPopupTitle",
":",
"'='",
",",
"smPopupHtml",
":",
"'='",
",",
"smPopupPosition",
":",
"'@'",
",",
"smPopupVariation",
":",
"'@'",
",",
"smPopupSettings",
":",
"'='",
",",
"smPopupOnInit",
":",
"'='",
",",
"smPopupOnCreate",
":",
"'='",
",",
"smPopupOnRemove",
":",
"'='",
",",
"smPopupOnShow",
":",
"'='",
",",
"smPopupOnVisible",
":",
"'='",
",",
"smPopupOnHide",
":",
"'='",
",",
"smPopupOnHidden",
":",
"'='",
"}",
",",
"link",
":",
"SemanticPopupLink",
"}",
";",
"}"
] |
An attribute directive which displays a popup for this element.
|
[
"An",
"attribute",
"directive",
"which",
"displays",
"a",
"popup",
"for",
"this",
"element",
"."
] |
b4b89a288535e56d61c3c8e86e47b84495d5d76d
|
https://github.com/ClickerMonkey/SemanticUI-Angular/blob/b4b89a288535e56d61c3c8e86e47b84495d5d76d/angular-semantic-ui.js#L1856-L1883
|
train
|
ClickerMonkey/SemanticUI-Angular
|
angular-semantic-ui.js
|
SemanticPopupInline
|
function SemanticPopupInline(SemanticPopupInlineLink)
{
return {
restrict: 'A',
scope: {
/* Optional */
smPopupInline: '=',
smPopupInlineOnInit: '=',
/* Events */
smPopupInlineOnCreate: '=',
smPopupInlineOnRemove: '=',
smPopupInlineOnShow: '=',
smPopupInlineOnVisible: '=',
smPopupInlineOnHide: '=',
smPopupInlineOnHidden: '='
},
link: SemanticPopupInlineLink
};
}
|
javascript
|
function SemanticPopupInline(SemanticPopupInlineLink)
{
return {
restrict: 'A',
scope: {
/* Optional */
smPopupInline: '=',
smPopupInlineOnInit: '=',
/* Events */
smPopupInlineOnCreate: '=',
smPopupInlineOnRemove: '=',
smPopupInlineOnShow: '=',
smPopupInlineOnVisible: '=',
smPopupInlineOnHide: '=',
smPopupInlineOnHidden: '='
},
link: SemanticPopupInlineLink
};
}
|
[
"function",
"SemanticPopupInline",
"(",
"SemanticPopupInlineLink",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"scope",
":",
"{",
"smPopupInline",
":",
"'='",
",",
"smPopupInlineOnInit",
":",
"'='",
",",
"smPopupInlineOnCreate",
":",
"'='",
",",
"smPopupInlineOnRemove",
":",
"'='",
",",
"smPopupInlineOnShow",
":",
"'='",
",",
"smPopupInlineOnVisible",
":",
"'='",
",",
"smPopupInlineOnHide",
":",
"'='",
",",
"smPopupInlineOnHidden",
":",
"'='",
"}",
",",
"link",
":",
"SemanticPopupInlineLink",
"}",
";",
"}"
] |
An attribute directive to show the detached popup which follows this element.
|
[
"An",
"attribute",
"directive",
"to",
"show",
"the",
"detached",
"popup",
"which",
"follows",
"this",
"element",
"."
] |
b4b89a288535e56d61c3c8e86e47b84495d5d76d
|
https://github.com/ClickerMonkey/SemanticUI-Angular/blob/b4b89a288535e56d61c3c8e86e47b84495d5d76d/angular-semantic-ui.js#L1918-L1939
|
train
|
ClickerMonkey/SemanticUI-Angular
|
angular-semantic-ui.js
|
SemanticPopupDisplay
|
function SemanticPopupDisplay(SemanticPopupDisplayLink)
{
return {
restrict: 'A',
scope: {
/* Required */
smPopupDisplay: '@',
/* Optional */
smPopupDisplaySettings: '=',
smPopupDisplayOnInit: '=',
/* Events */
smPopupDisplayOnCreate: '=',
smPopupDisplayOnRemove: '=',
smPopupDisplayOnShow: '=',
smPopupDisplayOnVisible: '=',
smPopupDisplayOnHide: '=',
smPopupDisplayOnHidden: '='
},
link: SemanticPopupDisplayLink
};
}
|
javascript
|
function SemanticPopupDisplay(SemanticPopupDisplayLink)
{
return {
restrict: 'A',
scope: {
/* Required */
smPopupDisplay: '@',
/* Optional */
smPopupDisplaySettings: '=',
smPopupDisplayOnInit: '=',
/* Events */
smPopupDisplayOnCreate: '=',
smPopupDisplayOnRemove: '=',
smPopupDisplayOnShow: '=',
smPopupDisplayOnVisible: '=',
smPopupDisplayOnHide: '=',
smPopupDisplayOnHidden: '='
},
link: SemanticPopupDisplayLink
};
}
|
[
"function",
"SemanticPopupDisplay",
"(",
"SemanticPopupDisplayLink",
")",
"{",
"return",
"{",
"restrict",
":",
"'A'",
",",
"scope",
":",
"{",
"smPopupDisplay",
":",
"'@'",
",",
"smPopupDisplaySettings",
":",
"'='",
",",
"smPopupDisplayOnInit",
":",
"'='",
",",
"smPopupDisplayOnCreate",
":",
"'='",
",",
"smPopupDisplayOnRemove",
":",
"'='",
",",
"smPopupDisplayOnShow",
":",
"'='",
",",
"smPopupDisplayOnVisible",
":",
"'='",
",",
"smPopupDisplayOnHide",
":",
"'='",
",",
"smPopupDisplayOnHidden",
":",
"'='",
"}",
",",
"link",
":",
"SemanticPopupDisplayLink",
"}",
";",
"}"
] |
An attribute directive to show a detached popup over this element given it's name.
|
[
"An",
"attribute",
"directive",
"to",
"show",
"a",
"detached",
"popup",
"over",
"this",
"element",
"given",
"it",
"s",
"name",
"."
] |
b4b89a288535e56d61c3c8e86e47b84495d5d76d
|
https://github.com/ClickerMonkey/SemanticUI-Angular/blob/b4b89a288535e56d61c3c8e86e47b84495d5d76d/angular-semantic-ui.js#L1969-L1992
|
train
|
dvdln/jsonpath-object-transform
|
lib/jsonpath-object-transform.js
|
walk
|
function walk(data, path, result, key) {
var fn;
switch (type(path)) {
case 'string':
fn = seekSingle;
break;
case 'array':
fn = seekArray;
break;
case 'object':
fn = seekObject;
break;
}
if (fn) {
fn(data, path, result, key);
}
}
|
javascript
|
function walk(data, path, result, key) {
var fn;
switch (type(path)) {
case 'string':
fn = seekSingle;
break;
case 'array':
fn = seekArray;
break;
case 'object':
fn = seekObject;
break;
}
if (fn) {
fn(data, path, result, key);
}
}
|
[
"function",
"walk",
"(",
"data",
",",
"path",
",",
"result",
",",
"key",
")",
"{",
"var",
"fn",
";",
"switch",
"(",
"type",
"(",
"path",
")",
")",
"{",
"case",
"'string'",
":",
"fn",
"=",
"seekSingle",
";",
"break",
";",
"case",
"'array'",
":",
"fn",
"=",
"seekArray",
";",
"break",
";",
"case",
"'object'",
":",
"fn",
"=",
"seekObject",
";",
"break",
";",
"}",
"if",
"(",
"fn",
")",
"{",
"fn",
"(",
"data",
",",
"path",
",",
"result",
",",
"key",
")",
";",
"}",
"}"
] |
Step through data object and apply path transforms.
@param {object} data
@param {object} path
@param {object} result
@param {string} key
|
[
"Step",
"through",
"data",
"object",
"and",
"apply",
"path",
"transforms",
"."
] |
e33f4f143976db3c2a52439ff42a5e1982e2defe
|
https://github.com/dvdln/jsonpath-object-transform/blob/e33f4f143976db3c2a52439ff42a5e1982e2defe/lib/jsonpath-object-transform.js#L34-L54
|
train
|
dvdln/jsonpath-object-transform
|
lib/jsonpath-object-transform.js
|
seekSingle
|
function seekSingle(data, pathStr, result, key) {
if(pathStr.indexOf('$') < 0){
result[key] = pathStr;
}else{
var seek = jsonPath.eval(data, pathStr) || [];
result[key] = seek.length ? seek[0] : undefined;
}
}
|
javascript
|
function seekSingle(data, pathStr, result, key) {
if(pathStr.indexOf('$') < 0){
result[key] = pathStr;
}else{
var seek = jsonPath.eval(data, pathStr) || [];
result[key] = seek.length ? seek[0] : undefined;
}
}
|
[
"function",
"seekSingle",
"(",
"data",
",",
"pathStr",
",",
"result",
",",
"key",
")",
"{",
"if",
"(",
"pathStr",
".",
"indexOf",
"(",
"'$'",
")",
"<",
"0",
")",
"{",
"result",
"[",
"key",
"]",
"=",
"pathStr",
";",
"}",
"else",
"{",
"var",
"seek",
"=",
"jsonPath",
".",
"eval",
"(",
"data",
",",
"pathStr",
")",
"||",
"[",
"]",
";",
"result",
"[",
"key",
"]",
"=",
"seek",
".",
"length",
"?",
"seek",
"[",
"0",
"]",
":",
"undefined",
";",
"}",
"}"
] |
Get single property from data object.
@param {object} data
@param {string} pathStr
@param {object} result
@param {string} key
|
[
"Get",
"single",
"property",
"from",
"data",
"object",
"."
] |
e33f4f143976db3c2a52439ff42a5e1982e2defe
|
https://github.com/dvdln/jsonpath-object-transform/blob/e33f4f143976db3c2a52439ff42a5e1982e2defe/lib/jsonpath-object-transform.js#L74-L82
|
train
|
dvdln/jsonpath-object-transform
|
lib/jsonpath-object-transform.js
|
seekArray
|
function seekArray(data, pathArr, result, key) {
var subpath = pathArr[1];
var path = pathArr[0];
var seek = jsonPath.eval(data, path) || [];
if (seek.length && subpath) {
result = result[key] = [];
seek[0].forEach(function(item, index) {
walk(item, subpath, result, index);
});
} else {
result[key] = seek;
}
}
|
javascript
|
function seekArray(data, pathArr, result, key) {
var subpath = pathArr[1];
var path = pathArr[0];
var seek = jsonPath.eval(data, path) || [];
if (seek.length && subpath) {
result = result[key] = [];
seek[0].forEach(function(item, index) {
walk(item, subpath, result, index);
});
} else {
result[key] = seek;
}
}
|
[
"function",
"seekArray",
"(",
"data",
",",
"pathArr",
",",
"result",
",",
"key",
")",
"{",
"var",
"subpath",
"=",
"pathArr",
"[",
"1",
"]",
";",
"var",
"path",
"=",
"pathArr",
"[",
"0",
"]",
";",
"var",
"seek",
"=",
"jsonPath",
".",
"eval",
"(",
"data",
",",
"path",
")",
"||",
"[",
"]",
";",
"if",
"(",
"seek",
".",
"length",
"&&",
"subpath",
")",
"{",
"result",
"=",
"result",
"[",
"key",
"]",
"=",
"[",
"]",
";",
"seek",
"[",
"0",
"]",
".",
"forEach",
"(",
"function",
"(",
"item",
",",
"index",
")",
"{",
"walk",
"(",
"item",
",",
"subpath",
",",
"result",
",",
"index",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"result",
"[",
"key",
"]",
"=",
"seek",
";",
"}",
"}"
] |
Get array of properties from data object.
@param {object} data
@param {array} pathArr
@param {object} result
@param {string} key
|
[
"Get",
"array",
"of",
"properties",
"from",
"data",
"object",
"."
] |
e33f4f143976db3c2a52439ff42a5e1982e2defe
|
https://github.com/dvdln/jsonpath-object-transform/blob/e33f4f143976db3c2a52439ff42a5e1982e2defe/lib/jsonpath-object-transform.js#L92-L106
|
train
|
dvdln/jsonpath-object-transform
|
lib/jsonpath-object-transform.js
|
seekObject
|
function seekObject(data, pathObj, result, key) {
if (typeof key !== 'undefined') {
result = result[key] = {};
}
Object.keys(pathObj).forEach(function(name) {
walk(data, pathObj[name], result, name);
});
}
|
javascript
|
function seekObject(data, pathObj, result, key) {
if (typeof key !== 'undefined') {
result = result[key] = {};
}
Object.keys(pathObj).forEach(function(name) {
walk(data, pathObj[name], result, name);
});
}
|
[
"function",
"seekObject",
"(",
"data",
",",
"pathObj",
",",
"result",
",",
"key",
")",
"{",
"if",
"(",
"typeof",
"key",
"!==",
"'undefined'",
")",
"{",
"result",
"=",
"result",
"[",
"key",
"]",
"=",
"{",
"}",
";",
"}",
"Object",
".",
"keys",
"(",
"pathObj",
")",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"walk",
"(",
"data",
",",
"pathObj",
"[",
"name",
"]",
",",
"result",
",",
"name",
")",
";",
"}",
")",
";",
"}"
] |
Get object property from data object.
@param {object} data
@param {object} pathObj
@param {object} result
@param {string} key
|
[
"Get",
"object",
"property",
"from",
"data",
"object",
"."
] |
e33f4f143976db3c2a52439ff42a5e1982e2defe
|
https://github.com/dvdln/jsonpath-object-transform/blob/e33f4f143976db3c2a52439ff42a5e1982e2defe/lib/jsonpath-object-transform.js#L116-L124
|
train
|
mixmaxhq/electron-editor-context-menu
|
src/index.js
|
function(selection, mainTemplate, suggestionsTemplate) {
selection = defaults({}, selection, {
isMisspelled: false,
spellingSuggestions: []
});
var template = getTemplate(mainTemplate, DEFAULT_MAIN_TPL);
var suggestionsTpl = getTemplate(suggestionsTemplate, DEFAULT_SUGGESTIONS_TPL);
if (selection.isMisspelled) {
var suggestions = selection.spellingSuggestions;
if (isEmpty(suggestions)) {
template.unshift.apply(template, suggestionsTpl);
} else {
template.unshift.apply(template, suggestions.map(function(suggestion) {
return {
label: suggestion,
click: function() {
BrowserWindow.getFocusedWindow().webContents.replaceMisspelling(suggestion);
}
};
}).concat({
type: 'separator'
}));
}
}
return Menu.buildFromTemplate(template);
}
|
javascript
|
function(selection, mainTemplate, suggestionsTemplate) {
selection = defaults({}, selection, {
isMisspelled: false,
spellingSuggestions: []
});
var template = getTemplate(mainTemplate, DEFAULT_MAIN_TPL);
var suggestionsTpl = getTemplate(suggestionsTemplate, DEFAULT_SUGGESTIONS_TPL);
if (selection.isMisspelled) {
var suggestions = selection.spellingSuggestions;
if (isEmpty(suggestions)) {
template.unshift.apply(template, suggestionsTpl);
} else {
template.unshift.apply(template, suggestions.map(function(suggestion) {
return {
label: suggestion,
click: function() {
BrowserWindow.getFocusedWindow().webContents.replaceMisspelling(suggestion);
}
};
}).concat({
type: 'separator'
}));
}
}
return Menu.buildFromTemplate(template);
}
|
[
"function",
"(",
"selection",
",",
"mainTemplate",
",",
"suggestionsTemplate",
")",
"{",
"selection",
"=",
"defaults",
"(",
"{",
"}",
",",
"selection",
",",
"{",
"isMisspelled",
":",
"false",
",",
"spellingSuggestions",
":",
"[",
"]",
"}",
")",
";",
"var",
"template",
"=",
"getTemplate",
"(",
"mainTemplate",
",",
"DEFAULT_MAIN_TPL",
")",
";",
"var",
"suggestionsTpl",
"=",
"getTemplate",
"(",
"suggestionsTemplate",
",",
"DEFAULT_SUGGESTIONS_TPL",
")",
";",
"if",
"(",
"selection",
".",
"isMisspelled",
")",
"{",
"var",
"suggestions",
"=",
"selection",
".",
"spellingSuggestions",
";",
"if",
"(",
"isEmpty",
"(",
"suggestions",
")",
")",
"{",
"template",
".",
"unshift",
".",
"apply",
"(",
"template",
",",
"suggestionsTpl",
")",
";",
"}",
"else",
"{",
"template",
".",
"unshift",
".",
"apply",
"(",
"template",
",",
"suggestions",
".",
"map",
"(",
"function",
"(",
"suggestion",
")",
"{",
"return",
"{",
"label",
":",
"suggestion",
",",
"click",
":",
"function",
"(",
")",
"{",
"BrowserWindow",
".",
"getFocusedWindow",
"(",
")",
".",
"webContents",
".",
"replaceMisspelling",
"(",
"suggestion",
")",
";",
"}",
"}",
";",
"}",
")",
".",
"concat",
"(",
"{",
"type",
":",
"'separator'",
"}",
")",
")",
";",
"}",
"}",
"return",
"Menu",
".",
"buildFromTemplate",
"(",
"template",
")",
";",
"}"
] |
Builds a context menu suitable for showing in a text editor.
@param {Object=} selection - An object describing the current text selection.
@property {Boolean=false} isMisspelled - `true` if the selection is
misspelled, `false` if it is spelled correctly or is not text.
@property {Array<String>=[]} spellingSuggestions - An array of suggestions
to show to correct the misspelling. Ignored if `isMisspelled` is `false`.
@param {Function|Array} mainTemplate - Optional. If it's an array, use as is.
If it's a function, used to customize the template of always-present menu items.
Receives the default template as a parameter. Should return a template.
@param {Function|Array} suggestionsTemplate - Optional. If it's an array, use as is.
If it's a function, used to customize the template of spelling suggestion items.
Receives the default suggestions template as a parameter. Should return a template.
@return {Menu}
|
[
"Builds",
"a",
"context",
"menu",
"suitable",
"for",
"showing",
"in",
"a",
"text",
"editor",
"."
] |
dbb3474f0767304a7fb5a7f50e36c0b34ef1de03
|
https://github.com/mixmaxhq/electron-editor-context-menu/blob/dbb3474f0767304a7fb5a7f50e36c0b34ef1de03/src/index.js#L83-L112
|
train
|
|
xdenser/node-firebird-libfbclient
|
samples/fileman/static/elfinder/elfinder.full.js
|
resize
|
function resize(w, h) {
w && self.view.win.width(w);
h && self.view.nav.add(self.view.cwd).height(h);
}
|
javascript
|
function resize(w, h) {
w && self.view.win.width(w);
h && self.view.nav.add(self.view.cwd).height(h);
}
|
[
"function",
"resize",
"(",
"w",
",",
"h",
")",
"{",
"w",
"&&",
"self",
".",
"view",
".",
"win",
".",
"width",
"(",
"w",
")",
";",
"h",
"&&",
"self",
".",
"view",
".",
"nav",
".",
"add",
"(",
"self",
".",
"view",
".",
"cwd",
")",
".",
"height",
"(",
"h",
")",
";",
"}"
] |
Resize file manager
@param Number width
@param Number height
|
[
"Resize",
"file",
"manager"
] |
455c5e023b979d68e41ef8946dbdc9abd0a6e2d0
|
https://github.com/xdenser/node-firebird-libfbclient/blob/455c5e023b979d68e41ef8946dbdc9abd0a6e2d0/samples/fileman/static/elfinder/elfinder.full.js#L550-L553
|
train
|
xdenser/node-firebird-libfbclient
|
samples/fileman/static/elfinder/elfinder.full.js
|
dialogResize
|
function dialogResize() {
resize(null, self.dialog.height()-self.view.tlb.parent().height()-($.browser.msie ? 47 : 32))
}
|
javascript
|
function dialogResize() {
resize(null, self.dialog.height()-self.view.tlb.parent().height()-($.browser.msie ? 47 : 32))
}
|
[
"function",
"dialogResize",
"(",
")",
"{",
"resize",
"(",
"null",
",",
"self",
".",
"dialog",
".",
"height",
"(",
")",
"-",
"self",
".",
"view",
".",
"tlb",
".",
"parent",
"(",
")",
".",
"height",
"(",
")",
"-",
"(",
"$",
".",
"browser",
".",
"msie",
"?",
"47",
":",
"32",
")",
")",
"}"
] |
Resize file manager in dialog window while it resize
|
[
"Resize",
"file",
"manager",
"in",
"dialog",
"window",
"while",
"it",
"resize"
] |
455c5e023b979d68e41ef8946dbdc9abd0a6e2d0
|
https://github.com/xdenser/node-firebird-libfbclient/blob/455c5e023b979d68e41ef8946dbdc9abd0a6e2d0/samples/fileman/static/elfinder/elfinder.full.js#L559-L561
|
train
|
xdenser/node-firebird-libfbclient
|
samples/fileman/static/elfinder/elfinder.full.js
|
reset
|
function reset() {
self.media.hide().empty();
self.win.attr('class', 'el-finder-ql').css('z-index', self.fm.zIndex);
self.title.empty();
self.ico.removeAttr('style').show();
self.add.hide().empty();
self._hash = '';
}
|
javascript
|
function reset() {
self.media.hide().empty();
self.win.attr('class', 'el-finder-ql').css('z-index', self.fm.zIndex);
self.title.empty();
self.ico.removeAttr('style').show();
self.add.hide().empty();
self._hash = '';
}
|
[
"function",
"reset",
"(",
")",
"{",
"self",
".",
"media",
".",
"hide",
"(",
")",
".",
"empty",
"(",
")",
";",
"self",
".",
"win",
".",
"attr",
"(",
"'class'",
",",
"'el-finder-ql'",
")",
".",
"css",
"(",
"'z-index'",
",",
"self",
".",
"fm",
".",
"zIndex",
")",
";",
"self",
".",
"title",
".",
"empty",
"(",
")",
";",
"self",
".",
"ico",
".",
"removeAttr",
"(",
"'style'",
")",
".",
"show",
"(",
")",
";",
"self",
".",
"add",
".",
"hide",
"(",
")",
".",
"empty",
"(",
")",
";",
"self",
".",
"_hash",
"=",
"''",
";",
"}"
] |
Clean quickLook window DOM elements
|
[
"Clean",
"quickLook",
"window",
"DOM",
"elements"
] |
455c5e023b979d68e41ef8946dbdc9abd0a6e2d0
|
https://github.com/xdenser/node-firebird-libfbclient/blob/455c5e023b979d68e41ef8946dbdc9abd0a6e2d0/samples/fileman/static/elfinder/elfinder.full.js#L2728-L2735
|
train
|
xdenser/node-firebird-libfbclient
|
samples/fileman/static/elfinder/elfinder.full.js
|
update
|
function update() {
var f = self.fm.getSelected(0);
reset();
self._hash = f.hash;
self.title.text(f.name);
self.win.addClass(self.fm.view.mime2class(f.mime));
self.name.text(f.name);
self.kind.text(self.fm.view.mime2kind(f.link ? 'symlink' : f.mime));
self.size.text(self.fm.view.formatSize(f.size));
self.date.text(self.fm.i18n('Modified')+': '+self.fm.view.formatDate(f.date));
f.dim && self.add.append('<span>'+f.dim+' px</span>').show();
f.tmb && self.ico.css('background', 'url("'+f.tmb+'") 0 0 no-repeat');
if (f.url) {
self.url.text(f.url).attr('href', f.url).show();
for (var i in self.plugins) {
if (self.plugins[i].test && self.plugins[i].test(f.mime, self.mimes, f.name)) {
self.plugins[i].show(self, f);
return;
}
}
} else {
self.url.hide();
}
self.win.css({
width : '420px',
height : 'auto'
});
}
|
javascript
|
function update() {
var f = self.fm.getSelected(0);
reset();
self._hash = f.hash;
self.title.text(f.name);
self.win.addClass(self.fm.view.mime2class(f.mime));
self.name.text(f.name);
self.kind.text(self.fm.view.mime2kind(f.link ? 'symlink' : f.mime));
self.size.text(self.fm.view.formatSize(f.size));
self.date.text(self.fm.i18n('Modified')+': '+self.fm.view.formatDate(f.date));
f.dim && self.add.append('<span>'+f.dim+' px</span>').show();
f.tmb && self.ico.css('background', 'url("'+f.tmb+'") 0 0 no-repeat');
if (f.url) {
self.url.text(f.url).attr('href', f.url).show();
for (var i in self.plugins) {
if (self.plugins[i].test && self.plugins[i].test(f.mime, self.mimes, f.name)) {
self.plugins[i].show(self, f);
return;
}
}
} else {
self.url.hide();
}
self.win.css({
width : '420px',
height : 'auto'
});
}
|
[
"function",
"update",
"(",
")",
"{",
"var",
"f",
"=",
"self",
".",
"fm",
".",
"getSelected",
"(",
"0",
")",
";",
"reset",
"(",
")",
";",
"self",
".",
"_hash",
"=",
"f",
".",
"hash",
";",
"self",
".",
"title",
".",
"text",
"(",
"f",
".",
"name",
")",
";",
"self",
".",
"win",
".",
"addClass",
"(",
"self",
".",
"fm",
".",
"view",
".",
"mime2class",
"(",
"f",
".",
"mime",
")",
")",
";",
"self",
".",
"name",
".",
"text",
"(",
"f",
".",
"name",
")",
";",
"self",
".",
"kind",
".",
"text",
"(",
"self",
".",
"fm",
".",
"view",
".",
"mime2kind",
"(",
"f",
".",
"link",
"?",
"'symlink'",
":",
"f",
".",
"mime",
")",
")",
";",
"self",
".",
"size",
".",
"text",
"(",
"self",
".",
"fm",
".",
"view",
".",
"formatSize",
"(",
"f",
".",
"size",
")",
")",
";",
"self",
".",
"date",
".",
"text",
"(",
"self",
".",
"fm",
".",
"i18n",
"(",
"'Modified'",
")",
"+",
"': '",
"+",
"self",
".",
"fm",
".",
"view",
".",
"formatDate",
"(",
"f",
".",
"date",
")",
")",
";",
"f",
".",
"dim",
"&&",
"self",
".",
"add",
".",
"append",
"(",
"'<span>'",
"+",
"f",
".",
"dim",
"+",
"' px</span>'",
")",
".",
"show",
"(",
")",
";",
"f",
".",
"tmb",
"&&",
"self",
".",
"ico",
".",
"css",
"(",
"'background'",
",",
"'url(\"'",
"+",
"f",
".",
"tmb",
"+",
"'\") 0 0 no-repeat'",
")",
";",
"if",
"(",
"f",
".",
"url",
")",
"{",
"self",
".",
"url",
".",
"text",
"(",
"f",
".",
"url",
")",
".",
"attr",
"(",
"'href'",
",",
"f",
".",
"url",
")",
".",
"show",
"(",
")",
";",
"for",
"(",
"var",
"i",
"in",
"self",
".",
"plugins",
")",
"{",
"if",
"(",
"self",
".",
"plugins",
"[",
"i",
"]",
".",
"test",
"&&",
"self",
".",
"plugins",
"[",
"i",
"]",
".",
"test",
"(",
"f",
".",
"mime",
",",
"self",
".",
"mimes",
",",
"f",
".",
"name",
")",
")",
"{",
"self",
".",
"plugins",
"[",
"i",
"]",
".",
"show",
"(",
"self",
",",
"f",
")",
";",
"return",
";",
"}",
"}",
"}",
"else",
"{",
"self",
".",
"url",
".",
"hide",
"(",
")",
";",
"}",
"self",
".",
"win",
".",
"css",
"(",
"{",
"width",
":",
"'420px'",
",",
"height",
":",
"'auto'",
"}",
")",
";",
"}"
] |
Update quickLook window content
|
[
"Update",
"quickLook",
"window",
"content"
] |
455c5e023b979d68e41ef8946dbdc9abd0a6e2d0
|
https://github.com/xdenser/node-firebird-libfbclient/blob/455c5e023b979d68e41ef8946dbdc9abd0a6e2d0/samples/fileman/static/elfinder/elfinder.full.js#L2740-L2769
|
train
|
xdenser/node-firebird-libfbclient
|
samples/fileman/static/elfinder/elfinder.full.js
|
moveSelection
|
function moveSelection(forward, reset) {
var p, _p, cur;
if (!$('[key]', self.cwd).length) {
return;
}
if (self.fm.selected.length == 0) {
p = $('[key]:'+(forward ? 'first' : 'last'), self.cwd);
self.fm.select(p);
} else if (reset) {
p = $('.ui-selected:'+(forward ? 'last' : 'first'), self.cwd);
_p = p[forward ? 'next' : 'prev']('[key]');
if (_p.length) {
p = _p;
}
self.fm.select(p, true);
} else {
if (self.pointer) {
cur = $('[key="'+self.pointer+'"].ui-selected', self.cwd);
}
if (!cur || !cur.length) {
cur = $('.ui-selected:'+(forward ? 'last' : 'first'), self.cwd);
}
p = cur[forward ? 'next' : 'prev']('[key]');
if (!p.length) {
p = cur;
} else {
if (!p.hasClass('ui-selected')) {
self.fm.select(p);
} else {
if (!cur.hasClass('ui-selected')) {
self.fm.unselect(p);
} else {
_p = cur[forward ? 'prev' : 'next']('[key]')
if (!_p.length || !_p.hasClass('ui-selected')) {
self.fm.unselect(cur);
} else {
while ((_p = forward ? p.next('[key]') : p.prev('[key]')) && p.hasClass('ui-selected')) {
p = _p;
}
self.fm.select(p);
}
}
}
}
}
self.pointer = p.attr('key');
self.fm.checkSelectedPos(forward);
}
|
javascript
|
function moveSelection(forward, reset) {
var p, _p, cur;
if (!$('[key]', self.cwd).length) {
return;
}
if (self.fm.selected.length == 0) {
p = $('[key]:'+(forward ? 'first' : 'last'), self.cwd);
self.fm.select(p);
} else if (reset) {
p = $('.ui-selected:'+(forward ? 'last' : 'first'), self.cwd);
_p = p[forward ? 'next' : 'prev']('[key]');
if (_p.length) {
p = _p;
}
self.fm.select(p, true);
} else {
if (self.pointer) {
cur = $('[key="'+self.pointer+'"].ui-selected', self.cwd);
}
if (!cur || !cur.length) {
cur = $('.ui-selected:'+(forward ? 'last' : 'first'), self.cwd);
}
p = cur[forward ? 'next' : 'prev']('[key]');
if (!p.length) {
p = cur;
} else {
if (!p.hasClass('ui-selected')) {
self.fm.select(p);
} else {
if (!cur.hasClass('ui-selected')) {
self.fm.unselect(p);
} else {
_p = cur[forward ? 'prev' : 'next']('[key]')
if (!_p.length || !_p.hasClass('ui-selected')) {
self.fm.unselect(cur);
} else {
while ((_p = forward ? p.next('[key]') : p.prev('[key]')) && p.hasClass('ui-selected')) {
p = _p;
}
self.fm.select(p);
}
}
}
}
}
self.pointer = p.attr('key');
self.fm.checkSelectedPos(forward);
}
|
[
"function",
"moveSelection",
"(",
"forward",
",",
"reset",
")",
"{",
"var",
"p",
",",
"_p",
",",
"cur",
";",
"if",
"(",
"!",
"$",
"(",
"'[key]'",
",",
"self",
".",
"cwd",
")",
".",
"length",
")",
"{",
"return",
";",
"}",
"if",
"(",
"self",
".",
"fm",
".",
"selected",
".",
"length",
"==",
"0",
")",
"{",
"p",
"=",
"$",
"(",
"'[key]:'",
"+",
"(",
"forward",
"?",
"'first'",
":",
"'last'",
")",
",",
"self",
".",
"cwd",
")",
";",
"self",
".",
"fm",
".",
"select",
"(",
"p",
")",
";",
"}",
"else",
"if",
"(",
"reset",
")",
"{",
"p",
"=",
"$",
"(",
"'.ui-selected:'",
"+",
"(",
"forward",
"?",
"'last'",
":",
"'first'",
")",
",",
"self",
".",
"cwd",
")",
";",
"_p",
"=",
"p",
"[",
"forward",
"?",
"'next'",
":",
"'prev'",
"]",
"(",
"'[key]'",
")",
";",
"if",
"(",
"_p",
".",
"length",
")",
"{",
"p",
"=",
"_p",
";",
"}",
"self",
".",
"fm",
".",
"select",
"(",
"p",
",",
"true",
")",
";",
"}",
"else",
"{",
"if",
"(",
"self",
".",
"pointer",
")",
"{",
"cur",
"=",
"$",
"(",
"'[key=\"'",
"+",
"self",
".",
"pointer",
"+",
"'\"].ui-selected'",
",",
"self",
".",
"cwd",
")",
";",
"}",
"if",
"(",
"!",
"cur",
"||",
"!",
"cur",
".",
"length",
")",
"{",
"cur",
"=",
"$",
"(",
"'.ui-selected:'",
"+",
"(",
"forward",
"?",
"'last'",
":",
"'first'",
")",
",",
"self",
".",
"cwd",
")",
";",
"}",
"p",
"=",
"cur",
"[",
"forward",
"?",
"'next'",
":",
"'prev'",
"]",
"(",
"'[key]'",
")",
";",
"if",
"(",
"!",
"p",
".",
"length",
")",
"{",
"p",
"=",
"cur",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"p",
".",
"hasClass",
"(",
"'ui-selected'",
")",
")",
"{",
"self",
".",
"fm",
".",
"select",
"(",
"p",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"cur",
".",
"hasClass",
"(",
"'ui-selected'",
")",
")",
"{",
"self",
".",
"fm",
".",
"unselect",
"(",
"p",
")",
";",
"}",
"else",
"{",
"_p",
"=",
"cur",
"[",
"forward",
"?",
"'prev'",
":",
"'next'",
"]",
"(",
"'[key]'",
")",
"if",
"(",
"!",
"_p",
".",
"length",
"||",
"!",
"_p",
".",
"hasClass",
"(",
"'ui-selected'",
")",
")",
"{",
"self",
".",
"fm",
".",
"unselect",
"(",
"cur",
")",
";",
"}",
"else",
"{",
"while",
"(",
"(",
"_p",
"=",
"forward",
"?",
"p",
".",
"next",
"(",
"'[key]'",
")",
":",
"p",
".",
"prev",
"(",
"'[key]'",
")",
")",
"&&",
"p",
".",
"hasClass",
"(",
"'ui-selected'",
")",
")",
"{",
"p",
"=",
"_p",
";",
"}",
"self",
".",
"fm",
".",
"select",
"(",
"p",
")",
";",
"}",
"}",
"}",
"}",
"}",
"self",
".",
"pointer",
"=",
"p",
".",
"attr",
"(",
"'key'",
")",
";",
"self",
".",
"fm",
".",
"checkSelectedPos",
"(",
"forward",
")",
";",
"}"
] |
Move selection in current dir
@param Boolean move forward?
@param Boolean clear current selection?
|
[
"Move",
"selection",
"in",
"current",
"dir"
] |
455c5e023b979d68e41ef8946dbdc9abd0a6e2d0
|
https://github.com/xdenser/node-firebird-libfbclient/blob/455c5e023b979d68e41ef8946dbdc9abd0a6e2d0/samples/fileman/static/elfinder/elfinder.full.js#L3277-L3327
|
train
|
DevExpress/testcafe-legacy-api
|
src/compiler/tools/uglify-js/lib/consolidator.js
|
function(oExpression, sIdentifierName) {
fCountPrimaryExpression(
EPrimaryExpressionCategories.N_IDENTIFIER_NAMES,
EValuePrefixes.S_STRING + sIdentifierName);
return ['dot', oWalker.walk(oExpression), sIdentifierName];
}
|
javascript
|
function(oExpression, sIdentifierName) {
fCountPrimaryExpression(
EPrimaryExpressionCategories.N_IDENTIFIER_NAMES,
EValuePrefixes.S_STRING + sIdentifierName);
return ['dot', oWalker.walk(oExpression), sIdentifierName];
}
|
[
"function",
"(",
"oExpression",
",",
"sIdentifierName",
")",
"{",
"fCountPrimaryExpression",
"(",
"EPrimaryExpressionCategories",
".",
"N_IDENTIFIER_NAMES",
",",
"EValuePrefixes",
".",
"S_STRING",
"+",
"sIdentifierName",
")",
";",
"return",
"[",
"'dot'",
",",
"oWalker",
".",
"walk",
"(",
"oExpression",
")",
",",
"sIdentifierName",
"]",
";",
"}"
] |
Increments the count of the number of occurrences of the String
value that is equivalent to the sequence of terminal symbols
that constitute the encountered identifier name.
@param {!TSyntacticCodeUnit} oExpression The nonterminal
MemberExpression.
@param {string} sIdentifierName The identifier name used as the
property accessor.
@return {!Array} The encountered branch of an <abbr title=
"abstract syntax tree">AST</abbr> with its nonterminal
MemberExpression traversed.
|
[
"Increments",
"the",
"count",
"of",
"the",
"number",
"of",
"occurrences",
"of",
"the",
"String",
"value",
"that",
"is",
"equivalent",
"to",
"the",
"sequence",
"of",
"terminal",
"symbols",
"that",
"constitute",
"the",
"encountered",
"identifier",
"name",
"."
] |
97c5dcfe46fb6a43efd2cc571bb1aa8c654c1947
|
https://github.com/DevExpress/testcafe-legacy-api/blob/97c5dcfe46fb6a43efd2cc571bb1aa8c654c1947/src/compiler/tools/uglify-js/lib/consolidator.js#L401-L406
|
train
|
|
DevExpress/testcafe-legacy-api
|
src/compiler/tools/uglify-js/lib/consolidator.js
|
function(oExpression, sIdentifierName) {
/**
* The prefixed String value that is equivalent to the
* sequence of terminal symbols that constitute the
* encountered identifier name.
* @type {string}
*/
var sPrefixed = EValuePrefixes.S_STRING + sIdentifierName;
return oSolutionBest.oPrimitiveValues.hasOwnProperty(
sPrefixed) &&
oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
['sub',
oWalker.walk(oExpression),
['name',
oSolutionBest.oPrimitiveValues[sPrefixed].sName]] :
['dot', oWalker.walk(oExpression), sIdentifierName];
}
|
javascript
|
function(oExpression, sIdentifierName) {
/**
* The prefixed String value that is equivalent to the
* sequence of terminal symbols that constitute the
* encountered identifier name.
* @type {string}
*/
var sPrefixed = EValuePrefixes.S_STRING + sIdentifierName;
return oSolutionBest.oPrimitiveValues.hasOwnProperty(
sPrefixed) &&
oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
['sub',
oWalker.walk(oExpression),
['name',
oSolutionBest.oPrimitiveValues[sPrefixed].sName]] :
['dot', oWalker.walk(oExpression), sIdentifierName];
}
|
[
"function",
"(",
"oExpression",
",",
"sIdentifierName",
")",
"{",
"var",
"sPrefixed",
"=",
"EValuePrefixes",
".",
"S_STRING",
"+",
"sIdentifierName",
";",
"return",
"oSolutionBest",
".",
"oPrimitiveValues",
".",
"hasOwnProperty",
"(",
"sPrefixed",
")",
"&&",
"oSolutionBest",
".",
"oPrimitiveValues",
"[",
"sPrefixed",
"]",
".",
"nSaving",
">",
"0",
"?",
"[",
"'sub'",
",",
"oWalker",
".",
"walk",
"(",
"oExpression",
")",
",",
"[",
"'name'",
",",
"oSolutionBest",
".",
"oPrimitiveValues",
"[",
"sPrefixed",
"]",
".",
"sName",
"]",
"]",
":",
"[",
"'dot'",
",",
"oWalker",
".",
"walk",
"(",
"oExpression",
")",
",",
"sIdentifierName",
"]",
";",
"}"
] |
If the String value that is equivalent to the sequence of
terminal symbols that constitute the encountered identifier
name is worthwhile, a syntactic conversion from the dot
notation to the bracket notation ensues with that sequence
being substituted by an identifier name to which the value
is assigned.
Applies to property accessors that use the dot notation.
@param {!TSyntacticCodeUnit} oExpression The nonterminal
MemberExpression.
@param {string} sIdentifierName The identifier name used as
the property accessor.
@return {!Array} A syntactic code unit that is equivalent to
the one encountered.
@see TPrimitiveValue#nSaving
|
[
"If",
"the",
"String",
"value",
"that",
"is",
"equivalent",
"to",
"the",
"sequence",
"of",
"terminal",
"symbols",
"that",
"constitute",
"the",
"encountered",
"identifier",
"name",
"is",
"worthwhile",
"a",
"syntactic",
"conversion",
"from",
"the",
"dot",
"notation",
"to",
"the",
"bracket",
"notation",
"ensues",
"with",
"that",
"sequence",
"being",
"substituted",
"by",
"an",
"identifier",
"name",
"to",
"which",
"the",
"value",
"is",
"assigned",
".",
"Applies",
"to",
"property",
"accessors",
"that",
"use",
"the",
"dot",
"notation",
"."
] |
97c5dcfe46fb6a43efd2cc571bb1aa8c654c1947
|
https://github.com/DevExpress/testcafe-legacy-api/blob/97c5dcfe46fb6a43efd2cc571bb1aa8c654c1947/src/compiler/tools/uglify-js/lib/consolidator.js#L685-L702
|
train
|
|
DevExpress/testcafe-legacy-api
|
src/compiler/tools/uglify-js/lib/consolidator.js
|
function(sIdentifier) {
/**
* The prefixed representation String of the identifier.
* @type {string}
*/
var sPrefixed = EValuePrefixes.S_SYMBOLIC + sIdentifier;
return [
'name',
oSolutionBest.oPrimitiveValues.hasOwnProperty(sPrefixed) &&
oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
oSolutionBest.oPrimitiveValues[sPrefixed].sName :
sIdentifier
];
}
|
javascript
|
function(sIdentifier) {
/**
* The prefixed representation String of the identifier.
* @type {string}
*/
var sPrefixed = EValuePrefixes.S_SYMBOLIC + sIdentifier;
return [
'name',
oSolutionBest.oPrimitiveValues.hasOwnProperty(sPrefixed) &&
oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
oSolutionBest.oPrimitiveValues[sPrefixed].sName :
sIdentifier
];
}
|
[
"function",
"(",
"sIdentifier",
")",
"{",
"var",
"sPrefixed",
"=",
"EValuePrefixes",
".",
"S_SYMBOLIC",
"+",
"sIdentifier",
";",
"return",
"[",
"'name'",
",",
"oSolutionBest",
".",
"oPrimitiveValues",
".",
"hasOwnProperty",
"(",
"sPrefixed",
")",
"&&",
"oSolutionBest",
".",
"oPrimitiveValues",
"[",
"sPrefixed",
"]",
".",
"nSaving",
">",
"0",
"?",
"oSolutionBest",
".",
"oPrimitiveValues",
"[",
"sPrefixed",
"]",
".",
"sName",
":",
"sIdentifier",
"]",
";",
"}"
] |
If the encountered identifier is a null or Boolean literal
and its value is worthwhile, the identifier is substituted
by an identifier name to which that value is assigned.
Applies to identifier names.
@param {string} sIdentifier The identifier encountered.
@return {!Array} A syntactic code unit that is equivalent to
the one encountered.
@see TPrimitiveValue#nSaving
|
[
"If",
"the",
"encountered",
"identifier",
"is",
"a",
"null",
"or",
"Boolean",
"literal",
"and",
"its",
"value",
"is",
"worthwhile",
"the",
"identifier",
"is",
"substituted",
"by",
"an",
"identifier",
"name",
"to",
"which",
"that",
"value",
"is",
"assigned",
".",
"Applies",
"to",
"identifier",
"names",
"."
] |
97c5dcfe46fb6a43efd2cc571bb1aa8c654c1947
|
https://github.com/DevExpress/testcafe-legacy-api/blob/97c5dcfe46fb6a43efd2cc571bb1aa8c654c1947/src/compiler/tools/uglify-js/lib/consolidator.js#L713-L727
|
train
|
|
DevExpress/testcafe-legacy-api
|
src/compiler/tools/uglify-js/lib/consolidator.js
|
function(sStringValue) {
/**
* The prefixed representation String of the primitive value
* of the literal.
* @type {string}
*/
var sPrefixed =
EValuePrefixes.S_STRING + sStringValue;
return oSolutionBest.oPrimitiveValues.hasOwnProperty(
sPrefixed) &&
oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
['name',
oSolutionBest.oPrimitiveValues[sPrefixed].sName] :
['string', sStringValue];
}
|
javascript
|
function(sStringValue) {
/**
* The prefixed representation String of the primitive value
* of the literal.
* @type {string}
*/
var sPrefixed =
EValuePrefixes.S_STRING + sStringValue;
return oSolutionBest.oPrimitiveValues.hasOwnProperty(
sPrefixed) &&
oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
['name',
oSolutionBest.oPrimitiveValues[sPrefixed].sName] :
['string', sStringValue];
}
|
[
"function",
"(",
"sStringValue",
")",
"{",
"var",
"sPrefixed",
"=",
"EValuePrefixes",
".",
"S_STRING",
"+",
"sStringValue",
";",
"return",
"oSolutionBest",
".",
"oPrimitiveValues",
".",
"hasOwnProperty",
"(",
"sPrefixed",
")",
"&&",
"oSolutionBest",
".",
"oPrimitiveValues",
"[",
"sPrefixed",
"]",
".",
"nSaving",
">",
"0",
"?",
"[",
"'name'",
",",
"oSolutionBest",
".",
"oPrimitiveValues",
"[",
"sPrefixed",
"]",
".",
"sName",
"]",
":",
"[",
"'string'",
",",
"sStringValue",
"]",
";",
"}"
] |
If the encountered String value is worthwhile, it is
substituted by an identifier name to which that value is
assigned.
Applies to String values.
@param {string} sStringValue The String value of the string
literal encountered.
@return {!Array} A syntactic code unit that is equivalent to
the one encountered.
@see TPrimitiveValue#nSaving
|
[
"If",
"the",
"encountered",
"String",
"value",
"is",
"worthwhile",
"it",
"is",
"substituted",
"by",
"an",
"identifier",
"name",
"to",
"which",
"that",
"value",
"is",
"assigned",
".",
"Applies",
"to",
"String",
"values",
"."
] |
97c5dcfe46fb6a43efd2cc571bb1aa8c654c1947
|
https://github.com/DevExpress/testcafe-legacy-api/blob/97c5dcfe46fb6a43efd2cc571bb1aa8c654c1947/src/compiler/tools/uglify-js/lib/consolidator.js#L739-L754
|
train
|
|
iVis-at-Bilkent/cytoscape.js-grid-guide
|
src/alignment.js
|
moveTopDown
|
function moveTopDown(node, dx, dy) {
var nodes = node.union(node.descendants());
nodes.filter(":childless").positions(function (node, i) {
if(typeof node === "number") {
node = i;
}
var pos = node.position();
return {
x: pos.x + dx,
y: pos.y + dy
};
});
}
|
javascript
|
function moveTopDown(node, dx, dy) {
var nodes = node.union(node.descendants());
nodes.filter(":childless").positions(function (node, i) {
if(typeof node === "number") {
node = i;
}
var pos = node.position();
return {
x: pos.x + dx,
y: pos.y + dy
};
});
}
|
[
"function",
"moveTopDown",
"(",
"node",
",",
"dx",
",",
"dy",
")",
"{",
"var",
"nodes",
"=",
"node",
".",
"union",
"(",
"node",
".",
"descendants",
"(",
")",
")",
";",
"nodes",
".",
"filter",
"(",
"\":childless\"",
")",
".",
"positions",
"(",
"function",
"(",
"node",
",",
"i",
")",
"{",
"if",
"(",
"typeof",
"node",
"===",
"\"number\"",
")",
"{",
"node",
"=",
"i",
";",
"}",
"var",
"pos",
"=",
"node",
".",
"position",
"(",
")",
";",
"return",
"{",
"x",
":",
"pos",
".",
"x",
"+",
"dx",
",",
"y",
":",
"pos",
".",
"y",
"+",
"dy",
"}",
";",
"}",
")",
";",
"}"
] |
Needed because parent nodes cannot be moved in Cytoscape.js < v3.2
|
[
"Needed",
"because",
"parent",
"nodes",
"cannot",
"be",
"moved",
"in",
"Cytoscape",
".",
"js",
"<",
"v3",
".",
"2"
] |
9649d89aafd702b097456adccdcf0395a818907d
|
https://github.com/iVis-at-Bilkent/cytoscape.js-grid-guide/blob/9649d89aafd702b097456adccdcf0395a818907d/src/alignment.js#L4-L17
|
train
|
forsigner/node-pngdefry
|
lib/index.js
|
getOutputDir
|
function getOutputDir(output) {
var arr = output.split(path.sep);
arr.pop();
return arr.join(path.sep);
}
|
javascript
|
function getOutputDir(output) {
var arr = output.split(path.sep);
arr.pop();
return arr.join(path.sep);
}
|
[
"function",
"getOutputDir",
"(",
"output",
")",
"{",
"var",
"arr",
"=",
"output",
".",
"split",
"(",
"path",
".",
"sep",
")",
";",
"arr",
".",
"pop",
"(",
")",
";",
"return",
"arr",
".",
"join",
"(",
"path",
".",
"sep",
")",
";",
"}"
] |
get output directory from original output
@param {string} output
@return {string} outputDir
@private
|
[
"get",
"output",
"directory",
"from",
"original",
"output"
] |
a6c0e501afb36b11af3db8f5afa59bfed71377a8
|
https://github.com/forsigner/node-pngdefry/blob/a6c0e501afb36b11af3db8f5afa59bfed71377a8/lib/index.js#L31-L35
|
train
|
forsigner/node-pngdefry
|
lib/index.js
|
getOutputFilePath
|
function getOutputFilePath(input, outputDir, suffix) {
var inputArr = input.split(path.sep);
var originFileName = inputArr[inputArr.length - 1];
var newFileName = originFileName.replace(/\.png$/, suffix + '.png');
var outputFilePath = path.join(outputDir, newFileName);
return outputFilePath;
}
|
javascript
|
function getOutputFilePath(input, outputDir, suffix) {
var inputArr = input.split(path.sep);
var originFileName = inputArr[inputArr.length - 1];
var newFileName = originFileName.replace(/\.png$/, suffix + '.png');
var outputFilePath = path.join(outputDir, newFileName);
return outputFilePath;
}
|
[
"function",
"getOutputFilePath",
"(",
"input",
",",
"outputDir",
",",
"suffix",
")",
"{",
"var",
"inputArr",
"=",
"input",
".",
"split",
"(",
"path",
".",
"sep",
")",
";",
"var",
"originFileName",
"=",
"inputArr",
"[",
"inputArr",
".",
"length",
"-",
"1",
"]",
";",
"var",
"newFileName",
"=",
"originFileName",
".",
"replace",
"(",
"/",
"\\.png$",
"/",
",",
"suffix",
"+",
"'.png'",
")",
";",
"var",
"outputFilePath",
"=",
"path",
".",
"join",
"(",
"outputDir",
",",
"newFileName",
")",
";",
"return",
"outputFilePath",
";",
"}"
] |
get temp output file path with our suffix
@param {string} output
@return {string} outputDir
@return {string} suffix
@return {string} outputFilePath
@private
|
[
"get",
"temp",
"output",
"file",
"path",
"with",
"our",
"suffix"
] |
a6c0e501afb36b11af3db8f5afa59bfed71377a8
|
https://github.com/forsigner/node-pngdefry/blob/a6c0e501afb36b11af3db8f5afa59bfed71377a8/lib/index.js#L45-L51
|
train
|
marcuswestin/fin
|
engines/redis/storage.js
|
getBytes
|
function getBytes(key, callback) {
this.redisClient.get(key, function(err, valueBytes) {
if (err) { return callback(err) }
if (!valueBytes) { return callback(null, null) }
callback(null, valueBytes.toString())
})
}
|
javascript
|
function getBytes(key, callback) {
this.redisClient.get(key, function(err, valueBytes) {
if (err) { return callback(err) }
if (!valueBytes) { return callback(null, null) }
callback(null, valueBytes.toString())
})
}
|
[
"function",
"getBytes",
"(",
"key",
",",
"callback",
")",
"{",
"this",
".",
"redisClient",
".",
"get",
"(",
"key",
",",
"function",
"(",
"err",
",",
"valueBytes",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
"}",
"if",
"(",
"!",
"valueBytes",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"null",
")",
"}",
"callback",
"(",
"null",
",",
"valueBytes",
".",
"toString",
"(",
")",
")",
"}",
")",
"}"
] |
Returns a string
|
[
"Returns",
"a",
"string"
] |
25060c404fdc8f3baf9c99ebc89fa0cb04cbfb05
|
https://github.com/marcuswestin/fin/blob/25060c404fdc8f3baf9c99ebc89fa0cb04cbfb05/engines/redis/storage.js#L43-L49
|
train
|
warehouseai/smart-private-npm
|
lib/npm-proxy.js
|
onDecision
|
function onDecision(err, target) {
//
// If there was no target then this is a 404 by definition
// even if it exists in the public registry because of a
// potential whitelist.
//
if (err || !target) {
return self.notFound(req, res, err || { message: 'Unknown pkg: ' + pkg });
}
// if X-Forwarded-Host is set, npm returns 404 {"error":"not_found","reason":"no_db_file"}
if (req.headers["x-forwarded-host"]) delete req.headers["x-forwarded-host"];
//
// If we get a valid target then we can proxy to it
//
self.log.info('[decide] %s - %s %s %s %j', address, req.method, req.url, target.vhost || target.host || target.hostname, req.headers);
self.emit('headers', req, req.headers, target);
req.headers.host = target.vhost || target.host || target.hostname;
proxy.web(req, res, {
target: target.href
});
}
|
javascript
|
function onDecision(err, target) {
//
// If there was no target then this is a 404 by definition
// even if it exists in the public registry because of a
// potential whitelist.
//
if (err || !target) {
return self.notFound(req, res, err || { message: 'Unknown pkg: ' + pkg });
}
// if X-Forwarded-Host is set, npm returns 404 {"error":"not_found","reason":"no_db_file"}
if (req.headers["x-forwarded-host"]) delete req.headers["x-forwarded-host"];
//
// If we get a valid target then we can proxy to it
//
self.log.info('[decide] %s - %s %s %s %j', address, req.method, req.url, target.vhost || target.host || target.hostname, req.headers);
self.emit('headers', req, req.headers, target);
req.headers.host = target.vhost || target.host || target.hostname;
proxy.web(req, res, {
target: target.href
});
}
|
[
"function",
"onDecision",
"(",
"err",
",",
"target",
")",
"{",
"if",
"(",
"err",
"||",
"!",
"target",
")",
"{",
"return",
"self",
".",
"notFound",
"(",
"req",
",",
"res",
",",
"err",
"||",
"{",
"message",
":",
"'Unknown pkg: '",
"+",
"pkg",
"}",
")",
";",
"}",
"if",
"(",
"req",
".",
"headers",
"[",
"\"x-forwarded-host\"",
"]",
")",
"delete",
"req",
".",
"headers",
"[",
"\"x-forwarded-host\"",
"]",
";",
"self",
".",
"log",
".",
"info",
"(",
"'[decide] %s - %s %s %s %j'",
",",
"address",
",",
"req",
".",
"method",
",",
"req",
".",
"url",
",",
"target",
".",
"vhost",
"||",
"target",
".",
"host",
"||",
"target",
".",
"hostname",
",",
"req",
".",
"headers",
")",
";",
"self",
".",
"emit",
"(",
"'headers'",
",",
"req",
",",
"req",
".",
"headers",
",",
"target",
")",
";",
"req",
".",
"headers",
".",
"host",
"=",
"target",
".",
"vhost",
"||",
"target",
".",
"host",
"||",
"target",
".",
"hostname",
";",
"proxy",
".",
"web",
"(",
"req",
",",
"res",
",",
"{",
"target",
":",
"target",
".",
"href",
"}",
")",
";",
"}"
] |
Proxy or serve not found based on the decision
|
[
"Proxy",
"or",
"serve",
"not",
"found",
"based",
"on",
"the",
"decision"
] |
c5e1f2bc62fbb51f6ee56f93ec6e24753849c9b7
|
https://github.com/warehouseai/smart-private-npm/blob/c5e1f2bc62fbb51f6ee56f93ec6e24753849c9b7/lib/npm-proxy.js#L245-L269
|
train
|
sassoftware/restaf
|
src/serverCalls/index.js
|
implicitGrant
|
function implicitGrant (iconfig) {
/* */
let link = iconfig.link ;
window.location.href = `${iconfig.host + link.href}?response_type=${link.responseType}&client_id=${iconfig.clientID}`;
return new Promise.resolve()
}
|
javascript
|
function implicitGrant (iconfig) {
/* */
let link = iconfig.link ;
window.location.href = `${iconfig.host + link.href}?response_type=${link.responseType}&client_id=${iconfig.clientID}`;
return new Promise.resolve()
}
|
[
"function",
"implicitGrant",
"(",
"iconfig",
")",
"{",
"let",
"link",
"=",
"iconfig",
".",
"link",
";",
"window",
".",
"location",
".",
"href",
"=",
"`",
"${",
"iconfig",
".",
"host",
"+",
"link",
".",
"href",
"}",
"${",
"link",
".",
"responseType",
"}",
"${",
"iconfig",
".",
"clientID",
"}",
"`",
";",
"return",
"new",
"Promise",
".",
"resolve",
"(",
")",
"}"
] |
Code below is for experimenting.
|
[
"Code",
"below",
"is",
"for",
"experimenting",
"."
] |
fc3122184ab8cf32dd431f0b832b87d156873d0b
|
https://github.com/sassoftware/restaf/blob/fc3122184ab8cf32dd431f0b832b87d156873d0b/src/serverCalls/index.js#L282-L289
|
train
|
sassoftware/restaf
|
src/store/apiSubmit.js
|
apiSubmit
|
async function apiSubmit (store, iroute, payload, delay, jobContext, onCompletion, progress){
if (progress) {
progress('pending', jobContext);
}
let job = await iapiCall(store, iroute, API_CALL, payload, 0, null, null, jobContext);
if (job.links('state')) {
let status = await jobState(store, job, null, 'wait', delay, progress, jobContext);
completion(store, onCompletion,status.data,status.job, jobContext);
return status.job;
} else {
completion(store, onCompletion, 'unknown', job, jobContext);
return job;
}
}
|
javascript
|
async function apiSubmit (store, iroute, payload, delay, jobContext, onCompletion, progress){
if (progress) {
progress('pending', jobContext);
}
let job = await iapiCall(store, iroute, API_CALL, payload, 0, null, null, jobContext);
if (job.links('state')) {
let status = await jobState(store, job, null, 'wait', delay, progress, jobContext);
completion(store, onCompletion,status.data,status.job, jobContext);
return status.job;
} else {
completion(store, onCompletion, 'unknown', job, jobContext);
return job;
}
}
|
[
"async",
"function",
"apiSubmit",
"(",
"store",
",",
"iroute",
",",
"payload",
",",
"delay",
",",
"jobContext",
",",
"onCompletion",
",",
"progress",
")",
"{",
"if",
"(",
"progress",
")",
"{",
"progress",
"(",
"'pending'",
",",
"jobContext",
")",
";",
"}",
"let",
"job",
"=",
"await",
"iapiCall",
"(",
"store",
",",
"iroute",
",",
"API_CALL",
",",
"payload",
",",
"0",
",",
"null",
",",
"null",
",",
"jobContext",
")",
";",
"if",
"(",
"job",
".",
"links",
"(",
"'state'",
")",
")",
"{",
"let",
"status",
"=",
"await",
"jobState",
"(",
"store",
",",
"job",
",",
"null",
",",
"'wait'",
",",
"delay",
",",
"progress",
",",
"jobContext",
")",
";",
"completion",
"(",
"store",
",",
"onCompletion",
",",
"status",
".",
"data",
",",
"status",
".",
"job",
",",
"jobContext",
")",
";",
"return",
"status",
".",
"job",
";",
"}",
"else",
"{",
"completion",
"(",
"store",
",",
"onCompletion",
",",
"'unknown'",
",",
"job",
",",
"jobContext",
")",
";",
"return",
"job",
";",
"}",
"}"
] |
store, iroute, actionType, payload, delay, eventHandler, parentRoute, jobContext
|
[
"store",
"iroute",
"actionType",
"payload",
"delay",
"eventHandler",
"parentRoute",
"jobContext"
] |
fc3122184ab8cf32dd431f0b832b87d156873d0b
|
https://github.com/sassoftware/restaf/blob/fc3122184ab8cf32dd431f0b832b87d156873d0b/src/store/apiSubmit.js#L26-L43
|
train
|
m19c/gulp-run
|
command.js
|
Command
|
function Command(command, options) {
var previousPath;
this.command = command;
// We're on Windows if `process.platform` starts with "win", i.e. "win32".
this.isWindows = (process.platform.lastIndexOf('win') === 0);
// the cwd and environment of the command are the same as the main node
// process by default.
this.options = defaults(options || {}, {
cwd: process.cwd(),
env: process.env,
verbosity: (options && options.silent) ? 1 : 2,
usePowerShell: false
});
// include node_modules/.bin on the path when we execute the command.
previousPath = this.options.env.PATH;
this.options.env.PATH = path.join(this.options.cwd, 'node_modules', '.bin');
this.options.env.PATH += path.delimiter;
this.options.env.PATH += previousPath;
}
|
javascript
|
function Command(command, options) {
var previousPath;
this.command = command;
// We're on Windows if `process.platform` starts with "win", i.e. "win32".
this.isWindows = (process.platform.lastIndexOf('win') === 0);
// the cwd and environment of the command are the same as the main node
// process by default.
this.options = defaults(options || {}, {
cwd: process.cwd(),
env: process.env,
verbosity: (options && options.silent) ? 1 : 2,
usePowerShell: false
});
// include node_modules/.bin on the path when we execute the command.
previousPath = this.options.env.PATH;
this.options.env.PATH = path.join(this.options.cwd, 'node_modules', '.bin');
this.options.env.PATH += path.delimiter;
this.options.env.PATH += previousPath;
}
|
[
"function",
"Command",
"(",
"command",
",",
"options",
")",
"{",
"var",
"previousPath",
";",
"this",
".",
"command",
"=",
"command",
";",
"this",
".",
"isWindows",
"=",
"(",
"process",
".",
"platform",
".",
"lastIndexOf",
"(",
"'win'",
")",
"===",
"0",
")",
";",
"this",
".",
"options",
"=",
"defaults",
"(",
"options",
"||",
"{",
"}",
",",
"{",
"cwd",
":",
"process",
".",
"cwd",
"(",
")",
",",
"env",
":",
"process",
".",
"env",
",",
"verbosity",
":",
"(",
"options",
"&&",
"options",
".",
"silent",
")",
"?",
"1",
":",
"2",
",",
"usePowerShell",
":",
"false",
"}",
")",
";",
"previousPath",
"=",
"this",
".",
"options",
".",
"env",
".",
"PATH",
";",
"this",
".",
"options",
".",
"env",
".",
"PATH",
"=",
"path",
".",
"join",
"(",
"this",
".",
"options",
".",
"cwd",
",",
"'node_modules'",
",",
"'.bin'",
")",
";",
"this",
".",
"options",
".",
"env",
".",
"PATH",
"+=",
"path",
".",
"delimiter",
";",
"this",
".",
"options",
".",
"env",
".",
"PATH",
"+=",
"previousPath",
";",
"}"
] |
Creates a new `gulp-run` command.
@param {string} command
@param {object} options
|
[
"Creates",
"a",
"new",
"gulp",
"-",
"run",
"command",
"."
] |
f58b6dbeb2d9f1c21579a7654d28ce6764f3a541
|
https://github.com/m19c/gulp-run/blob/f58b6dbeb2d9f1c21579a7654d28ce6764f3a541/command.js#L16-L38
|
train
|
m19c/gulp-run
|
index.js
|
GulpRunner
|
function GulpRunner(template, options) {
if (!(this instanceof GulpRunner)) {
return new GulpRunner(template, options);
}
this.command = new Command(template, options || {});
Transform.call(this, { objectMode: true });
}
|
javascript
|
function GulpRunner(template, options) {
if (!(this instanceof GulpRunner)) {
return new GulpRunner(template, options);
}
this.command = new Command(template, options || {});
Transform.call(this, { objectMode: true });
}
|
[
"function",
"GulpRunner",
"(",
"template",
",",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"GulpRunner",
")",
")",
"{",
"return",
"new",
"GulpRunner",
"(",
"template",
",",
"options",
")",
";",
"}",
"this",
".",
"command",
"=",
"new",
"Command",
"(",
"template",
",",
"options",
"||",
"{",
"}",
")",
";",
"Transform",
".",
"call",
"(",
"this",
",",
"{",
"objectMode",
":",
"true",
"}",
")",
";",
"}"
] |
Creates a GulpRunner.
A GulpRunner is a Vinyl transform stream that spawns a child process to
transform the file. A separate process is spawned to handle each file
passing through the stream.
@param {string} template
@param {object} options
|
[
"Creates",
"a",
"GulpRunner",
"."
] |
f58b6dbeb2d9f1c21579a7654d28ce6764f3a541
|
https://github.com/m19c/gulp-run/blob/f58b6dbeb2d9f1c21579a7654d28ce6764f3a541/index.js#L20-L27
|
train
|
gruntjs/grunt-init
|
tasks/init.js
|
function(arg1) {
if (arg1 == null) { return null; }
var args = [name, 'root'].concat(grunt.util.toArray(arguments));
return helpers.getFile.apply(helpers, args);
}
|
javascript
|
function(arg1) {
if (arg1 == null) { return null; }
var args = [name, 'root'].concat(grunt.util.toArray(arguments));
return helpers.getFile.apply(helpers, args);
}
|
[
"function",
"(",
"arg1",
")",
"{",
"if",
"(",
"arg1",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"var",
"args",
"=",
"[",
"name",
",",
"'root'",
"]",
".",
"concat",
"(",
"grunt",
".",
"util",
".",
"toArray",
"(",
"arguments",
")",
")",
";",
"return",
"helpers",
".",
"getFile",
".",
"apply",
"(",
"helpers",
",",
"args",
")",
";",
"}"
] |
Search init template paths for filename.
|
[
"Search",
"init",
"template",
"paths",
"for",
"filename",
"."
] |
cbec886f26dce52d19c828df3fed031ce9767663
|
https://github.com/gruntjs/grunt-init/blob/cbec886f26dce52d19c828df3fed031ce9767663/tasks/init.js#L342-L346
|
train
|
|
gruntjs/grunt-init
|
tasks/init.js
|
function(files, licenses) {
licenses.forEach(function(license) {
var fileobj = helpers.expand({filter: 'isFile'}, 'licenses/LICENSE-' + license)[0];
if(fileobj) {
files['LICENSE-' + license] = fileobj.rel;
}
});
}
|
javascript
|
function(files, licenses) {
licenses.forEach(function(license) {
var fileobj = helpers.expand({filter: 'isFile'}, 'licenses/LICENSE-' + license)[0];
if(fileobj) {
files['LICENSE-' + license] = fileobj.rel;
}
});
}
|
[
"function",
"(",
"files",
",",
"licenses",
")",
"{",
"licenses",
".",
"forEach",
"(",
"function",
"(",
"license",
")",
"{",
"var",
"fileobj",
"=",
"helpers",
".",
"expand",
"(",
"{",
"filter",
":",
"'isFile'",
"}",
",",
"'licenses/LICENSE-'",
"+",
"license",
")",
"[",
"0",
"]",
";",
"if",
"(",
"fileobj",
")",
"{",
"files",
"[",
"'LICENSE-'",
"+",
"license",
"]",
"=",
"fileobj",
".",
"rel",
";",
"}",
"}",
")",
";",
"}"
] |
Given some number of licenses, add properly-named license files to the files object.
|
[
"Given",
"some",
"number",
"of",
"licenses",
"add",
"properly",
"-",
"named",
"license",
"files",
"to",
"the",
"files",
"object",
"."
] |
cbec886f26dce52d19c828df3fed031ce9767663
|
https://github.com/gruntjs/grunt-init/blob/cbec886f26dce52d19c828df3fed031ce9767663/tasks/init.js#L351-L358
|
train
|
|
gruntjs/grunt-init
|
tasks/init.js
|
function(srcpath, destpath, options) {
// Destpath is optional.
if (typeof destpath !== 'string') {
options = destpath;
destpath = srcpath;
}
// Ensure srcpath is absolute.
if (!grunt.file.isPathAbsolute(srcpath)) {
srcpath = init.srcpath(srcpath);
}
// Use placeholder file if no src exists.
if (!srcpath) {
srcpath = helpers.getFile('misc/placeholder');
}
grunt.verbose.or.write('Writing ' + destpath + '...');
try {
grunt.file.copy(srcpath, init.destpath(destpath), options);
grunt.verbose.or.ok();
} catch(e) {
grunt.verbose.or.error().error(e);
throw e;
}
}
|
javascript
|
function(srcpath, destpath, options) {
// Destpath is optional.
if (typeof destpath !== 'string') {
options = destpath;
destpath = srcpath;
}
// Ensure srcpath is absolute.
if (!grunt.file.isPathAbsolute(srcpath)) {
srcpath = init.srcpath(srcpath);
}
// Use placeholder file if no src exists.
if (!srcpath) {
srcpath = helpers.getFile('misc/placeholder');
}
grunt.verbose.or.write('Writing ' + destpath + '...');
try {
grunt.file.copy(srcpath, init.destpath(destpath), options);
grunt.verbose.or.ok();
} catch(e) {
grunt.verbose.or.error().error(e);
throw e;
}
}
|
[
"function",
"(",
"srcpath",
",",
"destpath",
",",
"options",
")",
"{",
"if",
"(",
"typeof",
"destpath",
"!==",
"'string'",
")",
"{",
"options",
"=",
"destpath",
";",
"destpath",
"=",
"srcpath",
";",
"}",
"if",
"(",
"!",
"grunt",
".",
"file",
".",
"isPathAbsolute",
"(",
"srcpath",
")",
")",
"{",
"srcpath",
"=",
"init",
".",
"srcpath",
"(",
"srcpath",
")",
";",
"}",
"if",
"(",
"!",
"srcpath",
")",
"{",
"srcpath",
"=",
"helpers",
".",
"getFile",
"(",
"'misc/placeholder'",
")",
";",
"}",
"grunt",
".",
"verbose",
".",
"or",
".",
"write",
"(",
"'Writing '",
"+",
"destpath",
"+",
"'...'",
")",
";",
"try",
"{",
"grunt",
".",
"file",
".",
"copy",
"(",
"srcpath",
",",
"init",
".",
"destpath",
"(",
"destpath",
")",
",",
"options",
")",
";",
"grunt",
".",
"verbose",
".",
"or",
".",
"ok",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"grunt",
".",
"verbose",
".",
"or",
".",
"error",
"(",
")",
".",
"error",
"(",
"e",
")",
";",
"throw",
"e",
";",
"}",
"}"
] |
Given an absolute or relative source path, and an optional relative destination path, copy a file, optionally processing it through the passed callback.
|
[
"Given",
"an",
"absolute",
"or",
"relative",
"source",
"path",
"and",
"an",
"optional",
"relative",
"destination",
"path",
"copy",
"a",
"file",
"optionally",
"processing",
"it",
"through",
"the",
"passed",
"callback",
"."
] |
cbec886f26dce52d19c828df3fed031ce9767663
|
https://github.com/gruntjs/grunt-init/blob/cbec886f26dce52d19c828df3fed031ce9767663/tasks/init.js#L362-L384
|
train
|
|
gruntjs/grunt-init
|
tasks/init.js
|
function(files, props, options) {
options = _.defaults(options || {}, {
process: function(contents) {
return grunt.template.process(contents, {data: props, delimiters: 'init'});
}
});
Object.keys(files).forEach(function(destpath) {
var o = Object.create(options);
var srcpath = files[destpath];
// If srcpath is relative, match it against options.noProcess if
// necessary, then make srcpath absolute.
var relpath;
if (srcpath && !grunt.file.isPathAbsolute(srcpath)) {
if (o.noProcess) {
relpath = srcpath.slice(pathPrefix.length);
o.noProcess = grunt.file.isMatch({matchBase: true}, o.noProcess, relpath);
}
srcpath = helpers.getFile(srcpath);
}
// Copy!
init.copy(srcpath, destpath, o);
});
}
|
javascript
|
function(files, props, options) {
options = _.defaults(options || {}, {
process: function(contents) {
return grunt.template.process(contents, {data: props, delimiters: 'init'});
}
});
Object.keys(files).forEach(function(destpath) {
var o = Object.create(options);
var srcpath = files[destpath];
// If srcpath is relative, match it against options.noProcess if
// necessary, then make srcpath absolute.
var relpath;
if (srcpath && !grunt.file.isPathAbsolute(srcpath)) {
if (o.noProcess) {
relpath = srcpath.slice(pathPrefix.length);
o.noProcess = grunt.file.isMatch({matchBase: true}, o.noProcess, relpath);
}
srcpath = helpers.getFile(srcpath);
}
// Copy!
init.copy(srcpath, destpath, o);
});
}
|
[
"function",
"(",
"files",
",",
"props",
",",
"options",
")",
"{",
"options",
"=",
"_",
".",
"defaults",
"(",
"options",
"||",
"{",
"}",
",",
"{",
"process",
":",
"function",
"(",
"contents",
")",
"{",
"return",
"grunt",
".",
"template",
".",
"process",
"(",
"contents",
",",
"{",
"data",
":",
"props",
",",
"delimiters",
":",
"'init'",
"}",
")",
";",
"}",
"}",
")",
";",
"Object",
".",
"keys",
"(",
"files",
")",
".",
"forEach",
"(",
"function",
"(",
"destpath",
")",
"{",
"var",
"o",
"=",
"Object",
".",
"create",
"(",
"options",
")",
";",
"var",
"srcpath",
"=",
"files",
"[",
"destpath",
"]",
";",
"var",
"relpath",
";",
"if",
"(",
"srcpath",
"&&",
"!",
"grunt",
".",
"file",
".",
"isPathAbsolute",
"(",
"srcpath",
")",
")",
"{",
"if",
"(",
"o",
".",
"noProcess",
")",
"{",
"relpath",
"=",
"srcpath",
".",
"slice",
"(",
"pathPrefix",
".",
"length",
")",
";",
"o",
".",
"noProcess",
"=",
"grunt",
".",
"file",
".",
"isMatch",
"(",
"{",
"matchBase",
":",
"true",
"}",
",",
"o",
".",
"noProcess",
",",
"relpath",
")",
";",
"}",
"srcpath",
"=",
"helpers",
".",
"getFile",
"(",
"srcpath",
")",
";",
"}",
"init",
".",
"copy",
"(",
"srcpath",
",",
"destpath",
",",
"o",
")",
";",
"}",
")",
";",
"}"
] |
Iterate over all files in the passed object, copying the source file to the destination, processing the contents.
|
[
"Iterate",
"over",
"all",
"files",
"in",
"the",
"passed",
"object",
"copying",
"the",
"source",
"file",
"to",
"the",
"destination",
"processing",
"the",
"contents",
"."
] |
cbec886f26dce52d19c828df3fed031ce9767663
|
https://github.com/gruntjs/grunt-init/blob/cbec886f26dce52d19c828df3fed031ce9767663/tasks/init.js#L387-L409
|
train
|
|
vskosp/vsGoogleAutocomplete
|
dist/vs-autocomplete-validator.js
|
Validator
|
function Validator(validatorsNamesList) {
// add default embedded validator name
validatorsNamesList.unshift('vsGooglePlace');
this._embeddedValidators = vsEmbeddedValidatorsInjector.get(validatorsNamesList);
this.error = {};
this.valid = true;
}
|
javascript
|
function Validator(validatorsNamesList) {
// add default embedded validator name
validatorsNamesList.unshift('vsGooglePlace');
this._embeddedValidators = vsEmbeddedValidatorsInjector.get(validatorsNamesList);
this.error = {};
this.valid = true;
}
|
[
"function",
"Validator",
"(",
"validatorsNamesList",
")",
"{",
"validatorsNamesList",
".",
"unshift",
"(",
"'vsGooglePlace'",
")",
";",
"this",
".",
"_embeddedValidators",
"=",
"vsEmbeddedValidatorsInjector",
".",
"get",
"(",
"validatorsNamesList",
")",
";",
"this",
".",
"error",
"=",
"{",
"}",
";",
"this",
".",
"valid",
"=",
"true",
";",
"}"
] |
Class making validator associated with vsGoogleAutocomplete controller.
@constructor
@param {Array.<string>} validatorsNamesList - List of embedded validator names.
|
[
"Class",
"making",
"validator",
"associated",
"with",
"vsGoogleAutocomplete",
"controller",
"."
] |
4ec8b242904d3a94761f4278989f161c910f71ac
|
https://github.com/vskosp/vsGoogleAutocomplete/blob/4ec8b242904d3a94761f4278989f161c910f71ac/dist/vs-autocomplete-validator.js#L60-L67
|
train
|
vskosp/vsGoogleAutocomplete
|
dist/vs-autocomplete-validator.js
|
parseValidatorNames
|
function parseValidatorNames(attrs) {
var attrValue = attrs.vsAutocompleteValidator,
validatorNames = (attrValue!=="") ? attrValue.trim().split(',') : [];
// normalize validator names
for (var i = 0; i < validatorNames.length; i++) {
validatorNames[i] = attrs.$normalize(validatorNames[i]);
}
return validatorNames;
}
|
javascript
|
function parseValidatorNames(attrs) {
var attrValue = attrs.vsAutocompleteValidator,
validatorNames = (attrValue!=="") ? attrValue.trim().split(',') : [];
// normalize validator names
for (var i = 0; i < validatorNames.length; i++) {
validatorNames[i] = attrs.$normalize(validatorNames[i]);
}
return validatorNames;
}
|
[
"function",
"parseValidatorNames",
"(",
"attrs",
")",
"{",
"var",
"attrValue",
"=",
"attrs",
".",
"vsAutocompleteValidator",
",",
"validatorNames",
"=",
"(",
"attrValue",
"!==",
"\"\"",
")",
"?",
"attrValue",
".",
"trim",
"(",
")",
".",
"split",
"(",
"','",
")",
":",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"validatorNames",
".",
"length",
";",
"i",
"++",
")",
"{",
"validatorNames",
"[",
"i",
"]",
"=",
"attrs",
".",
"$normalize",
"(",
"validatorNames",
"[",
"i",
"]",
")",
";",
"}",
"return",
"validatorNames",
";",
"}"
] |
Parse validator names from attribute.
@param {$compile.directive.Attributes} attrs Element attributes
@return {Array.<string>} Returns array of normalized validator names.
|
[
"Parse",
"validator",
"names",
"from",
"attribute",
"."
] |
4ec8b242904d3a94761f4278989f161c910f71ac
|
https://github.com/vskosp/vsGoogleAutocomplete/blob/4ec8b242904d3a94761f4278989f161c910f71ac/dist/vs-autocomplete-validator.js#L126-L136
|
train
|
mongodb-js/extended-json
|
lib/serialize.js
|
serialize
|
function serialize(value) {
if (Array.isArray(value) === true) {
return serializeArray(value);
}
if (isObject(value) === false) {
return serializePrimitive(value);
}
return serializeObject(value);
}
|
javascript
|
function serialize(value) {
if (Array.isArray(value) === true) {
return serializeArray(value);
}
if (isObject(value) === false) {
return serializePrimitive(value);
}
return serializeObject(value);
}
|
[
"function",
"serialize",
"(",
"value",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"value",
")",
"===",
"true",
")",
"{",
"return",
"serializeArray",
"(",
"value",
")",
";",
"}",
"if",
"(",
"isObject",
"(",
"value",
")",
"===",
"false",
")",
"{",
"return",
"serializePrimitive",
"(",
"value",
")",
";",
"}",
"return",
"serializeObject",
"(",
"value",
")",
";",
"}"
] |
Format values with extra extended json type data.
@param {Any} value - What to wrap as a `{$<type>: <encoded>}` object.
@return {Any}
@api private
|
[
"Format",
"values",
"with",
"extra",
"extended",
"json",
"type",
"data",
"."
] |
3116e58531c504d9c9f1c6a5f53c24bb7d1ec65f
|
https://github.com/mongodb-js/extended-json/blob/3116e58531c504d9c9f1c6a5f53c24bb7d1ec65f/lib/serialize.js#L44-L52
|
train
|
canjs/can-compile
|
example/js/components/todo-app.js
|
function () {
var filter = can.route.attr('filter');
return this.todos.filter(function (todo) {
if (filter === 'completed') {
return todo.attr('complete');
}
if (filter === 'active') {
return !todo.attr('complete');
}
return true;
});
}
|
javascript
|
function () {
var filter = can.route.attr('filter');
return this.todos.filter(function (todo) {
if (filter === 'completed') {
return todo.attr('complete');
}
if (filter === 'active') {
return !todo.attr('complete');
}
return true;
});
}
|
[
"function",
"(",
")",
"{",
"var",
"filter",
"=",
"can",
".",
"route",
".",
"attr",
"(",
"'filter'",
")",
";",
"return",
"this",
".",
"todos",
".",
"filter",
"(",
"function",
"(",
"todo",
")",
"{",
"if",
"(",
"filter",
"===",
"'completed'",
")",
"{",
"return",
"todo",
".",
"attr",
"(",
"'complete'",
")",
";",
"}",
"if",
"(",
"filter",
"===",
"'active'",
")",
"{",
"return",
"!",
"todo",
".",
"attr",
"(",
"'complete'",
")",
";",
"}",
"return",
"true",
";",
"}",
")",
";",
"}"
] |
Returns a list of Todos filtered based on the route
|
[
"Returns",
"a",
"list",
"of",
"Todos",
"filtered",
"based",
"on",
"the",
"route"
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/js/components/todo-app.js#L27-L40
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(el, val) {
if (val == null || val === "") {
el.removeAttribute("src");
return null;
} else {
el.setAttribute("src", val);
return val;
}
}
|
javascript
|
function(el, val) {
if (val == null || val === "") {
el.removeAttribute("src");
return null;
} else {
el.setAttribute("src", val);
return val;
}
}
|
[
"function",
"(",
"el",
",",
"val",
")",
"{",
"if",
"(",
"val",
"==",
"null",
"||",
"val",
"===",
"\"\"",
")",
"{",
"el",
".",
"removeAttribute",
"(",
"\"src\"",
")",
";",
"return",
"null",
";",
"}",
"else",
"{",
"el",
".",
"setAttribute",
"(",
"\"src\"",
",",
"val",
")",
";",
"return",
"val",
";",
"}",
"}"
] |
For the `src` attribute we are using a setter function to prevent values such as an empty string or null from being set. An `img` tag attempts to fetch the `src` when it is set, so we need to prevent that from happening by removing the attribute instead.
|
[
"For",
"the",
"src",
"attribute",
"we",
"are",
"using",
"a",
"setter",
"function",
"to",
"prevent",
"values",
"such",
"as",
"an",
"empty",
"string",
"or",
"null",
"from",
"being",
"set",
".",
"An",
"img",
"tag",
"attempts",
"to",
"fetch",
"the",
"src",
"when",
"it",
"is",
"set",
"so",
"we",
"need",
"to",
"prevent",
"that",
"from",
"happening",
"by",
"removing",
"the",
"attribute",
"instead",
"."
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L9149-L9157
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function() {
if (arguments.length === 0 && can.Control && this instanceof can.Control) {
return can.Control.prototype.on.call(this);
} else {
return can.addEvent.apply(this, arguments);
}
}
|
javascript
|
function() {
if (arguments.length === 0 && can.Control && this instanceof can.Control) {
return can.Control.prototype.on.call(this);
} else {
return can.addEvent.apply(this, arguments);
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"0",
"&&",
"can",
".",
"Control",
"&&",
"this",
"instanceof",
"can",
".",
"Control",
")",
"{",
"return",
"can",
".",
"Control",
".",
"prototype",
".",
"on",
".",
"call",
"(",
"this",
")",
";",
"}",
"else",
"{",
"return",
"can",
".",
"addEvent",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
"}"
] |
Event method aliases
|
[
"Event",
"method",
"aliases"
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L9461-L9467
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(fullName, klass, proto) {
// Figure out what was passed and normalize it.
if (typeof fullName !== 'string') {
proto = klass;
klass = fullName;
fullName = null;
}
if (!proto) {
proto = klass;
klass = null;
}
proto = proto || {};
var _super_class = this,
_super = this.prototype,
parts, current, _fullName, _shortName, name, shortName, namespace, prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor).
prototype = this.instance();
// Copy the properties over onto the new prototype.
can.Construct._inherit(proto, _super, prototype);
// The dummy class constructor.
function Constructor() {
// All construction is actually done in the init method.
if (!initializing) {
return this.constructor !== Constructor &&
// We are being called without `new` or we are extending.
arguments.length && Constructor.constructorExtends ? Constructor.extend.apply(Constructor, arguments) :
// We are being called with `new`.
Constructor.newInstance.apply(Constructor, arguments);
}
}
// Copy old stuff onto class (can probably be merged w/ inherit)
for (name in _super_class) {
if (_super_class.hasOwnProperty(name)) {
Constructor[name] = _super_class[name];
}
}
// Copy new static properties on class.
can.Construct._inherit(klass, _super_class, Constructor);
// Setup namespaces.
if (fullName) {
parts = fullName.split('.');
shortName = parts.pop();
current = can.getObject(parts.join('.'), window, true);
namespace = current;
_fullName = can.underscore(fullName.replace(/\./g, "_"));
_shortName = can.underscore(shortName);
current[shortName] = Constructor;
}
// Set things that shouldn't be overwritten.
can.extend(Constructor, {
constructor: Constructor,
prototype: prototype,
namespace: namespace,
_shortName: _shortName,
fullName: fullName,
_fullName: _fullName
});
// Dojo and YUI extend undefined
if (shortName !== undefined) {
Constructor.shortName = shortName;
}
// Make sure our prototype looks nice.
Constructor.prototype.constructor = Constructor;
// Call the class `setup` and `init`
var t = [_super_class].concat(can.makeArray(arguments)),
args = Constructor.setup.apply(Constructor, t);
if (Constructor.init) {
Constructor.init.apply(Constructor, args || t);
}
return Constructor;
}
|
javascript
|
function(fullName, klass, proto) {
// Figure out what was passed and normalize it.
if (typeof fullName !== 'string') {
proto = klass;
klass = fullName;
fullName = null;
}
if (!proto) {
proto = klass;
klass = null;
}
proto = proto || {};
var _super_class = this,
_super = this.prototype,
parts, current, _fullName, _shortName, name, shortName, namespace, prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor).
prototype = this.instance();
// Copy the properties over onto the new prototype.
can.Construct._inherit(proto, _super, prototype);
// The dummy class constructor.
function Constructor() {
// All construction is actually done in the init method.
if (!initializing) {
return this.constructor !== Constructor &&
// We are being called without `new` or we are extending.
arguments.length && Constructor.constructorExtends ? Constructor.extend.apply(Constructor, arguments) :
// We are being called with `new`.
Constructor.newInstance.apply(Constructor, arguments);
}
}
// Copy old stuff onto class (can probably be merged w/ inherit)
for (name in _super_class) {
if (_super_class.hasOwnProperty(name)) {
Constructor[name] = _super_class[name];
}
}
// Copy new static properties on class.
can.Construct._inherit(klass, _super_class, Constructor);
// Setup namespaces.
if (fullName) {
parts = fullName.split('.');
shortName = parts.pop();
current = can.getObject(parts.join('.'), window, true);
namespace = current;
_fullName = can.underscore(fullName.replace(/\./g, "_"));
_shortName = can.underscore(shortName);
current[shortName] = Constructor;
}
// Set things that shouldn't be overwritten.
can.extend(Constructor, {
constructor: Constructor,
prototype: prototype,
namespace: namespace,
_shortName: _shortName,
fullName: fullName,
_fullName: _fullName
});
// Dojo and YUI extend undefined
if (shortName !== undefined) {
Constructor.shortName = shortName;
}
// Make sure our prototype looks nice.
Constructor.prototype.constructor = Constructor;
// Call the class `setup` and `init`
var t = [_super_class].concat(can.makeArray(arguments)),
args = Constructor.setup.apply(Constructor, t);
if (Constructor.init) {
Constructor.init.apply(Constructor, args || t);
}
return Constructor;
}
|
[
"function",
"(",
"fullName",
",",
"klass",
",",
"proto",
")",
"{",
"if",
"(",
"typeof",
"fullName",
"!==",
"'string'",
")",
"{",
"proto",
"=",
"klass",
";",
"klass",
"=",
"fullName",
";",
"fullName",
"=",
"null",
";",
"}",
"if",
"(",
"!",
"proto",
")",
"{",
"proto",
"=",
"klass",
";",
"klass",
"=",
"null",
";",
"}",
"proto",
"=",
"proto",
"||",
"{",
"}",
";",
"var",
"_super_class",
"=",
"this",
",",
"_super",
"=",
"this",
".",
"prototype",
",",
"parts",
",",
"current",
",",
"_fullName",
",",
"_shortName",
",",
"name",
",",
"shortName",
",",
"namespace",
",",
"prototype",
";",
"prototype",
"=",
"this",
".",
"instance",
"(",
")",
";",
"can",
".",
"Construct",
".",
"_inherit",
"(",
"proto",
",",
"_super",
",",
"prototype",
")",
";",
"function",
"Constructor",
"(",
")",
"{",
"if",
"(",
"!",
"initializing",
")",
"{",
"return",
"this",
".",
"constructor",
"!==",
"Constructor",
"&&",
"arguments",
".",
"length",
"&&",
"Constructor",
".",
"constructorExtends",
"?",
"Constructor",
".",
"extend",
".",
"apply",
"(",
"Constructor",
",",
"arguments",
")",
":",
"Constructor",
".",
"newInstance",
".",
"apply",
"(",
"Constructor",
",",
"arguments",
")",
";",
"}",
"}",
"for",
"(",
"name",
"in",
"_super_class",
")",
"{",
"if",
"(",
"_super_class",
".",
"hasOwnProperty",
"(",
"name",
")",
")",
"{",
"Constructor",
"[",
"name",
"]",
"=",
"_super_class",
"[",
"name",
"]",
";",
"}",
"}",
"can",
".",
"Construct",
".",
"_inherit",
"(",
"klass",
",",
"_super_class",
",",
"Constructor",
")",
";",
"if",
"(",
"fullName",
")",
"{",
"parts",
"=",
"fullName",
".",
"split",
"(",
"'.'",
")",
";",
"shortName",
"=",
"parts",
".",
"pop",
"(",
")",
";",
"current",
"=",
"can",
".",
"getObject",
"(",
"parts",
".",
"join",
"(",
"'.'",
")",
",",
"window",
",",
"true",
")",
";",
"namespace",
"=",
"current",
";",
"_fullName",
"=",
"can",
".",
"underscore",
"(",
"fullName",
".",
"replace",
"(",
"/",
"\\.",
"/",
"g",
",",
"\"_\"",
")",
")",
";",
"_shortName",
"=",
"can",
".",
"underscore",
"(",
"shortName",
")",
";",
"current",
"[",
"shortName",
"]",
"=",
"Constructor",
";",
"}",
"can",
".",
"extend",
"(",
"Constructor",
",",
"{",
"constructor",
":",
"Constructor",
",",
"prototype",
":",
"prototype",
",",
"namespace",
":",
"namespace",
",",
"_shortName",
":",
"_shortName",
",",
"fullName",
":",
"fullName",
",",
"_fullName",
":",
"_fullName",
"}",
")",
";",
"if",
"(",
"shortName",
"!==",
"undefined",
")",
"{",
"Constructor",
".",
"shortName",
"=",
"shortName",
";",
"}",
"Constructor",
".",
"prototype",
".",
"constructor",
"=",
"Constructor",
";",
"var",
"t",
"=",
"[",
"_super_class",
"]",
".",
"concat",
"(",
"can",
".",
"makeArray",
"(",
"arguments",
")",
")",
",",
"args",
"=",
"Constructor",
".",
"setup",
".",
"apply",
"(",
"Constructor",
",",
"t",
")",
";",
"if",
"(",
"Constructor",
".",
"init",
")",
"{",
"Constructor",
".",
"init",
".",
"apply",
"(",
"Constructor",
",",
"args",
"||",
"t",
")",
";",
"}",
"return",
"Constructor",
";",
"}"
] |
Extends classes.
|
[
"Extends",
"classes",
"."
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L10667-L10749
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function() {
for (var cid in madeMap) {
if (madeMap[cid].added) {
delete madeMap[cid].obj._cid;
}
}
madeMap = null;
}
|
javascript
|
function() {
for (var cid in madeMap) {
if (madeMap[cid].added) {
delete madeMap[cid].obj._cid;
}
}
madeMap = null;
}
|
[
"function",
"(",
")",
"{",
"for",
"(",
"var",
"cid",
"in",
"madeMap",
")",
"{",
"if",
"(",
"madeMap",
"[",
"cid",
"]",
".",
"added",
")",
"{",
"delete",
"madeMap",
"[",
"cid",
"]",
".",
"obj",
".",
"_cid",
";",
"}",
"}",
"madeMap",
"=",
"null",
";",
"}"
] |
Clears out map of converted objects.
|
[
"Clears",
"out",
"map",
"of",
"converted",
"objects",
"."
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L11306-L11313
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function() {
var computes = this.constructor._computes;
this._computedBindings = {};
for (var i = 0, len = computes.length, prop; i < len; i++) {
prop = computes[i];
// Make the context of the compute the current Map
this[prop] = this[prop].clone(this);
// Keep track of computed properties
this._computedBindings[prop] = {
count: 0
};
}
}
|
javascript
|
function() {
var computes = this.constructor._computes;
this._computedBindings = {};
for (var i = 0, len = computes.length, prop; i < len; i++) {
prop = computes[i];
// Make the context of the compute the current Map
this[prop] = this[prop].clone(this);
// Keep track of computed properties
this._computedBindings[prop] = {
count: 0
};
}
}
|
[
"function",
"(",
")",
"{",
"var",
"computes",
"=",
"this",
".",
"constructor",
".",
"_computes",
";",
"this",
".",
"_computedBindings",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"computes",
".",
"length",
",",
"prop",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"prop",
"=",
"computes",
"[",
"i",
"]",
";",
"this",
"[",
"prop",
"]",
"=",
"this",
"[",
"prop",
"]",
".",
"clone",
"(",
"this",
")",
";",
"this",
".",
"_computedBindings",
"[",
"prop",
"]",
"=",
"{",
"count",
":",
"0",
"}",
";",
"}",
"}"
] |
Sets up computed properties on a Map.
|
[
"Sets",
"up",
"computed",
"properties",
"on",
"a",
"Map",
"."
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L11517-L11530
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(ev, attr, how, newVal, oldVal) {
// when a change happens, create the named event.
can.batch.trigger(this, {
type: attr,
batchNum: ev.batchNum
}, [newVal, oldVal]);
if (how === "remove" || how === "add") {
can.batch.trigger(this, {
type: "__keys",
batchNum: ev.batchNum
});
}
}
|
javascript
|
function(ev, attr, how, newVal, oldVal) {
// when a change happens, create the named event.
can.batch.trigger(this, {
type: attr,
batchNum: ev.batchNum
}, [newVal, oldVal]);
if (how === "remove" || how === "add") {
can.batch.trigger(this, {
type: "__keys",
batchNum: ev.batchNum
});
}
}
|
[
"function",
"(",
"ev",
",",
"attr",
",",
"how",
",",
"newVal",
",",
"oldVal",
")",
"{",
"can",
".",
"batch",
".",
"trigger",
"(",
"this",
",",
"{",
"type",
":",
"attr",
",",
"batchNum",
":",
"ev",
".",
"batchNum",
"}",
",",
"[",
"newVal",
",",
"oldVal",
"]",
")",
";",
"if",
"(",
"how",
"===",
"\"remove\"",
"||",
"how",
"===",
"\"add\"",
")",
"{",
"can",
".",
"batch",
".",
"trigger",
"(",
"this",
",",
"{",
"type",
":",
"\"__keys\"",
",",
"batchNum",
":",
"ev",
".",
"batchNum",
"}",
")",
";",
"}",
"}"
] |
`change`event handler.
|
[
"change",
"event",
"handler",
"."
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L11539-L11552
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(attr, how, newVal, oldVal) {
can.batch.trigger(this, "change", can.makeArray(arguments));
}
|
javascript
|
function(attr, how, newVal, oldVal) {
can.batch.trigger(this, "change", can.makeArray(arguments));
}
|
[
"function",
"(",
"attr",
",",
"how",
",",
"newVal",
",",
"oldVal",
")",
"{",
"can",
".",
"batch",
".",
"trigger",
"(",
"this",
",",
"\"change\"",
",",
"can",
".",
"makeArray",
"(",
"arguments",
")",
")",
";",
"}"
] |
Trigger a change event.
|
[
"Trigger",
"a",
"change",
"event",
"."
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L11554-L11556
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(callback) {
var data = this.__get();
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
callback(data[prop], prop);
}
}
}
|
javascript
|
function(callback) {
var data = this.__get();
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
callback(data[prop], prop);
}
}
}
|
[
"function",
"(",
"callback",
")",
"{",
"var",
"data",
"=",
"this",
".",
"__get",
"(",
")",
";",
"for",
"(",
"var",
"prop",
"in",
"data",
")",
"{",
"if",
"(",
"data",
".",
"hasOwnProperty",
"(",
"prop",
")",
")",
"{",
"callback",
"(",
"data",
"[",
"prop",
"]",
",",
"prop",
")",
";",
"}",
"}",
"}"
] |
Iterator that does not trigger live binding.
|
[
"Iterator",
"that",
"does",
"not",
"trigger",
"live",
"binding",
"."
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L11558-L11565
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(prop, current) {
if (prop in this._data) {
// Delete the property from `_data` and the Map
// as long as it isn't part of the Map's prototype.
delete this._data[prop];
if (!(prop in this.constructor.prototype)) {
delete this[prop];
}
// Let others now this property has been removed.
this._triggerChange(prop, "remove", undefined, current);
}
}
|
javascript
|
function(prop, current) {
if (prop in this._data) {
// Delete the property from `_data` and the Map
// as long as it isn't part of the Map's prototype.
delete this._data[prop];
if (!(prop in this.constructor.prototype)) {
delete this[prop];
}
// Let others now this property has been removed.
this._triggerChange(prop, "remove", undefined, current);
}
}
|
[
"function",
"(",
"prop",
",",
"current",
")",
"{",
"if",
"(",
"prop",
"in",
"this",
".",
"_data",
")",
"{",
"delete",
"this",
".",
"_data",
"[",
"prop",
"]",
";",
"if",
"(",
"!",
"(",
"prop",
"in",
"this",
".",
"constructor",
".",
"prototype",
")",
")",
"{",
"delete",
"this",
"[",
"prop",
"]",
";",
"}",
"this",
".",
"_triggerChange",
"(",
"prop",
",",
"\"remove\"",
",",
"undefined",
",",
"current",
")",
";",
"}",
"}"
] |
Remove a property.
|
[
"Remove",
"a",
"property",
"."
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L11614-L11626
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(value, prop) {
// If we are getting an object.
if (!(value instanceof can.Map) && can.Map.helpers.canMakeObserve(value)) {
var cached = getMapFromObject(value);
if (cached) {
return cached;
}
if (can.isArray(value)) {
var List = can.List;
return new List(value);
} else {
var Map = this.constructor.Map || can.Map;
return new Map(value);
}
}
return value;
}
|
javascript
|
function(value, prop) {
// If we are getting an object.
if (!(value instanceof can.Map) && can.Map.helpers.canMakeObserve(value)) {
var cached = getMapFromObject(value);
if (cached) {
return cached;
}
if (can.isArray(value)) {
var List = can.List;
return new List(value);
} else {
var Map = this.constructor.Map || can.Map;
return new Map(value);
}
}
return value;
}
|
[
"function",
"(",
"value",
",",
"prop",
")",
"{",
"if",
"(",
"!",
"(",
"value",
"instanceof",
"can",
".",
"Map",
")",
"&&",
"can",
".",
"Map",
".",
"helpers",
".",
"canMakeObserve",
"(",
"value",
")",
")",
"{",
"var",
"cached",
"=",
"getMapFromObject",
"(",
"value",
")",
";",
"if",
"(",
"cached",
")",
"{",
"return",
"cached",
";",
"}",
"if",
"(",
"can",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"var",
"List",
"=",
"can",
".",
"List",
";",
"return",
"new",
"List",
"(",
"value",
")",
";",
"}",
"else",
"{",
"var",
"Map",
"=",
"this",
".",
"constructor",
".",
"Map",
"||",
"can",
".",
"Map",
";",
"return",
"new",
"Map",
"(",
"value",
")",
";",
"}",
"}",
"return",
"value",
";",
"}"
] |
converts the value into an observable if needed
|
[
"converts",
"the",
"value",
"into",
"an",
"observable",
"if",
"needed"
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L11672-L11689
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(updater) {
for (var name in readInfo.observed) {
var ob = readInfo.observed[name];
ob.obj.unbind(ob.event, onchanged);
}
}
|
javascript
|
function(updater) {
for (var name in readInfo.observed) {
var ob = readInfo.observed[name];
ob.obj.unbind(ob.event, onchanged);
}
}
|
[
"function",
"(",
"updater",
")",
"{",
"for",
"(",
"var",
"name",
"in",
"readInfo",
".",
"observed",
")",
"{",
"var",
"ob",
"=",
"readInfo",
".",
"observed",
"[",
"name",
"]",
";",
"ob",
".",
"obj",
".",
"unbind",
"(",
"ob",
".",
"event",
",",
"onchanged",
")",
";",
"}",
"}"
] |
Remove handler for the compute
|
[
"Remove",
"handler",
"for",
"the",
"compute"
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L12397-L12402
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(newValue, oldValue, batchNum) {
setCached(newValue);
updateOnChange(computed, newValue, oldValue, batchNum);
}
|
javascript
|
function(newValue, oldValue, batchNum) {
setCached(newValue);
updateOnChange(computed, newValue, oldValue, batchNum);
}
|
[
"function",
"(",
"newValue",
",",
"oldValue",
",",
"batchNum",
")",
"{",
"setCached",
"(",
"newValue",
")",
";",
"updateOnChange",
"(",
"computed",
",",
"newValue",
",",
"oldValue",
",",
"batchNum",
")",
";",
"}"
] |
The computed object
|
[
"The",
"computed",
"object"
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L12449-L12452
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function() {
for (var i = 0, len = computes.length; i < len; i++) {
computes[i].unbind('change', k);
}
computes = null;
}
|
javascript
|
function() {
for (var i = 0, len = computes.length; i < len; i++) {
computes[i].unbind('change', k);
}
computes = null;
}
|
[
"function",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"computes",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"computes",
"[",
"i",
"]",
".",
"unbind",
"(",
"'change'",
",",
"k",
")",
";",
"}",
"computes",
"=",
"null",
";",
"}"
] |
A list of temporarily bound computes
|
[
"A",
"list",
"of",
"temporarily",
"bound",
"computes"
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L12677-L12682
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(parentValue, nameIndex) {
if (nameIndex > defaultPropertyDepth) {
defaultObserve = currentObserve;
defaultReads = currentReads;
defaultPropertyDepth = nameIndex;
defaultScope = scope;
defaultComputeReadings = can.__clearReading();
}
}
|
javascript
|
function(parentValue, nameIndex) {
if (nameIndex > defaultPropertyDepth) {
defaultObserve = currentObserve;
defaultReads = currentReads;
defaultPropertyDepth = nameIndex;
defaultScope = scope;
defaultComputeReadings = can.__clearReading();
}
}
|
[
"function",
"(",
"parentValue",
",",
"nameIndex",
")",
"{",
"if",
"(",
"nameIndex",
">",
"defaultPropertyDepth",
")",
"{",
"defaultObserve",
"=",
"currentObserve",
";",
"defaultReads",
"=",
"currentReads",
";",
"defaultPropertyDepth",
"=",
"nameIndex",
";",
"defaultScope",
"=",
"scope",
";",
"defaultComputeReadings",
"=",
"can",
".",
"__clearReading",
"(",
")",
";",
"}",
"}"
] |
Called when we were unable to find a value.
|
[
"Called",
"when",
"we",
"were",
"unable",
"to",
"find",
"a",
"value",
"."
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L13034-L13044
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function() {
if (!tornDown) {
tornDown = true;
unbind(data);
can.unbind.call(el, 'removed', teardown);
}
return true;
}
|
javascript
|
function() {
if (!tornDown) {
tornDown = true;
unbind(data);
can.unbind.call(el, 'removed', teardown);
}
return true;
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"!",
"tornDown",
")",
"{",
"tornDown",
"=",
"true",
";",
"unbind",
"(",
"data",
")",
";",
"can",
".",
"unbind",
".",
"call",
"(",
"el",
",",
"'removed'",
",",
"teardown",
")",
";",
"}",
"return",
"true",
";",
"}"
] |
Removing an element can call teardown which unregister the nodeList which calls teardown
|
[
"Removing",
"an",
"element",
"can",
"call",
"teardown",
"which",
"unregister",
"the",
"nodeList",
"which",
"calls",
"teardown"
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L14373-L14380
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(expr, options) {
var value;
// if it's a function, wrap its value in a compute
// that will only change values from true to false
if (can.isFunction(expr)) {
value = can.compute.truthy(expr)();
} else {
value = !! Mustache.resolve(expr);
}
if (value) {
return options.fn(options.contexts || this);
} else {
return options.inverse(options.contexts || this);
}
}
|
javascript
|
function(expr, options) {
var value;
// if it's a function, wrap its value in a compute
// that will only change values from true to false
if (can.isFunction(expr)) {
value = can.compute.truthy(expr)();
} else {
value = !! Mustache.resolve(expr);
}
if (value) {
return options.fn(options.contexts || this);
} else {
return options.inverse(options.contexts || this);
}
}
|
[
"function",
"(",
"expr",
",",
"options",
")",
"{",
"var",
"value",
";",
"if",
"(",
"can",
".",
"isFunction",
"(",
"expr",
")",
")",
"{",
"value",
"=",
"can",
".",
"compute",
".",
"truthy",
"(",
"expr",
")",
"(",
")",
";",
"}",
"else",
"{",
"value",
"=",
"!",
"!",
"Mustache",
".",
"resolve",
"(",
"expr",
")",
";",
"}",
"if",
"(",
"value",
")",
"{",
"return",
"options",
".",
"fn",
"(",
"options",
".",
"contexts",
"||",
"this",
")",
";",
"}",
"else",
"{",
"return",
"options",
".",
"inverse",
"(",
"options",
".",
"contexts",
"||",
"this",
")",
";",
"}",
"}"
] |
Implements the `if` built-in helper.
|
[
"Implements",
"the",
"if",
"built",
"-",
"in",
"helper",
"."
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L15826-L15841
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(expr, options) {
var fn = options.fn;
options.fn = options.inverse;
options.inverse = fn;
return Mustache._helpers['if'].fn.apply(this, arguments);
}
|
javascript
|
function(expr, options) {
var fn = options.fn;
options.fn = options.inverse;
options.inverse = fn;
return Mustache._helpers['if'].fn.apply(this, arguments);
}
|
[
"function",
"(",
"expr",
",",
"options",
")",
"{",
"var",
"fn",
"=",
"options",
".",
"fn",
";",
"options",
".",
"fn",
"=",
"options",
".",
"inverse",
";",
"options",
".",
"inverse",
"=",
"fn",
";",
"return",
"Mustache",
".",
"_helpers",
"[",
"'if'",
"]",
".",
"fn",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}"
] |
Implements the `unless` built-in helper.
|
[
"Implements",
"the",
"unless",
"built",
"-",
"in",
"helper",
"."
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L15844-L15849
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(expr, options) {
// Check if this is a list or a compute that resolves to a list, and setup
// the incremental live-binding
// First, see what we are dealing with. It's ok to read the compute
// because can.view.text is only temporarily binding to what is going on here.
// Calling can.view.lists prevents anything from listening on that compute.
var resolved = Mustache.resolve(expr),
result = [],
keys,
key,
i;
// When resolved === undefined, the property hasn't been defined yet
// Assume it is intended to be a list
if (can.view.lists && (resolved instanceof can.List || (expr && expr.isComputed && resolved === undefined))) {
return can.view.lists(expr, function(item, index) {
return options.fn(options.scope.add({
"@index": index
})
.add(item));
});
}
expr = resolved;
if ( !! expr && isArrayLike(expr)) {
for (i = 0; i < expr.length; i++) {
result.push(options.fn(options.scope.add({
"@index": i
})
.add(expr[i])));
}
return result.join('');
} else if (isObserveLike(expr)) {
keys = can.Map.keys(expr);
// listen to keys changing so we can livebind lists of attributes.
for (i = 0; i < keys.length; i++) {
key = keys[i];
result.push(options.fn(options.scope.add({
"@key": key
})
.add(expr[key])));
}
return result.join('');
} else if (expr instanceof Object) {
for (key in expr) {
result.push(options.fn(options.scope.add({
"@key": key
})
.add(expr[key])));
}
return result.join('');
}
}
|
javascript
|
function(expr, options) {
// Check if this is a list or a compute that resolves to a list, and setup
// the incremental live-binding
// First, see what we are dealing with. It's ok to read the compute
// because can.view.text is only temporarily binding to what is going on here.
// Calling can.view.lists prevents anything from listening on that compute.
var resolved = Mustache.resolve(expr),
result = [],
keys,
key,
i;
// When resolved === undefined, the property hasn't been defined yet
// Assume it is intended to be a list
if (can.view.lists && (resolved instanceof can.List || (expr && expr.isComputed && resolved === undefined))) {
return can.view.lists(expr, function(item, index) {
return options.fn(options.scope.add({
"@index": index
})
.add(item));
});
}
expr = resolved;
if ( !! expr && isArrayLike(expr)) {
for (i = 0; i < expr.length; i++) {
result.push(options.fn(options.scope.add({
"@index": i
})
.add(expr[i])));
}
return result.join('');
} else if (isObserveLike(expr)) {
keys = can.Map.keys(expr);
// listen to keys changing so we can livebind lists of attributes.
for (i = 0; i < keys.length; i++) {
key = keys[i];
result.push(options.fn(options.scope.add({
"@key": key
})
.add(expr[key])));
}
return result.join('');
} else if (expr instanceof Object) {
for (key in expr) {
result.push(options.fn(options.scope.add({
"@key": key
})
.add(expr[key])));
}
return result.join('');
}
}
|
[
"function",
"(",
"expr",
",",
"options",
")",
"{",
"var",
"resolved",
"=",
"Mustache",
".",
"resolve",
"(",
"expr",
")",
",",
"result",
"=",
"[",
"]",
",",
"keys",
",",
"key",
",",
"i",
";",
"if",
"(",
"can",
".",
"view",
".",
"lists",
"&&",
"(",
"resolved",
"instanceof",
"can",
".",
"List",
"||",
"(",
"expr",
"&&",
"expr",
".",
"isComputed",
"&&",
"resolved",
"===",
"undefined",
")",
")",
")",
"{",
"return",
"can",
".",
"view",
".",
"lists",
"(",
"expr",
",",
"function",
"(",
"item",
",",
"index",
")",
"{",
"return",
"options",
".",
"fn",
"(",
"options",
".",
"scope",
".",
"add",
"(",
"{",
"\"@index\"",
":",
"index",
"}",
")",
".",
"add",
"(",
"item",
")",
")",
";",
"}",
")",
";",
"}",
"expr",
"=",
"resolved",
";",
"if",
"(",
"!",
"!",
"expr",
"&&",
"isArrayLike",
"(",
"expr",
")",
")",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"expr",
".",
"length",
";",
"i",
"++",
")",
"{",
"result",
".",
"push",
"(",
"options",
".",
"fn",
"(",
"options",
".",
"scope",
".",
"add",
"(",
"{",
"\"@index\"",
":",
"i",
"}",
")",
".",
"add",
"(",
"expr",
"[",
"i",
"]",
")",
")",
")",
";",
"}",
"return",
"result",
".",
"join",
"(",
"''",
")",
";",
"}",
"else",
"if",
"(",
"isObserveLike",
"(",
"expr",
")",
")",
"{",
"keys",
"=",
"can",
".",
"Map",
".",
"keys",
"(",
"expr",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"result",
".",
"push",
"(",
"options",
".",
"fn",
"(",
"options",
".",
"scope",
".",
"add",
"(",
"{",
"\"@key\"",
":",
"key",
"}",
")",
".",
"add",
"(",
"expr",
"[",
"key",
"]",
")",
")",
")",
";",
"}",
"return",
"result",
".",
"join",
"(",
"''",
")",
";",
"}",
"else",
"if",
"(",
"expr",
"instanceof",
"Object",
")",
"{",
"for",
"(",
"key",
"in",
"expr",
")",
"{",
"result",
".",
"push",
"(",
"options",
".",
"fn",
"(",
"options",
".",
"scope",
".",
"add",
"(",
"{",
"\"@key\"",
":",
"key",
"}",
")",
".",
"add",
"(",
"expr",
"[",
"key",
"]",
")",
")",
")",
";",
"}",
"return",
"result",
".",
"join",
"(",
"''",
")",
";",
"}",
"}"
] |
Implements the `each` built-in helper.
|
[
"Implements",
"the",
"each",
"built",
"-",
"in",
"helper",
"."
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L15853-L15908
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(expr, options) {
var ctx = expr;
expr = Mustache.resolve(expr);
if ( !! expr) {
return options.fn(ctx);
}
}
|
javascript
|
function(expr, options) {
var ctx = expr;
expr = Mustache.resolve(expr);
if ( !! expr) {
return options.fn(ctx);
}
}
|
[
"function",
"(",
"expr",
",",
"options",
")",
"{",
"var",
"ctx",
"=",
"expr",
";",
"expr",
"=",
"Mustache",
".",
"resolve",
"(",
"expr",
")",
";",
"if",
"(",
"!",
"!",
"expr",
")",
"{",
"return",
"options",
".",
"fn",
"(",
"ctx",
")",
";",
"}",
"}"
] |
Implements the `with` built-in helper.
|
[
"Implements",
"the",
"with",
"built",
"-",
"in",
"helper",
"."
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L15911-L15917
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(id, src) {
return "can.Mustache(function(" + ARG_NAMES + ") { " + new Mustache({
text: src,
name: id
})
.template.out + " })";
}
|
javascript
|
function(id, src) {
return "can.Mustache(function(" + ARG_NAMES + ") { " + new Mustache({
text: src,
name: id
})
.template.out + " })";
}
|
[
"function",
"(",
"id",
",",
"src",
")",
"{",
"return",
"\"can.Mustache(function(\"",
"+",
"ARG_NAMES",
"+",
"\") { \"",
"+",
"new",
"Mustache",
"(",
"{",
"text",
":",
"src",
",",
"name",
":",
"id",
"}",
")",
".",
"template",
".",
"out",
"+",
"\" })\"",
";",
"}"
] |
Returns a `function` that renders the view.
|
[
"Returns",
"a",
"function",
"that",
"renders",
"the",
"view",
"."
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L15941-L15947
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(value) {
if (value[0] === "{" && value[value.length - 1] === "}") {
return value.substr(1, value.length - 2);
}
return value;
}
|
javascript
|
function(value) {
if (value[0] === "{" && value[value.length - 1] === "}") {
return value.substr(1, value.length - 2);
}
return value;
}
|
[
"function",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"[",
"0",
"]",
"===",
"\"{\"",
"&&",
"value",
"[",
"value",
".",
"length",
"-",
"1",
"]",
"===",
"\"}\"",
")",
"{",
"return",
"value",
".",
"substr",
"(",
"1",
",",
"value",
".",
"length",
"-",
"2",
")",
";",
"}",
"return",
"value",
";",
"}"
] |
Function for determining of an element is contenteditable
|
[
"Function",
"for",
"determining",
"of",
"an",
"element",
"is",
"contenteditable"
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L15996-L16001
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(ev) {
// The attribute value, representing the name of the method to call (i.e. can-submit="foo" foo is the
// name of the method)
var attr = removeCurly(el.getAttribute(attributeName)),
scopeData = data.scope.read(attr, {
returnObserveMethods: true,
isArgument: true
});
return scopeData.value.call(scopeData.parent, data.scope._context, can.$(this), ev);
}
|
javascript
|
function(ev) {
// The attribute value, representing the name of the method to call (i.e. can-submit="foo" foo is the
// name of the method)
var attr = removeCurly(el.getAttribute(attributeName)),
scopeData = data.scope.read(attr, {
returnObserveMethods: true,
isArgument: true
});
return scopeData.value.call(scopeData.parent, data.scope._context, can.$(this), ev);
}
|
[
"function",
"(",
"ev",
")",
"{",
"var",
"attr",
"=",
"removeCurly",
"(",
"el",
".",
"getAttribute",
"(",
"attributeName",
")",
")",
",",
"scopeData",
"=",
"data",
".",
"scope",
".",
"read",
"(",
"attr",
",",
"{",
"returnObserveMethods",
":",
"true",
",",
"isArgument",
":",
"true",
"}",
")",
";",
"return",
"scopeData",
".",
"value",
".",
"call",
"(",
"scopeData",
".",
"parent",
",",
"data",
".",
"scope",
".",
"_context",
",",
"can",
".",
"$",
"(",
"this",
")",
",",
"ev",
")",
";",
"}"
] |
the attribute name is the function to call
|
[
"the",
"attribute",
"name",
"is",
"the",
"function",
"to",
"call"
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L16116-L16125
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function() {
// Get an array of the currently selected values
var value = this.get(),
currentValue = this.options.value();
// If the compute is a string, set its value to the joined version of the values array (i.e. "foo;bar")
if (this.isString || typeof currentValue === "string") {
this.isString = true;
this.options.value(value.join(this.delimiter));
}
// If the compute is a can.List, replace its current contents with the new array of values
else if (currentValue instanceof can.List) {
currentValue.attr(value, true);
}
// Otherwise set the value to the array of values selected in the input.
else {
this.options.value(value);
}
}
|
javascript
|
function() {
// Get an array of the currently selected values
var value = this.get(),
currentValue = this.options.value();
// If the compute is a string, set its value to the joined version of the values array (i.e. "foo;bar")
if (this.isString || typeof currentValue === "string") {
this.isString = true;
this.options.value(value.join(this.delimiter));
}
// If the compute is a can.List, replace its current contents with the new array of values
else if (currentValue instanceof can.List) {
currentValue.attr(value, true);
}
// Otherwise set the value to the array of values selected in the input.
else {
this.options.value(value);
}
}
|
[
"function",
"(",
")",
"{",
"var",
"value",
"=",
"this",
".",
"get",
"(",
")",
",",
"currentValue",
"=",
"this",
".",
"options",
".",
"value",
"(",
")",
";",
"if",
"(",
"this",
".",
"isString",
"||",
"typeof",
"currentValue",
"===",
"\"string\"",
")",
"{",
"this",
".",
"isString",
"=",
"true",
";",
"this",
".",
"options",
".",
"value",
"(",
"value",
".",
"join",
"(",
"this",
".",
"delimiter",
")",
")",
";",
"}",
"else",
"if",
"(",
"currentValue",
"instanceof",
"can",
".",
"List",
")",
"{",
"currentValue",
".",
"attr",
"(",
"value",
",",
"true",
")",
";",
"}",
"else",
"{",
"this",
".",
"options",
".",
"value",
"(",
"value",
")",
";",
"}",
"}"
] |
Called when the user changes this input in any way.
|
[
"Called",
"when",
"the",
"user",
"changes",
"this",
"input",
"in",
"any",
"way",
"."
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L16283-L16302
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(ev, newVal) {
scopePropertyUpdating = name;
componentScope.attr(name, newVal);
scopePropertyUpdating = null;
}
|
javascript
|
function(ev, newVal) {
scopePropertyUpdating = name;
componentScope.attr(name, newVal);
scopePropertyUpdating = null;
}
|
[
"function",
"(",
"ev",
",",
"newVal",
")",
"{",
"scopePropertyUpdating",
"=",
"name",
";",
"componentScope",
".",
"attr",
"(",
"name",
",",
"newVal",
")",
";",
"scopePropertyUpdating",
"=",
"null",
";",
"}"
] |
bind on this, check it's value, if it has dependencies
|
[
"bind",
"on",
"this",
"check",
"it",
"s",
"value",
"if",
"it",
"has",
"dependencies"
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L16447-L16451
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function(name) {
var parseName = "parse" + can.capitalize(name);
return function(data) {
// If there's a `parse...` function, use its output.
if (this[parseName]) {
data = this[parseName].apply(this, arguments);
}
// Run our maybe-parsed data through `model` or `models`.
return this[name](data);
};
}
|
javascript
|
function(name) {
var parseName = "parse" + can.capitalize(name);
return function(data) {
// If there's a `parse...` function, use its output.
if (this[parseName]) {
data = this[parseName].apply(this, arguments);
}
// Run our maybe-parsed data through `model` or `models`.
return this[name](data);
};
}
|
[
"function",
"(",
"name",
")",
"{",
"var",
"parseName",
"=",
"\"parse\"",
"+",
"can",
".",
"capitalize",
"(",
"name",
")",
";",
"return",
"function",
"(",
"data",
")",
"{",
"if",
"(",
"this",
"[",
"parseName",
"]",
")",
"{",
"data",
"=",
"this",
"[",
"parseName",
"]",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
"return",
"this",
"[",
"name",
"]",
"(",
"data",
")",
";",
"}",
";",
"}"
] |
Returns a function that knows how to prepare data from `findAll` or `findOne` calls. `name` should be either `model` or `models`.
|
[
"Returns",
"a",
"function",
"that",
"knows",
"how",
"to",
"prepare",
"data",
"from",
"findAll",
"or",
"findOne",
"calls",
".",
"name",
"should",
"be",
"either",
"model",
"or",
"models",
"."
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L17307-L17317
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function() {
if (!can.route.currentBinding) {
can.route._call("bind");
can.route.bind("change", onRouteDataChange);
can.route.currentBinding = can.route.defaultBinding;
}
}
|
javascript
|
function() {
if (!can.route.currentBinding) {
can.route._call("bind");
can.route.bind("change", onRouteDataChange);
can.route.currentBinding = can.route.defaultBinding;
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"!",
"can",
".",
"route",
".",
"currentBinding",
")",
"{",
"can",
".",
"route",
".",
"_call",
"(",
"\"bind\"",
")",
";",
"can",
".",
"route",
".",
"bind",
"(",
"\"change\"",
",",
"onRouteDataChange",
")",
";",
"can",
".",
"route",
".",
"currentBinding",
"=",
"can",
".",
"route",
".",
"defaultBinding",
";",
"}",
"}"
] |
we need to be able to easily kick off calling setState teardown whatever is there turn on a particular binding called when the route is ready
|
[
"we",
"need",
"to",
"be",
"able",
"to",
"easily",
"kick",
"off",
"calling",
"setState",
"teardown",
"whatever",
"is",
"there",
"turn",
"on",
"a",
"particular",
"binding",
"called",
"when",
"the",
"route",
"is",
"ready"
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L17833-L17839
|
train
|
|
canjs/can-compile
|
example/dist/production.js
|
function() {
var args = can.makeArray(arguments),
prop = args.shift(),
binding = can.route.bindings[can.route.currentBinding || can.route.defaultBinding],
method = binding[prop];
if (method.apply) {
return method.apply(binding, args);
} else {
return method;
}
}
|
javascript
|
function() {
var args = can.makeArray(arguments),
prop = args.shift(),
binding = can.route.bindings[can.route.currentBinding || can.route.defaultBinding],
method = binding[prop];
if (method.apply) {
return method.apply(binding, args);
} else {
return method;
}
}
|
[
"function",
"(",
")",
"{",
"var",
"args",
"=",
"can",
".",
"makeArray",
"(",
"arguments",
")",
",",
"prop",
"=",
"args",
".",
"shift",
"(",
")",
",",
"binding",
"=",
"can",
".",
"route",
".",
"bindings",
"[",
"can",
".",
"route",
".",
"currentBinding",
"||",
"can",
".",
"route",
".",
"defaultBinding",
"]",
",",
"method",
"=",
"binding",
"[",
"prop",
"]",
";",
"if",
"(",
"method",
".",
"apply",
")",
"{",
"return",
"method",
".",
"apply",
"(",
"binding",
",",
"args",
")",
";",
"}",
"else",
"{",
"return",
"method",
";",
"}",
"}"
] |
a helper to get stuff from the current or default bindings
|
[
"a",
"helper",
"to",
"get",
"stuff",
"from",
"the",
"current",
"or",
"default",
"bindings"
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/example/dist/production.js#L17850-L17860
|
train
|
|
component/toidentifier
|
index.js
|
toIdentifier
|
function toIdentifier (str) {
return str
.split(' ')
.map(function (token) {
return token.slice(0, 1).toUpperCase() + token.slice(1)
})
.join('')
.replace(/[^ _0-9a-z]/gi, '')
}
|
javascript
|
function toIdentifier (str) {
return str
.split(' ')
.map(function (token) {
return token.slice(0, 1).toUpperCase() + token.slice(1)
})
.join('')
.replace(/[^ _0-9a-z]/gi, '')
}
|
[
"function",
"toIdentifier",
"(",
"str",
")",
"{",
"return",
"str",
".",
"split",
"(",
"' '",
")",
".",
"map",
"(",
"function",
"(",
"token",
")",
"{",
"return",
"token",
".",
"slice",
"(",
"0",
",",
"1",
")",
".",
"toUpperCase",
"(",
")",
"+",
"token",
".",
"slice",
"(",
"1",
")",
"}",
")",
".",
"join",
"(",
"''",
")",
".",
"replace",
"(",
"/",
"[^ _0-9a-z]",
"/",
"gi",
",",
"''",
")",
"}"
] |
Trasform the given string into a JavaScript identifier
@param {string} str
@returns {string}
@public
|
[
"Trasform",
"the",
"given",
"string",
"into",
"a",
"JavaScript",
"identifier"
] |
8c09cba5e530de7d74b087ea66740c0e4a5af02b
|
https://github.com/component/toidentifier/blob/8c09cba5e530de7d74b087ea66740c0e4a5af02b/index.js#L22-L30
|
train
|
canjs/can-compile
|
gulp.js
|
runCompile
|
function runCompile(file, options) {
if (!file) {
throw new PluginError('can-compile', 'Missing file option for can-compile');
}
var templatePaths = [],
latestFile;
options = options || {};
function bufferStream (file, enc, cb) {
// ignore empty files
if (file.isNull()) {
cb();
return;
}
// can't do streams yet
if (file.isStream()) {
this.emit('error', new PluginError('can-compile', 'Streaming not supported for can-compile'));
cb();
return;
}
// set latest file if not already set,
// or if the current file was modified more recently.
if (!latestFile || file.stat && file.stat.mtime > latestFile.stat.mtime) {
latestFile = file;
}
templatePaths.push(file.path);
cb();
}
function endStream(cb) {
var self = this;
// no files passed in, no file goes out
if (!latestFile || !templatePaths.length) {
cb();
return;
}
compile(templatePaths, options, function (err, result) {
if (err) {
self.emit('error', new PluginError('can-compile', err));
return cb(err);
}
var joinedFile;
// if file opt was a file path
// clone everything from the latest file
if (typeof file === 'string') {
joinedFile = latestFile.clone({ contents: false });
joinedFile.path = path.join(latestFile.base, file);
} else {
joinedFile = new File(file);
}
joinedFile.contents = new Buffer(result);
self.push(joinedFile);
cb();
});
}
return through.obj(bufferStream, endStream);
}
|
javascript
|
function runCompile(file, options) {
if (!file) {
throw new PluginError('can-compile', 'Missing file option for can-compile');
}
var templatePaths = [],
latestFile;
options = options || {};
function bufferStream (file, enc, cb) {
// ignore empty files
if (file.isNull()) {
cb();
return;
}
// can't do streams yet
if (file.isStream()) {
this.emit('error', new PluginError('can-compile', 'Streaming not supported for can-compile'));
cb();
return;
}
// set latest file if not already set,
// or if the current file was modified more recently.
if (!latestFile || file.stat && file.stat.mtime > latestFile.stat.mtime) {
latestFile = file;
}
templatePaths.push(file.path);
cb();
}
function endStream(cb) {
var self = this;
// no files passed in, no file goes out
if (!latestFile || !templatePaths.length) {
cb();
return;
}
compile(templatePaths, options, function (err, result) {
if (err) {
self.emit('error', new PluginError('can-compile', err));
return cb(err);
}
var joinedFile;
// if file opt was a file path
// clone everything from the latest file
if (typeof file === 'string') {
joinedFile = latestFile.clone({ contents: false });
joinedFile.path = path.join(latestFile.base, file);
} else {
joinedFile = new File(file);
}
joinedFile.contents = new Buffer(result);
self.push(joinedFile);
cb();
});
}
return through.obj(bufferStream, endStream);
}
|
[
"function",
"runCompile",
"(",
"file",
",",
"options",
")",
"{",
"if",
"(",
"!",
"file",
")",
"{",
"throw",
"new",
"PluginError",
"(",
"'can-compile'",
",",
"'Missing file option for can-compile'",
")",
";",
"}",
"var",
"templatePaths",
"=",
"[",
"]",
",",
"latestFile",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"function",
"bufferStream",
"(",
"file",
",",
"enc",
",",
"cb",
")",
"{",
"if",
"(",
"file",
".",
"isNull",
"(",
")",
")",
"{",
"cb",
"(",
")",
";",
"return",
";",
"}",
"if",
"(",
"file",
".",
"isStream",
"(",
")",
")",
"{",
"this",
".",
"emit",
"(",
"'error'",
",",
"new",
"PluginError",
"(",
"'can-compile'",
",",
"'Streaming not supported for can-compile'",
")",
")",
";",
"cb",
"(",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"latestFile",
"||",
"file",
".",
"stat",
"&&",
"file",
".",
"stat",
".",
"mtime",
">",
"latestFile",
".",
"stat",
".",
"mtime",
")",
"{",
"latestFile",
"=",
"file",
";",
"}",
"templatePaths",
".",
"push",
"(",
"file",
".",
"path",
")",
";",
"cb",
"(",
")",
";",
"}",
"function",
"endStream",
"(",
"cb",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"!",
"latestFile",
"||",
"!",
"templatePaths",
".",
"length",
")",
"{",
"cb",
"(",
")",
";",
"return",
";",
"}",
"compile",
"(",
"templatePaths",
",",
"options",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"{",
"self",
".",
"emit",
"(",
"'error'",
",",
"new",
"PluginError",
"(",
"'can-compile'",
",",
"err",
")",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"var",
"joinedFile",
";",
"if",
"(",
"typeof",
"file",
"===",
"'string'",
")",
"{",
"joinedFile",
"=",
"latestFile",
".",
"clone",
"(",
"{",
"contents",
":",
"false",
"}",
")",
";",
"joinedFile",
".",
"path",
"=",
"path",
".",
"join",
"(",
"latestFile",
".",
"base",
",",
"file",
")",
";",
"}",
"else",
"{",
"joinedFile",
"=",
"new",
"File",
"(",
"file",
")",
";",
"}",
"joinedFile",
".",
"contents",
"=",
"new",
"Buffer",
"(",
"result",
")",
";",
"self",
".",
"push",
"(",
"joinedFile",
")",
";",
"cb",
"(",
")",
";",
"}",
")",
";",
"}",
"return",
"through",
".",
"obj",
"(",
"bufferStream",
",",
"endStream",
")",
";",
"}"
] |
file can be a vinyl file object or a string when a string it will construct a new one
|
[
"file",
"can",
"be",
"a",
"vinyl",
"file",
"object",
"or",
"a",
"string",
"when",
"a",
"string",
"it",
"will",
"construct",
"a",
"new",
"one"
] |
56c05e2b5f5dc441fa5ce00a499386ef1e992a2a
|
https://github.com/canjs/can-compile/blob/56c05e2b5f5dc441fa5ce00a499386ef1e992a2a/gulp.js#L12-L81
|
train
|
GluuFederation/oxd-node
|
oxd-node/utility.js
|
oxdSocketRequest
|
function oxdSocketRequest(port, host, params, command, callback) {
// OXD data
let data = {
command,
params
};
// Create socket object
const client = new net.Socket();
// Initiate a connection on a given socket.
client.connect(port, host, () => {
data = JSON.stringify(data);
console.log('Connected');
try {
if (data.length > 0 && data.length <= 100) {
console.log(`Send data : 00${data.length + data}`);
client.write(`00${data.length + data}`);
} else if (data.length > 100 && data.length < 1000) {
console.log(`Send data : 0${data.length + data}`);
client.write(`0${data.length + data}`);
}
} catch (err) {
console.log('Send data error:', err);
}
});
// Emitted when data is received
client.on('data', (req) => {
data = req.toString();
console.log('Response : ', data);
callback(null, JSON.parse(data.substring(4, data.length)));
client.end(); // kill client after server's response
});
// Emitted when an error occurs. The 'close' event will be called directly following this event.
client.on('error', (err) => {
console.log('Error: ', err);
callback(err, null);
client.end(); // kill client after server's response
});
// Emitted when the server closes.
client.on('close', () => {
console.log('Connection closed');
});
}
|
javascript
|
function oxdSocketRequest(port, host, params, command, callback) {
// OXD data
let data = {
command,
params
};
// Create socket object
const client = new net.Socket();
// Initiate a connection on a given socket.
client.connect(port, host, () => {
data = JSON.stringify(data);
console.log('Connected');
try {
if (data.length > 0 && data.length <= 100) {
console.log(`Send data : 00${data.length + data}`);
client.write(`00${data.length + data}`);
} else if (data.length > 100 && data.length < 1000) {
console.log(`Send data : 0${data.length + data}`);
client.write(`0${data.length + data}`);
}
} catch (err) {
console.log('Send data error:', err);
}
});
// Emitted when data is received
client.on('data', (req) => {
data = req.toString();
console.log('Response : ', data);
callback(null, JSON.parse(data.substring(4, data.length)));
client.end(); // kill client after server's response
});
// Emitted when an error occurs. The 'close' event will be called directly following this event.
client.on('error', (err) => {
console.log('Error: ', err);
callback(err, null);
client.end(); // kill client after server's response
});
// Emitted when the server closes.
client.on('close', () => {
console.log('Connection closed');
});
}
|
[
"function",
"oxdSocketRequest",
"(",
"port",
",",
"host",
",",
"params",
",",
"command",
",",
"callback",
")",
"{",
"let",
"data",
"=",
"{",
"command",
",",
"params",
"}",
";",
"const",
"client",
"=",
"new",
"net",
".",
"Socket",
"(",
")",
";",
"client",
".",
"connect",
"(",
"port",
",",
"host",
",",
"(",
")",
"=>",
"{",
"data",
"=",
"JSON",
".",
"stringify",
"(",
"data",
")",
";",
"console",
".",
"log",
"(",
"'Connected'",
")",
";",
"try",
"{",
"if",
"(",
"data",
".",
"length",
">",
"0",
"&&",
"data",
".",
"length",
"<=",
"100",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"data",
".",
"length",
"+",
"data",
"}",
"`",
")",
";",
"client",
".",
"write",
"(",
"`",
"${",
"data",
".",
"length",
"+",
"data",
"}",
"`",
")",
";",
"}",
"else",
"if",
"(",
"data",
".",
"length",
">",
"100",
"&&",
"data",
".",
"length",
"<",
"1000",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"data",
".",
"length",
"+",
"data",
"}",
"`",
")",
";",
"client",
".",
"write",
"(",
"`",
"${",
"data",
".",
"length",
"+",
"data",
"}",
"`",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"'Send data error:'",
",",
"err",
")",
";",
"}",
"}",
")",
";",
"client",
".",
"on",
"(",
"'data'",
",",
"(",
"req",
")",
"=>",
"{",
"data",
"=",
"req",
".",
"toString",
"(",
")",
";",
"console",
".",
"log",
"(",
"'Response : '",
",",
"data",
")",
";",
"callback",
"(",
"null",
",",
"JSON",
".",
"parse",
"(",
"data",
".",
"substring",
"(",
"4",
",",
"data",
".",
"length",
")",
")",
")",
";",
"client",
".",
"end",
"(",
")",
";",
"}",
")",
";",
"client",
".",
"on",
"(",
"'error'",
",",
"(",
"err",
")",
"=>",
"{",
"console",
".",
"log",
"(",
"'Error: '",
",",
"err",
")",
";",
"callback",
"(",
"err",
",",
"null",
")",
";",
"client",
".",
"end",
"(",
")",
";",
"}",
")",
";",
"client",
".",
"on",
"(",
"'close'",
",",
"(",
")",
"=>",
"{",
"console",
".",
"log",
"(",
"'Connection closed'",
")",
";",
"}",
")",
";",
"}"
] |
Function for oxd-server socket manipulation
@param {int} port - OXD port number for oxd-server
@param {int} host - URL of the oxd-server
@param {object} params - List of parameters to request oxd-server command
@param {string} command - OXD Command name
@param {function} callback - Callback response function
|
[
"Function",
"for",
"oxd",
"-",
"server",
"socket",
"manipulation"
] |
b8d794fcb65bfc7c33364695b8875ef5fa555a06
|
https://github.com/GluuFederation/oxd-node/blob/b8d794fcb65bfc7c33364695b8875ef5fa555a06/oxd-node/utility.js#L12-L58
|
train
|
ujjwalguptaofficial/sqlweb
|
examples/simple example/scripts/index.js
|
showTableData
|
function showTableData() {
connection.runSql('select * from Student').then(function (students) {
var HtmlString = "";
students.forEach(function (student) {
HtmlString += "<tr ItemId=" + student.Id + "><td>" +
student.Name + "</td><td>" +
student.Gender + "</td><td>" +
student.Country + "</td><td>" +
student.City + "</td><td>" +
"<a href='#' class='edit'>Edit</a></td>" +
"<td><a href='#' class='delete''>Delete</a></td>";
})
$('#tblGrid tbody').html(HtmlString);
}).catch(function (error) {
console.log(error);
});
}
|
javascript
|
function showTableData() {
connection.runSql('select * from Student').then(function (students) {
var HtmlString = "";
students.forEach(function (student) {
HtmlString += "<tr ItemId=" + student.Id + "><td>" +
student.Name + "</td><td>" +
student.Gender + "</td><td>" +
student.Country + "</td><td>" +
student.City + "</td><td>" +
"<a href='#' class='edit'>Edit</a></td>" +
"<td><a href='#' class='delete''>Delete</a></td>";
})
$('#tblGrid tbody').html(HtmlString);
}).catch(function (error) {
console.log(error);
});
}
|
[
"function",
"showTableData",
"(",
")",
"{",
"connection",
".",
"runSql",
"(",
"'select * from Student'",
")",
".",
"then",
"(",
"function",
"(",
"students",
")",
"{",
"var",
"HtmlString",
"=",
"\"\"",
";",
"students",
".",
"forEach",
"(",
"function",
"(",
"student",
")",
"{",
"HtmlString",
"+=",
"\"<tr ItemId=\"",
"+",
"student",
".",
"Id",
"+",
"\"><td>\"",
"+",
"student",
".",
"Name",
"+",
"\"</td><td>\"",
"+",
"student",
".",
"Gender",
"+",
"\"</td><td>\"",
"+",
"student",
".",
"Country",
"+",
"\"</td><td>\"",
"+",
"student",
".",
"City",
"+",
"\"</td><td>\"",
"+",
"\"<a href='#' class='edit'>Edit</a></td>\"",
"+",
"\"<td><a href='#' class='delete''>Delete</a></td>\"",
";",
"}",
")",
"$",
"(",
"'#tblGrid tbody'",
")",
".",
"html",
"(",
"HtmlString",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"error",
")",
"{",
"console",
".",
"log",
"(",
"error",
")",
";",
"}",
")",
";",
"}"
] |
This function refreshes the table
|
[
"This",
"function",
"refreshes",
"the",
"table"
] |
51fa7dbb53076ef2b0eff87c4bcedafcc0ec3f29
|
https://github.com/ujjwalguptaofficial/sqlweb/blob/51fa7dbb53076ef2b0eff87c4bcedafcc0ec3f29/examples/simple example/scripts/index.js#L86-L102
|
train
|
TooTallNate/node-icy
|
lib/client.js
|
Client
|
function Client (options, cb) {
if (typeof options == 'string')
options = url.parse(options)
var req;
if (options.protocol == "https:")
req = https.request(options);
else
req = http.request(options);
// add the "Icy-MetaData" header
req.setHeader('Icy-MetaData', '1');
if ('function' == typeof cb) {
req.once('icyResponse', cb);
}
req.once('response', icyOnResponse);
req.once('socket', icyOnSocket);
return req;
}
|
javascript
|
function Client (options, cb) {
if (typeof options == 'string')
options = url.parse(options)
var req;
if (options.protocol == "https:")
req = https.request(options);
else
req = http.request(options);
// add the "Icy-MetaData" header
req.setHeader('Icy-MetaData', '1');
if ('function' == typeof cb) {
req.once('icyResponse', cb);
}
req.once('response', icyOnResponse);
req.once('socket', icyOnSocket);
return req;
}
|
[
"function",
"Client",
"(",
"options",
",",
"cb",
")",
"{",
"if",
"(",
"typeof",
"options",
"==",
"'string'",
")",
"options",
"=",
"url",
".",
"parse",
"(",
"options",
")",
"var",
"req",
";",
"if",
"(",
"options",
".",
"protocol",
"==",
"\"https:\"",
")",
"req",
"=",
"https",
".",
"request",
"(",
"options",
")",
";",
"else",
"req",
"=",
"http",
".",
"request",
"(",
"options",
")",
";",
"req",
".",
"setHeader",
"(",
"'Icy-MetaData'",
",",
"'1'",
")",
";",
"if",
"(",
"'function'",
"==",
"typeof",
"cb",
")",
"{",
"req",
".",
"once",
"(",
"'icyResponse'",
",",
"cb",
")",
";",
"}",
"req",
".",
"once",
"(",
"'response'",
",",
"icyOnResponse",
")",
";",
"req",
".",
"once",
"(",
"'socket'",
",",
"icyOnSocket",
")",
";",
"return",
"req",
";",
"}"
] |
The `Client` class is a subclass of the `http.ClientRequest` object.
It adds a stream preprocessor to make "ICY" responses work. This is only needed
because of the strictness of node's HTTP parser. I'll volley for ICY to be
supported (or at least configurable) in the http header for the JavaScript
HTTP rewrite (v0.12 of node?).
The other big difference is that it passes an `icy.Reader` instance
instead of a `http.ClientResponse` instance to the "response" event callback,
so that the "metadata" events are automatically parsed and the raw audio stream
it output without the ICY bytes.
Also see the [`request()`](#request) and [`get()`](#get) convenience functions.
@param {Object} options connection info and options object
@param {Function} cb optional callback function for the "response" event
@api public
|
[
"The",
"Client",
"class",
"is",
"a",
"subclass",
"of",
"the",
"http",
".",
"ClientRequest",
"object",
"."
] |
1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6
|
https://github.com/TooTallNate/node-icy/blob/1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6/lib/client.js#L39-L60
|
train
|
TooTallNate/node-icy
|
lib/client.js
|
icyOnResponse
|
function icyOnResponse (res) {
debug('request "response" event');
var s = res;
var metaint = res.headers['icy-metaint'];
if (metaint) {
debug('got metaint: %d', metaint);
s = new Reader(metaint);
res.pipe(s);
s.res = res;
Object.keys(res).forEach(function (k) {
if ('_' === k[0]) return;
debug('proxying %j', k);
proxy(s, k);
});
}
if (res.connection._wasIcy) {
s.httpVersion = 'ICY';
}
this.emit('icyResponse', s);
}
|
javascript
|
function icyOnResponse (res) {
debug('request "response" event');
var s = res;
var metaint = res.headers['icy-metaint'];
if (metaint) {
debug('got metaint: %d', metaint);
s = new Reader(metaint);
res.pipe(s);
s.res = res;
Object.keys(res).forEach(function (k) {
if ('_' === k[0]) return;
debug('proxying %j', k);
proxy(s, k);
});
}
if (res.connection._wasIcy) {
s.httpVersion = 'ICY';
}
this.emit('icyResponse', s);
}
|
[
"function",
"icyOnResponse",
"(",
"res",
")",
"{",
"debug",
"(",
"'request \"response\" event'",
")",
";",
"var",
"s",
"=",
"res",
";",
"var",
"metaint",
"=",
"res",
".",
"headers",
"[",
"'icy-metaint'",
"]",
";",
"if",
"(",
"metaint",
")",
"{",
"debug",
"(",
"'got metaint: %d'",
",",
"metaint",
")",
";",
"s",
"=",
"new",
"Reader",
"(",
"metaint",
")",
";",
"res",
".",
"pipe",
"(",
"s",
")",
";",
"s",
".",
"res",
"=",
"res",
";",
"Object",
".",
"keys",
"(",
"res",
")",
".",
"forEach",
"(",
"function",
"(",
"k",
")",
"{",
"if",
"(",
"'_'",
"===",
"k",
"[",
"0",
"]",
")",
"return",
";",
"debug",
"(",
"'proxying %j'",
",",
"k",
")",
";",
"proxy",
"(",
"s",
",",
"k",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"res",
".",
"connection",
".",
"_wasIcy",
")",
"{",
"s",
".",
"httpVersion",
"=",
"'ICY'",
";",
"}",
"this",
".",
"emit",
"(",
"'icyResponse'",
",",
"s",
")",
";",
"}"
] |
"response" event listener.
@api private
|
[
"response",
"event",
"listener",
"."
] |
1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6
|
https://github.com/TooTallNate/node-icy/blob/1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6/lib/client.js#L68-L90
|
train
|
TooTallNate/node-icy
|
lib/client.js
|
proxy
|
function proxy (stream, key) {
if (key in stream) {
debug('not proxying prop "%s" because it already exists on target stream', key);
return;
}
function get () {
return stream.res[key];
}
function set (v) {
return stream.res[key] = v;
}
Object.defineProperty(stream, key, {
configurable: true,
enumerable: true,
get: get,
set: set
});
}
|
javascript
|
function proxy (stream, key) {
if (key in stream) {
debug('not proxying prop "%s" because it already exists on target stream', key);
return;
}
function get () {
return stream.res[key];
}
function set (v) {
return stream.res[key] = v;
}
Object.defineProperty(stream, key, {
configurable: true,
enumerable: true,
get: get,
set: set
});
}
|
[
"function",
"proxy",
"(",
"stream",
",",
"key",
")",
"{",
"if",
"(",
"key",
"in",
"stream",
")",
"{",
"debug",
"(",
"'not proxying prop \"%s\" because it already exists on target stream'",
",",
"key",
")",
";",
"return",
";",
"}",
"function",
"get",
"(",
")",
"{",
"return",
"stream",
".",
"res",
"[",
"key",
"]",
";",
"}",
"function",
"set",
"(",
"v",
")",
"{",
"return",
"stream",
".",
"res",
"[",
"key",
"]",
"=",
"v",
";",
"}",
"Object",
".",
"defineProperty",
"(",
"stream",
",",
"key",
",",
"{",
"configurable",
":",
"true",
",",
"enumerable",
":",
"true",
",",
"get",
":",
"get",
",",
"set",
":",
"set",
"}",
")",
";",
"}"
] |
Proxies "key" from `stream` to `stream.res`.
@api private
|
[
"Proxies",
"key",
"from",
"stream",
"to",
"stream",
".",
"res",
"."
] |
1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6
|
https://github.com/TooTallNate/node-icy/blob/1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6/lib/client.js#L113-L131
|
train
|
TooTallNate/node-icy
|
lib/stringify.js
|
stringify
|
function stringify (obj) {
var s = [];
Object.keys(obj).forEach(function (key) {
s.push(key);
s.push('=\'');
s.push(obj[key]);
s.push('\';');
});
return s.join('');
}
|
javascript
|
function stringify (obj) {
var s = [];
Object.keys(obj).forEach(function (key) {
s.push(key);
s.push('=\'');
s.push(obj[key]);
s.push('\';');
});
return s.join('');
}
|
[
"function",
"stringify",
"(",
"obj",
")",
"{",
"var",
"s",
"=",
"[",
"]",
";",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"s",
".",
"push",
"(",
"key",
")",
";",
"s",
".",
"push",
"(",
"'=\\''",
")",
";",
"\\'",
"s",
".",
"push",
"(",
"obj",
"[",
"key",
"]",
")",
";",
"}",
")",
";",
"s",
".",
"push",
"(",
"'\\';'",
")",
";",
"}"
] |
Takes an Object and converts it into an ICY metadata string.
@param {Object} obj
@return {String}
@api public
|
[
"Takes",
"an",
"Object",
"and",
"converts",
"it",
"into",
"an",
"ICY",
"metadata",
"string",
"."
] |
1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6
|
https://github.com/TooTallNate/node-icy/blob/1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6/lib/stringify.js#L16-L25
|
train
|
TooTallNate/node-icy
|
examples/client.js
|
onMetadata
|
function onMetadata (metadata) {
metadata = icy.parse(metadata);
console.error('METADATA EVENT:');
console.error(metadata);
}
|
javascript
|
function onMetadata (metadata) {
metadata = icy.parse(metadata);
console.error('METADATA EVENT:');
console.error(metadata);
}
|
[
"function",
"onMetadata",
"(",
"metadata",
")",
"{",
"metadata",
"=",
"icy",
".",
"parse",
"(",
"metadata",
")",
";",
"console",
".",
"error",
"(",
"'METADATA EVENT:'",
")",
";",
"console",
".",
"error",
"(",
"metadata",
")",
";",
"}"
] |
Invoked for every "metadata" event from the `res` stream.
|
[
"Invoked",
"for",
"every",
"metadata",
"event",
"from",
"the",
"res",
"stream",
"."
] |
1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6
|
https://github.com/TooTallNate/node-icy/blob/1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6/examples/client.js#L50-L54
|
train
|
TooTallNate/node-icy
|
lib/preprocessor.js
|
preprocessor
|
function preprocessor (socket) {
debug('setting up "data" preprocessor');
function ondata (chunk) {
// TODO: don't be lazy, buffer if needed...
assert(chunk.length >= 3, 'buffer too small! ' + chunk.length);
if (/icy/i.test(chunk.slice(0, 3))) {
debug('got ICY response!');
var b = new Buffer(chunk.length + HTTP10.length - 'icy'.length);
var i = 0;
i += HTTP10.copy(b);
i += chunk.copy(b, i, 3);
assert.equal(i, b.length);
chunk = b;
socket._wasIcy = true;
} else {
socket._wasIcy = false;
}
return chunk;
}
var listeners;
function icyOnData (buf) {
var chunk = ondata(buf);
// clean up, and re-emit "data" event
socket.removeListener('data', icyOnData);
listeners.forEach(function (listener) {
socket.on('data', listener);
});
listeners = null;
socket.emit('data', chunk);
}
if ('function' == typeof socket.ondata) {
// node < v0.11.3, the `ondata` function is set on the socket
var origOnData = socket.ondata;
socket.ondata = function (buf, start, length) {
var chunk = ondata(buf.slice(start, length));
// now clean up and inject the modified `chunk`
socket.ondata = origOnData;
origOnData = null;
socket.ondata(chunk, 0, chunk.length);
};
} else if (socket.listeners('data').length > 0) {
// node >= v0.11.3, the "data" event is listened for directly
// add our own "data" listener, and remove all the old ones
listeners = socket.listeners('data');
socket.removeAllListeners('data');
socket.on('data', icyOnData);
} else {
// never?
throw new Error('should not happen...');
}
}
|
javascript
|
function preprocessor (socket) {
debug('setting up "data" preprocessor');
function ondata (chunk) {
// TODO: don't be lazy, buffer if needed...
assert(chunk.length >= 3, 'buffer too small! ' + chunk.length);
if (/icy/i.test(chunk.slice(0, 3))) {
debug('got ICY response!');
var b = new Buffer(chunk.length + HTTP10.length - 'icy'.length);
var i = 0;
i += HTTP10.copy(b);
i += chunk.copy(b, i, 3);
assert.equal(i, b.length);
chunk = b;
socket._wasIcy = true;
} else {
socket._wasIcy = false;
}
return chunk;
}
var listeners;
function icyOnData (buf) {
var chunk = ondata(buf);
// clean up, and re-emit "data" event
socket.removeListener('data', icyOnData);
listeners.forEach(function (listener) {
socket.on('data', listener);
});
listeners = null;
socket.emit('data', chunk);
}
if ('function' == typeof socket.ondata) {
// node < v0.11.3, the `ondata` function is set on the socket
var origOnData = socket.ondata;
socket.ondata = function (buf, start, length) {
var chunk = ondata(buf.slice(start, length));
// now clean up and inject the modified `chunk`
socket.ondata = origOnData;
origOnData = null;
socket.ondata(chunk, 0, chunk.length);
};
} else if (socket.listeners('data').length > 0) {
// node >= v0.11.3, the "data" event is listened for directly
// add our own "data" listener, and remove all the old ones
listeners = socket.listeners('data');
socket.removeAllListeners('data');
socket.on('data', icyOnData);
} else {
// never?
throw new Error('should not happen...');
}
}
|
[
"function",
"preprocessor",
"(",
"socket",
")",
"{",
"debug",
"(",
"'setting up \"data\" preprocessor'",
")",
";",
"function",
"ondata",
"(",
"chunk",
")",
"{",
"assert",
"(",
"chunk",
".",
"length",
">=",
"3",
",",
"'buffer too small! '",
"+",
"chunk",
".",
"length",
")",
";",
"if",
"(",
"/",
"icy",
"/",
"i",
".",
"test",
"(",
"chunk",
".",
"slice",
"(",
"0",
",",
"3",
")",
")",
")",
"{",
"debug",
"(",
"'got ICY response!'",
")",
";",
"var",
"b",
"=",
"new",
"Buffer",
"(",
"chunk",
".",
"length",
"+",
"HTTP10",
".",
"length",
"-",
"'icy'",
".",
"length",
")",
";",
"var",
"i",
"=",
"0",
";",
"i",
"+=",
"HTTP10",
".",
"copy",
"(",
"b",
")",
";",
"i",
"+=",
"chunk",
".",
"copy",
"(",
"b",
",",
"i",
",",
"3",
")",
";",
"assert",
".",
"equal",
"(",
"i",
",",
"b",
".",
"length",
")",
";",
"chunk",
"=",
"b",
";",
"socket",
".",
"_wasIcy",
"=",
"true",
";",
"}",
"else",
"{",
"socket",
".",
"_wasIcy",
"=",
"false",
";",
"}",
"return",
"chunk",
";",
"}",
"var",
"listeners",
";",
"function",
"icyOnData",
"(",
"buf",
")",
"{",
"var",
"chunk",
"=",
"ondata",
"(",
"buf",
")",
";",
"socket",
".",
"removeListener",
"(",
"'data'",
",",
"icyOnData",
")",
";",
"listeners",
".",
"forEach",
"(",
"function",
"(",
"listener",
")",
"{",
"socket",
".",
"on",
"(",
"'data'",
",",
"listener",
")",
";",
"}",
")",
";",
"listeners",
"=",
"null",
";",
"socket",
".",
"emit",
"(",
"'data'",
",",
"chunk",
")",
";",
"}",
"if",
"(",
"'function'",
"==",
"typeof",
"socket",
".",
"ondata",
")",
"{",
"var",
"origOnData",
"=",
"socket",
".",
"ondata",
";",
"socket",
".",
"ondata",
"=",
"function",
"(",
"buf",
",",
"start",
",",
"length",
")",
"{",
"var",
"chunk",
"=",
"ondata",
"(",
"buf",
".",
"slice",
"(",
"start",
",",
"length",
")",
")",
";",
"socket",
".",
"ondata",
"=",
"origOnData",
";",
"origOnData",
"=",
"null",
";",
"socket",
".",
"ondata",
"(",
"chunk",
",",
"0",
",",
"chunk",
".",
"length",
")",
";",
"}",
";",
"}",
"else",
"if",
"(",
"socket",
".",
"listeners",
"(",
"'data'",
")",
".",
"length",
">",
"0",
")",
"{",
"listeners",
"=",
"socket",
".",
"listeners",
"(",
"'data'",
")",
";",
"socket",
".",
"removeAllListeners",
"(",
"'data'",
")",
";",
"socket",
".",
"on",
"(",
"'data'",
",",
"icyOnData",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'should not happen...'",
")",
";",
"}",
"}"
] |
This all really... really.. sucks...
|
[
"This",
"all",
"really",
"...",
"really",
"..",
"sucks",
"..."
] |
1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6
|
https://github.com/TooTallNate/node-icy/blob/1c7278102d66b2cb52bc6dc0b3f2101c4cfdfee6/lib/preprocessor.js#L25-L82
|
train
|
hypery2k/galenframework-cli
|
core/postinstall.js
|
writeLocationFile
|
function writeLocationFile(location) {
log.info('Writing location.js file');
if (process.platform === 'win32') {
location = location.replace(/\\/g, '\\\\');
}
fs.writeFileSync(path.join(libPath, 'location.js'),
'module.exports.location = \'' + location + '\';');
}
|
javascript
|
function writeLocationFile(location) {
log.info('Writing location.js file');
if (process.platform === 'win32') {
location = location.replace(/\\/g, '\\\\');
}
fs.writeFileSync(path.join(libPath, 'location.js'),
'module.exports.location = \'' + location + '\';');
}
|
[
"function",
"writeLocationFile",
"(",
"location",
")",
"{",
"log",
".",
"info",
"(",
"'Writing location.js file'",
")",
";",
"if",
"(",
"process",
".",
"platform",
"===",
"'win32'",
")",
"{",
"location",
"=",
"location",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'\\\\\\\\'",
")",
";",
"}",
"\\\\",
"}"
] |
Save the destination directory back
@param {string} location - path of the directory
|
[
"Save",
"the",
"destination",
"directory",
"back"
] |
eb18499201779bdef072cbad67bb8ce0360980cb
|
https://github.com/hypery2k/galenframework-cli/blob/eb18499201779bdef072cbad67bb8ce0360980cb/core/postinstall.js#L157-L164
|
train
|
hypery2k/galenframework-cli
|
core/postinstall.js
|
findSuitableTempDirectory
|
function findSuitableTempDirectory(npmConf) {
const now = Date.now();
const candidateTmpDirs = [
process.env.TMPDIR || process.env.TEMP || npmConf.get('tmp'),
path.join(process.cwd(), 'tmp',
'/tmp')
];
for (let i = 0; i < candidateTmpDirs.length; i++) {
const candidatePath = path.join(candidateTmpDirs[i], 'galenframework');
try {
fs.mkdirsSync(candidatePath, '0777');
// Make double sure we have 0777 permissions; some operating systems
// default umask does not allow write by default.
fs.chmodSync(candidatePath, '0777');
const testFile = path.join(candidatePath, now + '.tmp');
fs.writeFileSync(testFile, 'test');
fs.unlinkSync(testFile);
return candidatePath;
} catch (e) {
log.info(candidatePath, 'is not writable:', e.message);
}
}
log.error('Can not find a writable tmp directory.');
exit(1);
}
|
javascript
|
function findSuitableTempDirectory(npmConf) {
const now = Date.now();
const candidateTmpDirs = [
process.env.TMPDIR || process.env.TEMP || npmConf.get('tmp'),
path.join(process.cwd(), 'tmp',
'/tmp')
];
for (let i = 0; i < candidateTmpDirs.length; i++) {
const candidatePath = path.join(candidateTmpDirs[i], 'galenframework');
try {
fs.mkdirsSync(candidatePath, '0777');
// Make double sure we have 0777 permissions; some operating systems
// default umask does not allow write by default.
fs.chmodSync(candidatePath, '0777');
const testFile = path.join(candidatePath, now + '.tmp');
fs.writeFileSync(testFile, 'test');
fs.unlinkSync(testFile);
return candidatePath;
} catch (e) {
log.info(candidatePath, 'is not writable:', e.message);
}
}
log.error('Can not find a writable tmp directory.');
exit(1);
}
|
[
"function",
"findSuitableTempDirectory",
"(",
"npmConf",
")",
"{",
"const",
"now",
"=",
"Date",
".",
"now",
"(",
")",
";",
"const",
"candidateTmpDirs",
"=",
"[",
"process",
".",
"env",
".",
"TMPDIR",
"||",
"process",
".",
"env",
".",
"TEMP",
"||",
"npmConf",
".",
"get",
"(",
"'tmp'",
")",
",",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'tmp'",
",",
"'/tmp'",
")",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"candidateTmpDirs",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"candidatePath",
"=",
"path",
".",
"join",
"(",
"candidateTmpDirs",
"[",
"i",
"]",
",",
"'galenframework'",
")",
";",
"try",
"{",
"fs",
".",
"mkdirsSync",
"(",
"candidatePath",
",",
"'0777'",
")",
";",
"fs",
".",
"chmodSync",
"(",
"candidatePath",
",",
"'0777'",
")",
";",
"const",
"testFile",
"=",
"path",
".",
"join",
"(",
"candidatePath",
",",
"now",
"+",
"'.tmp'",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"testFile",
",",
"'test'",
")",
";",
"fs",
".",
"unlinkSync",
"(",
"testFile",
")",
";",
"return",
"candidatePath",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"log",
".",
"info",
"(",
"candidatePath",
",",
"'is not writable:'",
",",
"e",
".",
"message",
")",
";",
"}",
"}",
"log",
".",
"error",
"(",
"'Can not find a writable tmp directory.'",
")",
";",
"exit",
"(",
"1",
")",
";",
"}"
] |
Function to find an writable temp directory
@param {object} npmConf - current NPM configuration
@returns {string} representing suitable temp directory
@function
|
[
"Function",
"to",
"find",
"an",
"writable",
"temp",
"directory"
] |
eb18499201779bdef072cbad67bb8ce0360980cb
|
https://github.com/hypery2k/galenframework-cli/blob/eb18499201779bdef072cbad67bb8ce0360980cb/core/postinstall.js#L183-L210
|
train
|
hypery2k/galenframework-cli
|
core/postinstall.js
|
getRequestOptions
|
function getRequestOptions(conf) {
const strictSSL = conf.get('strict-ssl');
let options = {
uri: downloadUrl,
encoding: null, // Get response as a buffer
followRedirect: true, // The default download path redirects to a CDN URL.
headers: {},
strictSSL: strictSSL
};
let proxyUrl = conf.get('https-proxy') || conf.get('http-proxy') || conf.get('proxy');
if (proxyUrl) {
// Print using proxy
let proxy = url.parse(proxyUrl);
if (proxy.auth) {
// Mask password
proxy.auth = proxy.auth.replace(/:.*$/, ':******');
}
log.info('Using proxy ' + url.format(proxy));
// Enable proxy
options.proxy = proxyUrl;
// If going through proxy, use the user-agent string from the npm config
options.headers['User-Agent'] = conf.get('user-agent');
}
// Use certificate authority settings from npm
const ca = conf.get('ca');
if (ca) {
log.info('Using npmconf ca');
options.ca = ca;
}
return options;
}
|
javascript
|
function getRequestOptions(conf) {
const strictSSL = conf.get('strict-ssl');
let options = {
uri: downloadUrl,
encoding: null, // Get response as a buffer
followRedirect: true, // The default download path redirects to a CDN URL.
headers: {},
strictSSL: strictSSL
};
let proxyUrl = conf.get('https-proxy') || conf.get('http-proxy') || conf.get('proxy');
if (proxyUrl) {
// Print using proxy
let proxy = url.parse(proxyUrl);
if (proxy.auth) {
// Mask password
proxy.auth = proxy.auth.replace(/:.*$/, ':******');
}
log.info('Using proxy ' + url.format(proxy));
// Enable proxy
options.proxy = proxyUrl;
// If going through proxy, use the user-agent string from the npm config
options.headers['User-Agent'] = conf.get('user-agent');
}
// Use certificate authority settings from npm
const ca = conf.get('ca');
if (ca) {
log.info('Using npmconf ca');
options.ca = ca;
}
return options;
}
|
[
"function",
"getRequestOptions",
"(",
"conf",
")",
"{",
"const",
"strictSSL",
"=",
"conf",
".",
"get",
"(",
"'strict-ssl'",
")",
";",
"let",
"options",
"=",
"{",
"uri",
":",
"downloadUrl",
",",
"encoding",
":",
"null",
",",
"followRedirect",
":",
"true",
",",
"headers",
":",
"{",
"}",
",",
"strictSSL",
":",
"strictSSL",
"}",
";",
"let",
"proxyUrl",
"=",
"conf",
".",
"get",
"(",
"'https-proxy'",
")",
"||",
"conf",
".",
"get",
"(",
"'http-proxy'",
")",
"||",
"conf",
".",
"get",
"(",
"'proxy'",
")",
";",
"if",
"(",
"proxyUrl",
")",
"{",
"let",
"proxy",
"=",
"url",
".",
"parse",
"(",
"proxyUrl",
")",
";",
"if",
"(",
"proxy",
".",
"auth",
")",
"{",
"proxy",
".",
"auth",
"=",
"proxy",
".",
"auth",
".",
"replace",
"(",
"/",
":.*$",
"/",
",",
"':******'",
")",
";",
"}",
"log",
".",
"info",
"(",
"'Using proxy '",
"+",
"url",
".",
"format",
"(",
"proxy",
")",
")",
";",
"options",
".",
"proxy",
"=",
"proxyUrl",
";",
"options",
".",
"headers",
"[",
"'User-Agent'",
"]",
"=",
"conf",
".",
"get",
"(",
"'user-agent'",
")",
";",
"}",
"const",
"ca",
"=",
"conf",
".",
"get",
"(",
"'ca'",
")",
";",
"if",
"(",
"ca",
")",
"{",
"log",
".",
"info",
"(",
"'Using npmconf ca'",
")",
";",
"options",
".",
"ca",
"=",
"ca",
";",
"}",
"return",
"options",
";",
"}"
] |
Create request opions object
@param {object} conf - current NPM config
@returns {{uri: string, encoding: null, followRedirect: boolean, headers: {}, strictSSL: *}}
@function
|
[
"Create",
"request",
"opions",
"object"
] |
eb18499201779bdef072cbad67bb8ce0360980cb
|
https://github.com/hypery2k/galenframework-cli/blob/eb18499201779bdef072cbad67bb8ce0360980cb/core/postinstall.js#L218-L255
|
train
|
hypery2k/galenframework-cli
|
core/postinstall.js
|
requestBinary
|
function requestBinary(requestOptions, filePath) {
const deferred = kew.defer();
const writePath = filePath + '-download-' + Date.now();
log.info('Receiving...');
let bar = null;
requestProgress(request(requestOptions, (error, response, body) => {
log.info('');
if (!error && response.statusCode === 200) {
fs.writeFileSync(writePath, body);
log.info('Received ' + Math.floor(body.length / 1024) + 'K total.');
fs.renameSync(writePath, filePath);
deferred.resolve({
requestOptions: requestOptions,
downloadedFile: filePath
});
} else if (response) {
log.error('Error requesting archive.\n' +
'Status: ' + response.statusCode + '\n' +
'Request options: ' + JSON.stringify(requestOptions, null, 2) + '\n' +
'Response headers: ' + JSON.stringify(response.headers, null, 2) + '\n' +
'Make sure your network and proxy settings are correct.\n\n');
exit(1);
} else if (error && error.stack && error.stack.indexOf('SELF_SIGNED_CERT_IN_CHAIN') != -1) {
log.error('Error making request.');
exit(1);
} else if (error) {
log.error('Error making request.\n' + error.stack + '\n\n' +
'Please report this full log at https://github.com/hypery2k/galenframework-cli/issues');
exit(1);
} else {
log.error('Something unexpected happened, please report this full ' +
'log at https://github.com/hypery2k/galenframework-cli/issues');
exit(1);
}
})).on('progress', (state) => {
if (!bar) {
bar = new Progress(' [:bar] :percent :etas', { total: state.total, width: 40 });
}
bar.curr = state.received;
bar.tick(0);
});
return deferred.promise;
}
|
javascript
|
function requestBinary(requestOptions, filePath) {
const deferred = kew.defer();
const writePath = filePath + '-download-' + Date.now();
log.info('Receiving...');
let bar = null;
requestProgress(request(requestOptions, (error, response, body) => {
log.info('');
if (!error && response.statusCode === 200) {
fs.writeFileSync(writePath, body);
log.info('Received ' + Math.floor(body.length / 1024) + 'K total.');
fs.renameSync(writePath, filePath);
deferred.resolve({
requestOptions: requestOptions,
downloadedFile: filePath
});
} else if (response) {
log.error('Error requesting archive.\n' +
'Status: ' + response.statusCode + '\n' +
'Request options: ' + JSON.stringify(requestOptions, null, 2) + '\n' +
'Response headers: ' + JSON.stringify(response.headers, null, 2) + '\n' +
'Make sure your network and proxy settings are correct.\n\n');
exit(1);
} else if (error && error.stack && error.stack.indexOf('SELF_SIGNED_CERT_IN_CHAIN') != -1) {
log.error('Error making request.');
exit(1);
} else if (error) {
log.error('Error making request.\n' + error.stack + '\n\n' +
'Please report this full log at https://github.com/hypery2k/galenframework-cli/issues');
exit(1);
} else {
log.error('Something unexpected happened, please report this full ' +
'log at https://github.com/hypery2k/galenframework-cli/issues');
exit(1);
}
})).on('progress', (state) => {
if (!bar) {
bar = new Progress(' [:bar] :percent :etas', { total: state.total, width: 40 });
}
bar.curr = state.received;
bar.tick(0);
});
return deferred.promise;
}
|
[
"function",
"requestBinary",
"(",
"requestOptions",
",",
"filePath",
")",
"{",
"const",
"deferred",
"=",
"kew",
".",
"defer",
"(",
")",
";",
"const",
"writePath",
"=",
"filePath",
"+",
"'-download-'",
"+",
"Date",
".",
"now",
"(",
")",
";",
"log",
".",
"info",
"(",
"'Receiving...'",
")",
";",
"let",
"bar",
"=",
"null",
";",
"requestProgress",
"(",
"request",
"(",
"requestOptions",
",",
"(",
"error",
",",
"response",
",",
"body",
")",
"=>",
"{",
"log",
".",
"info",
"(",
"''",
")",
";",
"if",
"(",
"!",
"error",
"&&",
"response",
".",
"statusCode",
"===",
"200",
")",
"{",
"fs",
".",
"writeFileSync",
"(",
"writePath",
",",
"body",
")",
";",
"log",
".",
"info",
"(",
"'Received '",
"+",
"Math",
".",
"floor",
"(",
"body",
".",
"length",
"/",
"1024",
")",
"+",
"'K total.'",
")",
";",
"fs",
".",
"renameSync",
"(",
"writePath",
",",
"filePath",
")",
";",
"deferred",
".",
"resolve",
"(",
"{",
"requestOptions",
":",
"requestOptions",
",",
"downloadedFile",
":",
"filePath",
"}",
")",
";",
"}",
"else",
"if",
"(",
"response",
")",
"{",
"log",
".",
"error",
"(",
"'Error requesting archive.\\n'",
"+",
"\\n",
"+",
"'Status: '",
"+",
"response",
".",
"statusCode",
"+",
"'\\n'",
"+",
"\\n",
"+",
"'Request options: '",
"+",
"JSON",
".",
"stringify",
"(",
"requestOptions",
",",
"null",
",",
"2",
")",
"+",
"'\\n'",
"+",
"\\n",
"+",
"'Response headers: '",
")",
";",
"JSON",
".",
"stringify",
"(",
"response",
".",
"headers",
",",
"null",
",",
"2",
")",
"}",
"else",
"'\\n'",
"}",
")",
")",
".",
"\\n",
"'Make sure your network and proxy settings are correct.\\n\\n'",
";",
"\\n",
"}"
] |
Downloads binary file
@param {object} requestOptions - to use for HTTP call
@param {string} filePath - download URL
@returns {*}
@function
|
[
"Downloads",
"binary",
"file"
] |
eb18499201779bdef072cbad67bb8ce0360980cb
|
https://github.com/hypery2k/galenframework-cli/blob/eb18499201779bdef072cbad67bb8ce0360980cb/core/postinstall.js#L264-L309
|
train
|
hypery2k/galenframework-cli
|
core/postinstall.js
|
extractDownload
|
function extractDownload(filePath, requestOptions, retry) {
const deferred = kew.defer();
// extract to a unique directory in case multiple processes are
// installing and extracting at once
const extractedPath = filePath + '-extract-' + Date.now();
let options = { cwd: extractedPath };
fs.mkdirsSync(extractedPath, '0777');
// Make double sure we have 0777 permissions; some operating systems
// default umask does not allow write by default.
fs.chmodSync(extractedPath, '0777');
if (filePath.substr(-4) === '.zip') {
log.info('Extracting zip contents');
try {
let zip = new AdmZip(filePath);
zip.extractAllTo(extractedPath, true);
deferred.resolve(extractedPath);
} catch (err) {
log.error('Error extracting zip');
deferred.reject(err);
}
} else {
log.info('Extracting tar contents (via spawned process)');
cp.execFile('tar', ['jxf', filePath], options, function (err) {
if (err) {
if (!retry) {
log.info('Error during extracting. Trying to download again.');
fs.unlinkSync(filePath);
return requestBinary(requestOptions, filePath).then(function (downloadedFile) {
return extractDownload(downloadedFile, requestOptions, true);
});
} else {
deferred.reject(err);
log.error('Error extracting archive');
}
} else {
deferred.resolve(extractedPath);
}
});
}
return deferred.promise;
}
|
javascript
|
function extractDownload(filePath, requestOptions, retry) {
const deferred = kew.defer();
// extract to a unique directory in case multiple processes are
// installing and extracting at once
const extractedPath = filePath + '-extract-' + Date.now();
let options = { cwd: extractedPath };
fs.mkdirsSync(extractedPath, '0777');
// Make double sure we have 0777 permissions; some operating systems
// default umask does not allow write by default.
fs.chmodSync(extractedPath, '0777');
if (filePath.substr(-4) === '.zip') {
log.info('Extracting zip contents');
try {
let zip = new AdmZip(filePath);
zip.extractAllTo(extractedPath, true);
deferred.resolve(extractedPath);
} catch (err) {
log.error('Error extracting zip');
deferred.reject(err);
}
} else {
log.info('Extracting tar contents (via spawned process)');
cp.execFile('tar', ['jxf', filePath], options, function (err) {
if (err) {
if (!retry) {
log.info('Error during extracting. Trying to download again.');
fs.unlinkSync(filePath);
return requestBinary(requestOptions, filePath).then(function (downloadedFile) {
return extractDownload(downloadedFile, requestOptions, true);
});
} else {
deferred.reject(err);
log.error('Error extracting archive');
}
} else {
deferred.resolve(extractedPath);
}
});
}
return deferred.promise;
}
|
[
"function",
"extractDownload",
"(",
"filePath",
",",
"requestOptions",
",",
"retry",
")",
"{",
"const",
"deferred",
"=",
"kew",
".",
"defer",
"(",
")",
";",
"const",
"extractedPath",
"=",
"filePath",
"+",
"'-extract-'",
"+",
"Date",
".",
"now",
"(",
")",
";",
"let",
"options",
"=",
"{",
"cwd",
":",
"extractedPath",
"}",
";",
"fs",
".",
"mkdirsSync",
"(",
"extractedPath",
",",
"'0777'",
")",
";",
"fs",
".",
"chmodSync",
"(",
"extractedPath",
",",
"'0777'",
")",
";",
"if",
"(",
"filePath",
".",
"substr",
"(",
"-",
"4",
")",
"===",
"'.zip'",
")",
"{",
"log",
".",
"info",
"(",
"'Extracting zip contents'",
")",
";",
"try",
"{",
"let",
"zip",
"=",
"new",
"AdmZip",
"(",
"filePath",
")",
";",
"zip",
".",
"extractAllTo",
"(",
"extractedPath",
",",
"true",
")",
";",
"deferred",
".",
"resolve",
"(",
"extractedPath",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"log",
".",
"error",
"(",
"'Error extracting zip'",
")",
";",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"}",
"}",
"else",
"{",
"log",
".",
"info",
"(",
"'Extracting tar contents (via spawned process)'",
")",
";",
"cp",
".",
"execFile",
"(",
"'tar'",
",",
"[",
"'jxf'",
",",
"filePath",
"]",
",",
"options",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"retry",
")",
"{",
"log",
".",
"info",
"(",
"'Error during extracting. Trying to download again.'",
")",
";",
"fs",
".",
"unlinkSync",
"(",
"filePath",
")",
";",
"return",
"requestBinary",
"(",
"requestOptions",
",",
"filePath",
")",
".",
"then",
"(",
"function",
"(",
"downloadedFile",
")",
"{",
"return",
"extractDownload",
"(",
"downloadedFile",
",",
"requestOptions",
",",
"true",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"log",
".",
"error",
"(",
"'Error extracting archive'",
")",
";",
"}",
"}",
"else",
"{",
"deferred",
".",
"resolve",
"(",
"extractedPath",
")",
";",
"}",
"}",
")",
";",
"}",
"return",
"deferred",
".",
"promise",
";",
"}"
] |
Extracts the given Archive
@param {string} filePath - path of the ZIP archive to extract
@param {object} requestOptions - request options for retry attempt
@param {boolean} retry - set to true if it's already an retry attempt
@returns {*} - path of the extracted archive content
@function
|
[
"Extracts",
"the",
"given",
"Archive"
] |
eb18499201779bdef072cbad67bb8ce0360980cb
|
https://github.com/hypery2k/galenframework-cli/blob/eb18499201779bdef072cbad67bb8ce0360980cb/core/postinstall.js#L319-L363
|
train
|
hypery2k/galenframework-cli
|
core/postinstall.js
|
copyIntoPlace
|
function copyIntoPlace(extractedPath, targetPath) {
log.info('Removing', targetPath);
return kew.nfcall(fs.remove, targetPath).then(function () {
// Look for the extracted directory, so we can rename it.
const files = fs.readdirSync(extractedPath);
for (let i = 0; i < files.length; i++) {
const file = path.join(extractedPath, files[i]);
if (fs.statSync(file).isDirectory() && file.indexOf(helper.version) !== -1) {
log.info('Copying extracted folder', file, '->', targetPath);
return kew.nfcall(fs.move, file, targetPath);
}
}
log.info('Could not find extracted file', files);
throw new Error('Could not find extracted file');
});
}
|
javascript
|
function copyIntoPlace(extractedPath, targetPath) {
log.info('Removing', targetPath);
return kew.nfcall(fs.remove, targetPath).then(function () {
// Look for the extracted directory, so we can rename it.
const files = fs.readdirSync(extractedPath);
for (let i = 0; i < files.length; i++) {
const file = path.join(extractedPath, files[i]);
if (fs.statSync(file).isDirectory() && file.indexOf(helper.version) !== -1) {
log.info('Copying extracted folder', file, '->', targetPath);
return kew.nfcall(fs.move, file, targetPath);
}
}
log.info('Could not find extracted file', files);
throw new Error('Could not find extracted file');
});
}
|
[
"function",
"copyIntoPlace",
"(",
"extractedPath",
",",
"targetPath",
")",
"{",
"log",
".",
"info",
"(",
"'Removing'",
",",
"targetPath",
")",
";",
"return",
"kew",
".",
"nfcall",
"(",
"fs",
".",
"remove",
",",
"targetPath",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"const",
"files",
"=",
"fs",
".",
"readdirSync",
"(",
"extractedPath",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"file",
"=",
"path",
".",
"join",
"(",
"extractedPath",
",",
"files",
"[",
"i",
"]",
")",
";",
"if",
"(",
"fs",
".",
"statSync",
"(",
"file",
")",
".",
"isDirectory",
"(",
")",
"&&",
"file",
".",
"indexOf",
"(",
"helper",
".",
"version",
")",
"!==",
"-",
"1",
")",
"{",
"log",
".",
"info",
"(",
"'Copying extracted folder'",
",",
"file",
",",
"'->'",
",",
"targetPath",
")",
";",
"return",
"kew",
".",
"nfcall",
"(",
"fs",
".",
"move",
",",
"file",
",",
"targetPath",
")",
";",
"}",
"}",
"log",
".",
"info",
"(",
"'Could not find extracted file'",
",",
"files",
")",
";",
"throw",
"new",
"Error",
"(",
"'Could not find extracted file'",
")",
";",
"}",
")",
";",
"}"
] |
Helper function to move folder contents to target directory
@param {string} extractedPath - source directory path
@param {string} targetPath - target directory path
@returns {string} {!Promise.<RESULT>} promise for chaing
@function
|
[
"Helper",
"function",
"to",
"move",
"folder",
"contents",
"to",
"target",
"directory"
] |
eb18499201779bdef072cbad67bb8ce0360980cb
|
https://github.com/hypery2k/galenframework-cli/blob/eb18499201779bdef072cbad67bb8ce0360980cb/core/postinstall.js#L372-L387
|
train
|
Azure/azure-openapi-validator
|
gulpfile.js
|
getPathVariableName
|
function getPathVariableName() {
// windows calls it's path 'Path' usually, but this is not guaranteed.
if (process.platform === 'win32') {
for (const key of Object.keys(process.env))
if (key.match(/^PATH$/i))
return key;
return 'Path';
}
return "PATH";
}
|
javascript
|
function getPathVariableName() {
// windows calls it's path 'Path' usually, but this is not guaranteed.
if (process.platform === 'win32') {
for (const key of Object.keys(process.env))
if (key.match(/^PATH$/i))
return key;
return 'Path';
}
return "PATH";
}
|
[
"function",
"getPathVariableName",
"(",
")",
"{",
"if",
"(",
"process",
".",
"platform",
"===",
"'win32'",
")",
"{",
"for",
"(",
"const",
"key",
"of",
"Object",
".",
"keys",
"(",
"process",
".",
"env",
")",
")",
"if",
"(",
"key",
".",
"match",
"(",
"/",
"^PATH$",
"/",
"i",
")",
")",
"return",
"key",
";",
"return",
"'Path'",
";",
"}",
"return",
"\"PATH\"",
";",
"}"
] |
add .bin to PATH
|
[
"add",
".",
"bin",
"to",
"PATH"
] |
10ae24980631f9eae638e58f3953c38c6f8a852f
|
https://github.com/Azure/azure-openapi-validator/blob/10ae24980631f9eae638e58f3953c38c6f8a852f/gulpfile.js#L14-L23
|
train
|
clay/amphora-storage-postgres
|
services/db.js
|
put
|
function put(key, value, testCacheEnabled) {
const cacheEnabled = testCacheEnabled || CACHE_ENABLED;
return postgres.put(key, value)
.then((res) => {
// persist to cache only if cache is set up/enabled, return postgres result regardless
if (cacheEnabled) {
return redis.put(key, value).then(() => res);
}
return res;
});
}
|
javascript
|
function put(key, value, testCacheEnabled) {
const cacheEnabled = testCacheEnabled || CACHE_ENABLED;
return postgres.put(key, value)
.then((res) => {
// persist to cache only if cache is set up/enabled, return postgres result regardless
if (cacheEnabled) {
return redis.put(key, value).then(() => res);
}
return res;
});
}
|
[
"function",
"put",
"(",
"key",
",",
"value",
",",
"testCacheEnabled",
")",
"{",
"const",
"cacheEnabled",
"=",
"testCacheEnabled",
"||",
"CACHE_ENABLED",
";",
"return",
"postgres",
".",
"put",
"(",
"key",
",",
"value",
")",
".",
"then",
"(",
"(",
"res",
")",
"=>",
"{",
"if",
"(",
"cacheEnabled",
")",
"{",
"return",
"redis",
".",
"put",
"(",
"key",
",",
"value",
")",
".",
"then",
"(",
"(",
")",
"=>",
"res",
")",
";",
"}",
"return",
"res",
";",
"}",
")",
";",
"}"
] |
Write a single value to cache and db
@param {String} key
@param {Object} value
@param {Boolean} testCacheEnabled used for tests
@return {Promise}
|
[
"Write",
"a",
"single",
"value",
"to",
"cache",
"and",
"db"
] |
4279f932eed660737f5e2565d8e6cc3349d2776b
|
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/services/db.js#L16-L28
|
train
|
clay/amphora-storage-postgres
|
services/db.js
|
get
|
function get(key) {
return redis.get(key)
.then(data => {
if (isUri(key)) return data;
return JSON.parse(data); // Parse non-uri data to match Postgres
})
.catch(() => postgres.get(key));
}
|
javascript
|
function get(key) {
return redis.get(key)
.then(data => {
if (isUri(key)) return data;
return JSON.parse(data); // Parse non-uri data to match Postgres
})
.catch(() => postgres.get(key));
}
|
[
"function",
"get",
"(",
"key",
")",
"{",
"return",
"redis",
".",
"get",
"(",
"key",
")",
".",
"then",
"(",
"data",
"=>",
"{",
"if",
"(",
"isUri",
"(",
"key",
")",
")",
"return",
"data",
";",
"return",
"JSON",
".",
"parse",
"(",
"data",
")",
";",
"}",
")",
".",
"catch",
"(",
"(",
")",
"=>",
"postgres",
".",
"get",
"(",
"key",
")",
")",
";",
"}"
] |
Return a value from the db or cache. Must
return a Object, not stringified JSON
@param {String} key
@return {Promise}
|
[
"Return",
"a",
"value",
"from",
"the",
"db",
"or",
"cache",
".",
"Must",
"return",
"a",
"Object",
"not",
"stringified",
"JSON"
] |
4279f932eed660737f5e2565d8e6cc3349d2776b
|
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/services/db.js#L37-L44
|
train
|
clay/amphora-storage-postgres
|
services/db.js
|
batch
|
function batch(ops, testCacheEnabled) {
const cacheEnabled = testCacheEnabled || CACHE_ENABLED;
return postgres.batch(ops)
.then((res) => {
if (cacheEnabled) {
return redis.batch(ops).then(() => res);
}
return res;
});
}
|
javascript
|
function batch(ops, testCacheEnabled) {
const cacheEnabled = testCacheEnabled || CACHE_ENABLED;
return postgres.batch(ops)
.then((res) => {
if (cacheEnabled) {
return redis.batch(ops).then(() => res);
}
return res;
});
}
|
[
"function",
"batch",
"(",
"ops",
",",
"testCacheEnabled",
")",
"{",
"const",
"cacheEnabled",
"=",
"testCacheEnabled",
"||",
"CACHE_ENABLED",
";",
"return",
"postgres",
".",
"batch",
"(",
"ops",
")",
".",
"then",
"(",
"(",
"res",
")",
"=>",
"{",
"if",
"(",
"cacheEnabled",
")",
"{",
"return",
"redis",
".",
"batch",
"(",
"ops",
")",
".",
"then",
"(",
"(",
")",
"=>",
"res",
")",
";",
"}",
"return",
"res",
";",
"}",
")",
";",
"}"
] |
Process a whole group of saves
@param {Array} ops
@param {Boolean} testCacheEnabled used for tests
@return {Promise}
|
[
"Process",
"a",
"whole",
"group",
"of",
"saves"
] |
4279f932eed660737f5e2565d8e6cc3349d2776b
|
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/services/db.js#L53-L64
|
train
|
clay/amphora-storage-postgres
|
postgres/client.js
|
createDBIfNotExists
|
function createDBIfNotExists() {
const tmpClient = knexLib({
client: 'pg',
connection: {
host: POSTGRES_HOST,
user: POSTGRES_USER,
password: POSTGRES_PASSWORD,
database: 'postgres',
port: POSTGRES_PORT
},
pool: { min: CONNECTION_POOL_MIN, max: CONNECTION_POOL_MAX }
});
// https://github.com/clay/amphora-storage-postgres/pull/7/files/16d3429767943a593ad9667b0d471fefc15088d3#diff-6a1e11a6146d3a5a01f955a44a2ac07a
return tmpClient.raw('CREATE DATABASE ??', [POSTGRES_DB])
.then(() => tmpClient.destroy())
.then(connect);
}
|
javascript
|
function createDBIfNotExists() {
const tmpClient = knexLib({
client: 'pg',
connection: {
host: POSTGRES_HOST,
user: POSTGRES_USER,
password: POSTGRES_PASSWORD,
database: 'postgres',
port: POSTGRES_PORT
},
pool: { min: CONNECTION_POOL_MIN, max: CONNECTION_POOL_MAX }
});
// https://github.com/clay/amphora-storage-postgres/pull/7/files/16d3429767943a593ad9667b0d471fefc15088d3#diff-6a1e11a6146d3a5a01f955a44a2ac07a
return tmpClient.raw('CREATE DATABASE ??', [POSTGRES_DB])
.then(() => tmpClient.destroy())
.then(connect);
}
|
[
"function",
"createDBIfNotExists",
"(",
")",
"{",
"const",
"tmpClient",
"=",
"knexLib",
"(",
"{",
"client",
":",
"'pg'",
",",
"connection",
":",
"{",
"host",
":",
"POSTGRES_HOST",
",",
"user",
":",
"POSTGRES_USER",
",",
"password",
":",
"POSTGRES_PASSWORD",
",",
"database",
":",
"'postgres'",
",",
"port",
":",
"POSTGRES_PORT",
"}",
",",
"pool",
":",
"{",
"min",
":",
"CONNECTION_POOL_MIN",
",",
"max",
":",
"CONNECTION_POOL_MAX",
"}",
"}",
")",
";",
"return",
"tmpClient",
".",
"raw",
"(",
"'CREATE DATABASE ??'",
",",
"[",
"POSTGRES_DB",
"]",
")",
".",
"then",
"(",
"(",
")",
"=>",
"tmpClient",
".",
"destroy",
"(",
")",
")",
".",
"then",
"(",
"connect",
")",
";",
"}"
] |
Connect to the default DB and create the Clay
DB. Once the DB has been made the connection
can be killed and we can try to re-connect
to the Clay DB
@returns {Promise}
|
[
"Connect",
"to",
"the",
"default",
"DB",
"and",
"create",
"the",
"Clay",
"DB",
".",
"Once",
"the",
"DB",
"has",
"been",
"made",
"the",
"connection",
"can",
"be",
"killed",
"and",
"we",
"can",
"try",
"to",
"re",
"-",
"connect",
"to",
"the",
"Clay",
"DB"
] |
4279f932eed660737f5e2565d8e6cc3349d2776b
|
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/postgres/client.js#L21-L38
|
train
|
clay/amphora-storage-postgres
|
postgres/client.js
|
connect
|
function connect() {
log('debug', `Connecting to Postgres at ${POSTGRES_HOST}:${POSTGRES_PORT}`);
knex = knexLib({
client: 'pg',
connection: {
host: POSTGRES_HOST,
user: POSTGRES_USER,
password: POSTGRES_PASSWORD,
database: POSTGRES_DB,
port: POSTGRES_PORT
},
pool: { min: CONNECTION_POOL_MIN, max: CONNECTION_POOL_MAX }
});
// TODO: improve error catch! https://github.com/clay/amphora-storage-postgres/pull/7/files/16d3429767943a593ad9667b0d471fefc15088d3#diff-6a1e11a6146d3a5a01f955a44a2ac07a
return knex.table('information_schema.tables').first()
.catch(createDBIfNotExists);
}
|
javascript
|
function connect() {
log('debug', `Connecting to Postgres at ${POSTGRES_HOST}:${POSTGRES_PORT}`);
knex = knexLib({
client: 'pg',
connection: {
host: POSTGRES_HOST,
user: POSTGRES_USER,
password: POSTGRES_PASSWORD,
database: POSTGRES_DB,
port: POSTGRES_PORT
},
pool: { min: CONNECTION_POOL_MIN, max: CONNECTION_POOL_MAX }
});
// TODO: improve error catch! https://github.com/clay/amphora-storage-postgres/pull/7/files/16d3429767943a593ad9667b0d471fefc15088d3#diff-6a1e11a6146d3a5a01f955a44a2ac07a
return knex.table('information_schema.tables').first()
.catch(createDBIfNotExists);
}
|
[
"function",
"connect",
"(",
")",
"{",
"log",
"(",
"'debug'",
",",
"`",
"${",
"POSTGRES_HOST",
"}",
"${",
"POSTGRES_PORT",
"}",
"`",
")",
";",
"knex",
"=",
"knexLib",
"(",
"{",
"client",
":",
"'pg'",
",",
"connection",
":",
"{",
"host",
":",
"POSTGRES_HOST",
",",
"user",
":",
"POSTGRES_USER",
",",
"password",
":",
"POSTGRES_PASSWORD",
",",
"database",
":",
"POSTGRES_DB",
",",
"port",
":",
"POSTGRES_PORT",
"}",
",",
"pool",
":",
"{",
"min",
":",
"CONNECTION_POOL_MIN",
",",
"max",
":",
"CONNECTION_POOL_MAX",
"}",
"}",
")",
";",
"return",
"knex",
".",
"table",
"(",
"'information_schema.tables'",
")",
".",
"first",
"(",
")",
".",
"catch",
"(",
"createDBIfNotExists",
")",
";",
"}"
] |
Connect to the DB. We need to do a quick check
to see if we're actually connected to the Clay
DB. If we aren't, connect to default and then
use that connection to create the Clay DB.
@returns {Promise}
|
[
"Connect",
"to",
"the",
"DB",
".",
"We",
"need",
"to",
"do",
"a",
"quick",
"check",
"to",
"see",
"if",
"we",
"re",
"actually",
"connected",
"to",
"the",
"Clay",
"DB",
".",
"If",
"we",
"aren",
"t",
"connect",
"to",
"default",
"and",
"then",
"use",
"that",
"connection",
"to",
"create",
"the",
"Clay",
"DB",
"."
] |
4279f932eed660737f5e2565d8e6cc3349d2776b
|
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/postgres/client.js#L48-L66
|
train
|
clay/amphora-storage-postgres
|
postgres/client.js
|
get
|
function get(key) {
const dataProp = 'data';
return baseQuery(key)
.select(dataProp)
.where('id', key)
.then(pullValFromRows(key, dataProp));
}
|
javascript
|
function get(key) {
const dataProp = 'data';
return baseQuery(key)
.select(dataProp)
.where('id', key)
.then(pullValFromRows(key, dataProp));
}
|
[
"function",
"get",
"(",
"key",
")",
"{",
"const",
"dataProp",
"=",
"'data'",
";",
"return",
"baseQuery",
"(",
"key",
")",
".",
"select",
"(",
"dataProp",
")",
".",
"where",
"(",
"'id'",
",",
"key",
")",
".",
"then",
"(",
"pullValFromRows",
"(",
"key",
",",
"dataProp",
")",
")",
";",
"}"
] |
Retrieve a single entry from the DB
@param {String} key
@return {Promise}
|
[
"Retrieve",
"a",
"single",
"entry",
"from",
"the",
"DB"
] |
4279f932eed660737f5e2565d8e6cc3349d2776b
|
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/postgres/client.js#L99-L106
|
train
|
clay/amphora-storage-postgres
|
postgres/client.js
|
put
|
function put(key, value) {
const { schema, table } = findSchemaAndTable(key),
map = columnToValueMap('id', key); // create the value map
// add data to the map
columnToValueMap('data', wrapInObject(key, parseOrNot(value)), map);
let url;
if (isUri(key)) {
url = decode(key.split('/_uris/').pop());
// add url column to map if we're PUTting a uri
columnToValueMap('url', url, map);
}
return onConflictPut(map, schema, table)
.then(() => map.data);
}
|
javascript
|
function put(key, value) {
const { schema, table } = findSchemaAndTable(key),
map = columnToValueMap('id', key); // create the value map
// add data to the map
columnToValueMap('data', wrapInObject(key, parseOrNot(value)), map);
let url;
if (isUri(key)) {
url = decode(key.split('/_uris/').pop());
// add url column to map if we're PUTting a uri
columnToValueMap('url', url, map);
}
return onConflictPut(map, schema, table)
.then(() => map.data);
}
|
[
"function",
"put",
"(",
"key",
",",
"value",
")",
"{",
"const",
"{",
"schema",
",",
"table",
"}",
"=",
"findSchemaAndTable",
"(",
"key",
")",
",",
"map",
"=",
"columnToValueMap",
"(",
"'id'",
",",
"key",
")",
";",
"columnToValueMap",
"(",
"'data'",
",",
"wrapInObject",
"(",
"key",
",",
"parseOrNot",
"(",
"value",
")",
")",
",",
"map",
")",
";",
"let",
"url",
";",
"if",
"(",
"isUri",
"(",
"key",
")",
")",
"{",
"url",
"=",
"decode",
"(",
"key",
".",
"split",
"(",
"'/_uris/'",
")",
".",
"pop",
"(",
")",
")",
";",
"columnToValueMap",
"(",
"'url'",
",",
"url",
",",
"map",
")",
";",
"}",
"return",
"onConflictPut",
"(",
"map",
",",
"schema",
",",
"table",
")",
".",
"then",
"(",
"(",
")",
"=>",
"map",
".",
"data",
")",
";",
"}"
] |
Insert a row into the DB
@param {String} key
@param {Object} value
@return {Promise}
|
[
"Insert",
"a",
"row",
"into",
"the",
"DB"
] |
4279f932eed660737f5e2565d8e6cc3349d2776b
|
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/postgres/client.js#L131-L150
|
train
|
clay/amphora-storage-postgres
|
postgres/client.js
|
patch
|
function patch(prop) {
return (key, value) => {
const { schema, table } = findSchemaAndTable(key);
return raw('UPDATE ?? SET ?? = ?? || ? WHERE id = ?', [`${schema ? `${schema}.` : ''}${table}`, prop, prop, JSON.stringify(value), key]);
};
}
|
javascript
|
function patch(prop) {
return (key, value) => {
const { schema, table } = findSchemaAndTable(key);
return raw('UPDATE ?? SET ?? = ?? || ? WHERE id = ?', [`${schema ? `${schema}.` : ''}${table}`, prop, prop, JSON.stringify(value), key]);
};
}
|
[
"function",
"patch",
"(",
"prop",
")",
"{",
"return",
"(",
"key",
",",
"value",
")",
"=>",
"{",
"const",
"{",
"schema",
",",
"table",
"}",
"=",
"findSchemaAndTable",
"(",
"key",
")",
";",
"return",
"raw",
"(",
"'UPDATE ?? SET ?? = ?? || ? WHERE id = ?'",
",",
"[",
"`",
"${",
"schema",
"?",
"`",
"${",
"schema",
"}",
"`",
":",
"''",
"}",
"${",
"table",
"}",
"`",
",",
"prop",
",",
"prop",
",",
"JSON",
".",
"stringify",
"(",
"value",
")",
",",
"key",
"]",
")",
";",
"}",
";",
"}"
] |
Returns a function that handles data patching based on the curried prop.
@param {String} prop
@return {Function}
|
[
"Returns",
"a",
"function",
"that",
"handles",
"data",
"patching",
"based",
"on",
"the",
"curried",
"prop",
"."
] |
4279f932eed660737f5e2565d8e6cc3349d2776b
|
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/postgres/client.js#L157-L163
|
train
|
clay/amphora-storage-postgres
|
postgres/client.js
|
createReadStream
|
function createReadStream(options) {
const { prefix, values, keys } = options,
transform = TransformStream(options),
selects = [];
if (keys) selects.push('id');
if (values) selects.push('data');
baseQuery(prefix)
.select(...selects)
.where('id', 'like', `${prefix}%`)
.pipe(transform);
return transform;
}
|
javascript
|
function createReadStream(options) {
const { prefix, values, keys } = options,
transform = TransformStream(options),
selects = [];
if (keys) selects.push('id');
if (values) selects.push('data');
baseQuery(prefix)
.select(...selects)
.where('id', 'like', `${prefix}%`)
.pipe(transform);
return transform;
}
|
[
"function",
"createReadStream",
"(",
"options",
")",
"{",
"const",
"{",
"prefix",
",",
"values",
",",
"keys",
"}",
"=",
"options",
",",
"transform",
"=",
"TransformStream",
"(",
"options",
")",
",",
"selects",
"=",
"[",
"]",
";",
"if",
"(",
"keys",
")",
"selects",
".",
"push",
"(",
"'id'",
")",
";",
"if",
"(",
"values",
")",
"selects",
".",
"push",
"(",
"'data'",
")",
";",
"baseQuery",
"(",
"prefix",
")",
".",
"select",
"(",
"...",
"selects",
")",
".",
"where",
"(",
"'id'",
",",
"'like'",
",",
"`",
"${",
"prefix",
"}",
"`",
")",
".",
"pipe",
"(",
"transform",
")",
";",
"return",
"transform",
";",
"}"
] |
Return a readable stream of query results
from the db
@param {Object} options
@return {Stream}
|
[
"Return",
"a",
"readable",
"stream",
"of",
"query",
"results",
"from",
"the",
"db"
] |
4279f932eed660737f5e2565d8e6cc3349d2776b
|
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/postgres/client.js#L240-L254
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.