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
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
glennjones/elsewhere-profiles | lib/profile.js | function(urls){
if(this.hCards.length > -1){
// remove all organisational hCards using fn = org.organization-name pattern
var i = this.hCards.length;
while (i--) {
if(this.hCards[i].org && this.hCards[i].org[0]['organization-name']){
if( this.hCards[i].fn === this.hCards[i].org[0]['organization-name'] ){
this.hCards.splice(i,1);
}
}
}
// if there is only one hcard use that
if(this.hCards.length === 1){
this.representativehCard = this.hCards[0];
}else{
i = this.hCards.length;
var x = 0;
while (x < i) {
var hcard = this.hCards[x];
if(hcard.url){
// match the urls of the hcard to the known urls
for (var y = 0; y < urls.length; y++) {
for (var z = 0; z < hcard.url.length; z++) {
if( utils.compareUrl(urls[y], hcard.url[z]) ){
this.representativehCard = hcard;
}
}
}
// match the xfn urls of the page to hcard urls
if(this.xfn.length > -1){
for (var z = 0; z < this.xfn.length; z++) {
for (var y = 0; y < hcard.url.length; y++) {
if( this.xfn[z].link !== undefined
&& this.xfn[z].rel !== undefined
&& utils.compareUrl(hcard.url[y], this.xfn[z].link)
&& this.xfn[z].rel === 'me'){
this.representativehCard = hcard;
}
}
}
}
}
x++;
}
}
}
// if we have a hresume use contact hcard
if(this.hResumes.length !== 0){
if(this.hResumes[0].contact){
this.representativehCard = this.hResumes[0].contact
// description
if(this.hResumes[0].summary !== '')
this.representativehCard.note = this.hResumes[0].summary;
// job role
// org
}
}
this.filterRepresentativehCard();
} | javascript | function(urls){
if(this.hCards.length > -1){
// remove all organisational hCards using fn = org.organization-name pattern
var i = this.hCards.length;
while (i--) {
if(this.hCards[i].org && this.hCards[i].org[0]['organization-name']){
if( this.hCards[i].fn === this.hCards[i].org[0]['organization-name'] ){
this.hCards.splice(i,1);
}
}
}
// if there is only one hcard use that
if(this.hCards.length === 1){
this.representativehCard = this.hCards[0];
}else{
i = this.hCards.length;
var x = 0;
while (x < i) {
var hcard = this.hCards[x];
if(hcard.url){
// match the urls of the hcard to the known urls
for (var y = 0; y < urls.length; y++) {
for (var z = 0; z < hcard.url.length; z++) {
if( utils.compareUrl(urls[y], hcard.url[z]) ){
this.representativehCard = hcard;
}
}
}
// match the xfn urls of the page to hcard urls
if(this.xfn.length > -1){
for (var z = 0; z < this.xfn.length; z++) {
for (var y = 0; y < hcard.url.length; y++) {
if( this.xfn[z].link !== undefined
&& this.xfn[z].rel !== undefined
&& utils.compareUrl(hcard.url[y], this.xfn[z].link)
&& this.xfn[z].rel === 'me'){
this.representativehCard = hcard;
}
}
}
}
}
x++;
}
}
}
// if we have a hresume use contact hcard
if(this.hResumes.length !== 0){
if(this.hResumes[0].contact){
this.representativehCard = this.hResumes[0].contact
// description
if(this.hResumes[0].summary !== '')
this.representativehCard.note = this.hResumes[0].summary;
// job role
// org
}
}
this.filterRepresentativehCard();
} | [
"function",
"(",
"urls",
")",
"{",
"if",
"(",
"this",
".",
"hCards",
".",
"length",
">",
"-",
"1",
")",
"{",
"var",
"i",
"=",
"this",
".",
"hCards",
".",
"length",
";",
"while",
"(",
"i",
"--",
")",
"{",
"if",
"(",
"this",
".",
"hCards",
"[",
"i",
"]",
".",
"org",
"&&",
"this",
".",
"hCards",
"[",
"i",
"]",
".",
"org",
"[",
"0",
"]",
"[",
"'organization-name'",
"]",
")",
"{",
"if",
"(",
"this",
".",
"hCards",
"[",
"i",
"]",
".",
"fn",
"===",
"this",
".",
"hCards",
"[",
"i",
"]",
".",
"org",
"[",
"0",
"]",
"[",
"'organization-name'",
"]",
")",
"{",
"this",
".",
"hCards",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"}",
"}",
"}",
"if",
"(",
"this",
".",
"hCards",
".",
"length",
"===",
"1",
")",
"{",
"this",
".",
"representativehCard",
"=",
"this",
".",
"hCards",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"i",
"=",
"this",
".",
"hCards",
".",
"length",
";",
"var",
"x",
"=",
"0",
";",
"while",
"(",
"x",
"<",
"i",
")",
"{",
"var",
"hcard",
"=",
"this",
".",
"hCards",
"[",
"x",
"]",
";",
"if",
"(",
"hcard",
".",
"url",
")",
"{",
"for",
"(",
"var",
"y",
"=",
"0",
";",
"y",
"<",
"urls",
".",
"length",
";",
"y",
"++",
")",
"{",
"for",
"(",
"var",
"z",
"=",
"0",
";",
"z",
"<",
"hcard",
".",
"url",
".",
"length",
";",
"z",
"++",
")",
"{",
"if",
"(",
"utils",
".",
"compareUrl",
"(",
"urls",
"[",
"y",
"]",
",",
"hcard",
".",
"url",
"[",
"z",
"]",
")",
")",
"{",
"this",
".",
"representativehCard",
"=",
"hcard",
";",
"}",
"}",
"}",
"if",
"(",
"this",
".",
"xfn",
".",
"length",
">",
"-",
"1",
")",
"{",
"for",
"(",
"var",
"z",
"=",
"0",
";",
"z",
"<",
"this",
".",
"xfn",
".",
"length",
";",
"z",
"++",
")",
"{",
"for",
"(",
"var",
"y",
"=",
"0",
";",
"y",
"<",
"hcard",
".",
"url",
".",
"length",
";",
"y",
"++",
")",
"{",
"if",
"(",
"this",
".",
"xfn",
"[",
"z",
"]",
".",
"link",
"!==",
"undefined",
"&&",
"this",
".",
"xfn",
"[",
"z",
"]",
".",
"rel",
"!==",
"undefined",
"&&",
"utils",
".",
"compareUrl",
"(",
"hcard",
".",
"url",
"[",
"y",
"]",
",",
"this",
".",
"xfn",
"[",
"z",
"]",
".",
"link",
")",
"&&",
"this",
".",
"xfn",
"[",
"z",
"]",
".",
"rel",
"===",
"'me'",
")",
"{",
"this",
".",
"representativehCard",
"=",
"hcard",
";",
"}",
"}",
"}",
"}",
"}",
"x",
"++",
";",
"}",
"}",
"}",
"if",
"(",
"this",
".",
"hResumes",
".",
"length",
"!==",
"0",
")",
"{",
"if",
"(",
"this",
".",
"hResumes",
"[",
"0",
"]",
".",
"contact",
")",
"{",
"this",
".",
"representativehCard",
"=",
"this",
".",
"hResumes",
"[",
"0",
"]",
".",
"contact",
"if",
"(",
"this",
".",
"hResumes",
"[",
"0",
"]",
".",
"summary",
"!==",
"''",
")",
"this",
".",
"representativehCard",
".",
"note",
"=",
"this",
".",
"hResumes",
"[",
"0",
"]",
".",
"summary",
";",
"}",
"}",
"this",
".",
"filterRepresentativehCard",
"(",
")",
";",
"}"
] | using representative hCard parsing rules to find the right hCard | [
"using",
"representative",
"hCard",
"parsing",
"rules",
"to",
"find",
"the",
"right",
"hCard"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/profile.js#L24-L93 | train |
|
glennjones/elsewhere-profiles | lib/profile.js | function(){
var i = filters.length,
x = 0,
urlObj = url.parse(this.url, parseQueryString=false);
while (x < i) {
if(filters[x].domain === urlObj.hostname){
for (var y = 0; y < filters[x].hCardBlockList.length; y++) {
delete this.representativehCard.properties[filters[x].hCardBlockList[y]];
}
}
x++;
}
} | javascript | function(){
var i = filters.length,
x = 0,
urlObj = url.parse(this.url, parseQueryString=false);
while (x < i) {
if(filters[x].domain === urlObj.hostname){
for (var y = 0; y < filters[x].hCardBlockList.length; y++) {
delete this.representativehCard.properties[filters[x].hCardBlockList[y]];
}
}
x++;
}
} | [
"function",
"(",
")",
"{",
"var",
"i",
"=",
"filters",
".",
"length",
",",
"x",
"=",
"0",
",",
"urlObj",
"=",
"url",
".",
"parse",
"(",
"this",
".",
"url",
",",
"parseQueryString",
"=",
"false",
")",
";",
"while",
"(",
"x",
"<",
"i",
")",
"{",
"if",
"(",
"filters",
"[",
"x",
"]",
".",
"domain",
"===",
"urlObj",
".",
"hostname",
")",
"{",
"for",
"(",
"var",
"y",
"=",
"0",
";",
"y",
"<",
"filters",
"[",
"x",
"]",
".",
"hCardBlockList",
".",
"length",
";",
"y",
"++",
")",
"{",
"delete",
"this",
".",
"representativehCard",
".",
"properties",
"[",
"filters",
"[",
"x",
"]",
".",
"hCardBlockList",
"[",
"y",
"]",
"]",
";",
"}",
"}",
"x",
"++",
";",
"}",
"}"
] | loops through the filter and deletes properties in the block list from the matching domains representative hCard | [
"loops",
"through",
"the",
"filter",
"and",
"deletes",
"properties",
"in",
"the",
"block",
"list",
"from",
"the",
"matching",
"domains",
"representative",
"hCard"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/profile.js#L98-L111 | train |
|
nattreid/cms | assets/js/cms.bundled.js | winnow | function winnow( elements, qualifier, not ) {
if ( isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
return !!qualifier.call( elem, i, elem ) !== not;
} );
}
// Single element
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
} );
}
// Arraylike of elements (jQuery, arguments, Array)
if ( typeof qualifier !== "string" ) {
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) > -1 ) !== not;
} );
}
// Filtered directly for both simple and complex selectors
return jQuery.filter( qualifier, elements, not );
} | javascript | function winnow( elements, qualifier, not ) {
if ( isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
return !!qualifier.call( elem, i, elem ) !== not;
} );
}
// Single element
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
} );
}
// Arraylike of elements (jQuery, arguments, Array)
if ( typeof qualifier !== "string" ) {
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) > -1 ) !== not;
} );
}
// Filtered directly for both simple and complex selectors
return jQuery.filter( qualifier, elements, not );
} | [
"function",
"winnow",
"(",
"elements",
",",
"qualifier",
",",
"not",
")",
"{",
"if",
"(",
"isFunction",
"(",
"qualifier",
")",
")",
"{",
"return",
"jQuery",
".",
"grep",
"(",
"elements",
",",
"function",
"(",
"elem",
",",
"i",
")",
"{",
"return",
"!",
"!",
"qualifier",
".",
"call",
"(",
"elem",
",",
"i",
",",
"elem",
")",
"!==",
"not",
";",
"}",
")",
";",
"}",
"if",
"(",
"qualifier",
".",
"nodeType",
")",
"{",
"return",
"jQuery",
".",
"grep",
"(",
"elements",
",",
"function",
"(",
"elem",
")",
"{",
"return",
"(",
"elem",
"===",
"qualifier",
")",
"!==",
"not",
";",
"}",
")",
";",
"}",
"if",
"(",
"typeof",
"qualifier",
"!==",
"\"string\"",
")",
"{",
"return",
"jQuery",
".",
"grep",
"(",
"elements",
",",
"function",
"(",
"elem",
")",
"{",
"return",
"(",
"indexOf",
".",
"call",
"(",
"qualifier",
",",
"elem",
")",
">",
"-",
"1",
")",
"!==",
"not",
";",
"}",
")",
";",
"}",
"return",
"jQuery",
".",
"filter",
"(",
"qualifier",
",",
"elements",
",",
"not",
")",
";",
"}"
] | Implement the identical functionality for filter and not | [
"Implement",
"the",
"identical",
"functionality",
"for",
"filter",
"and",
"not"
] | 28eae564c6a8cdaf01d32ff5a1dffba58232f9c1 | https://github.com/nattreid/cms/blob/28eae564c6a8cdaf01d32ff5a1dffba58232f9c1/assets/js/cms.bundled.js#L2836-L2859 | train |
nattreid/cms | assets/js/cms.bundled.js | function( data ) {
// For mutual compressibility with _default, replace `this` access with a local var.
// `|| data` is dead code meant only to preserve the variable through minification.
var el = this || data;
// Claim the first handler
if ( rcheckableType.test( el.type ) &&
el.click && nodeName( el, "input" ) ) {
// dataPriv.set( el, "click", ... )
leverageNative( el, "click", returnTrue );
}
// Return false to allow normal processing in the caller
return false;
} | javascript | function( data ) {
// For mutual compressibility with _default, replace `this` access with a local var.
// `|| data` is dead code meant only to preserve the variable through minification.
var el = this || data;
// Claim the first handler
if ( rcheckableType.test( el.type ) &&
el.click && nodeName( el, "input" ) ) {
// dataPriv.set( el, "click", ... )
leverageNative( el, "click", returnTrue );
}
// Return false to allow normal processing in the caller
return false;
} | [
"function",
"(",
"data",
")",
"{",
"var",
"el",
"=",
"this",
"||",
"data",
";",
"if",
"(",
"rcheckableType",
".",
"test",
"(",
"el",
".",
"type",
")",
"&&",
"el",
".",
"click",
"&&",
"nodeName",
"(",
"el",
",",
"\"input\"",
")",
")",
"{",
"leverageNative",
"(",
"el",
",",
"\"click\"",
",",
"returnTrue",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Utilize native event to ensure correct state for checkable inputs | [
"Utilize",
"native",
"event",
"to",
"ensure",
"correct",
"state",
"for",
"checkable",
"inputs"
] | 28eae564c6a8cdaf01d32ff5a1dffba58232f9c1 | https://github.com/nattreid/cms/blob/28eae564c6a8cdaf01d32ff5a1dffba58232f9c1/assets/js/cms.bundled.js#L5358-L5374 | train |
|
nattreid/cms | assets/js/cms.bundled.js | finalPropName | function finalPropName( name ) {
var final = jQuery.cssProps[ name ] || vendorProps[ name ];
if ( final ) {
return final;
}
if ( name in emptyStyle ) {
return name;
}
return vendorProps[ name ] = vendorPropName( name ) || name;
} | javascript | function finalPropName( name ) {
var final = jQuery.cssProps[ name ] || vendorProps[ name ];
if ( final ) {
return final;
}
if ( name in emptyStyle ) {
return name;
}
return vendorProps[ name ] = vendorPropName( name ) || name;
} | [
"function",
"finalPropName",
"(",
"name",
")",
"{",
"var",
"final",
"=",
"jQuery",
".",
"cssProps",
"[",
"name",
"]",
"||",
"vendorProps",
"[",
"name",
"]",
";",
"if",
"(",
"final",
")",
"{",
"return",
"final",
";",
"}",
"if",
"(",
"name",
"in",
"emptyStyle",
")",
"{",
"return",
"name",
";",
"}",
"return",
"vendorProps",
"[",
"name",
"]",
"=",
"vendorPropName",
"(",
"name",
")",
"||",
"name",
";",
"}"
] | Return a potentially-mapped jQuery.cssProps or vendor prefixed property | [
"Return",
"a",
"potentially",
"-",
"mapped",
"jQuery",
".",
"cssProps",
"or",
"vendor",
"prefixed",
"property"
] | 28eae564c6a8cdaf01d32ff5a1dffba58232f9c1 | https://github.com/nattreid/cms/blob/28eae564c6a8cdaf01d32ff5a1dffba58232f9c1/assets/js/cms.bundled.js#L6431-L6441 | train |
nattreid/cms | assets/js/cms.bundled.js | function( element, set ) {
var i = 0, length = set.length;
for ( ; i < length; i++ ) {
if ( set[ i ] !== null ) {
element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
}
}
} | javascript | function( element, set ) {
var i = 0, length = set.length;
for ( ; i < length; i++ ) {
if ( set[ i ] !== null ) {
element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
}
}
} | [
"function",
"(",
"element",
",",
"set",
")",
"{",
"var",
"i",
"=",
"0",
",",
"length",
"=",
"set",
".",
"length",
";",
"for",
"(",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"set",
"[",
"i",
"]",
"!==",
"null",
")",
"{",
"element",
".",
"data",
"(",
"dataSpace",
"+",
"set",
"[",
"i",
"]",
",",
"element",
"[",
"0",
"]",
".",
"style",
"[",
"set",
"[",
"i",
"]",
"]",
")",
";",
"}",
"}",
"}"
] | Saves a set of properties in a data storage | [
"Saves",
"a",
"set",
"of",
"properties",
"in",
"a",
"data",
"storage"
] | 28eae564c6a8cdaf01d32ff5a1dffba58232f9c1 | https://github.com/nattreid/cms/blob/28eae564c6a8cdaf01d32ff5a1dffba58232f9c1/assets/js/cms.bundled.js#L12834-L12841 | train |
|
nattreid/cms | assets/js/cms.bundled.js | function( element ) {
var placeholder,
cssPosition = element.css( "position" ),
position = element.position();
// Lock in margins first to account for form elements, which
// will change margin if you explicitly set height
// see: http://jsfiddle.net/JZSMt/3/ https://bugs.webkit.org/show_bug.cgi?id=107380
// Support: Safari
element.css( {
marginTop: element.css( "marginTop" ),
marginBottom: element.css( "marginBottom" ),
marginLeft: element.css( "marginLeft" ),
marginRight: element.css( "marginRight" )
} )
.outerWidth( element.outerWidth() )
.outerHeight( element.outerHeight() );
if ( /^(static|relative)/.test( cssPosition ) ) {
cssPosition = "absolute";
placeholder = $( "<" + element[ 0 ].nodeName + ">" ).insertAfter( element ).css( {
// Convert inline to inline block to account for inline elements
// that turn to inline block based on content (like img)
display: /^(inline|ruby)/.test( element.css( "display" ) ) ?
"inline-block" :
"block",
visibility: "hidden",
// Margins need to be set to account for margin collapse
marginTop: element.css( "marginTop" ),
marginBottom: element.css( "marginBottom" ),
marginLeft: element.css( "marginLeft" ),
marginRight: element.css( "marginRight" ),
"float": element.css( "float" )
} )
.outerWidth( element.outerWidth() )
.outerHeight( element.outerHeight() )
.addClass( "ui-effects-placeholder" );
element.data( dataSpace + "placeholder", placeholder );
}
element.css( {
position: cssPosition,
left: position.left,
top: position.top
} );
return placeholder;
} | javascript | function( element ) {
var placeholder,
cssPosition = element.css( "position" ),
position = element.position();
// Lock in margins first to account for form elements, which
// will change margin if you explicitly set height
// see: http://jsfiddle.net/JZSMt/3/ https://bugs.webkit.org/show_bug.cgi?id=107380
// Support: Safari
element.css( {
marginTop: element.css( "marginTop" ),
marginBottom: element.css( "marginBottom" ),
marginLeft: element.css( "marginLeft" ),
marginRight: element.css( "marginRight" )
} )
.outerWidth( element.outerWidth() )
.outerHeight( element.outerHeight() );
if ( /^(static|relative)/.test( cssPosition ) ) {
cssPosition = "absolute";
placeholder = $( "<" + element[ 0 ].nodeName + ">" ).insertAfter( element ).css( {
// Convert inline to inline block to account for inline elements
// that turn to inline block based on content (like img)
display: /^(inline|ruby)/.test( element.css( "display" ) ) ?
"inline-block" :
"block",
visibility: "hidden",
// Margins need to be set to account for margin collapse
marginTop: element.css( "marginTop" ),
marginBottom: element.css( "marginBottom" ),
marginLeft: element.css( "marginLeft" ),
marginRight: element.css( "marginRight" ),
"float": element.css( "float" )
} )
.outerWidth( element.outerWidth() )
.outerHeight( element.outerHeight() )
.addClass( "ui-effects-placeholder" );
element.data( dataSpace + "placeholder", placeholder );
}
element.css( {
position: cssPosition,
left: position.left,
top: position.top
} );
return placeholder;
} | [
"function",
"(",
"element",
")",
"{",
"var",
"placeholder",
",",
"cssPosition",
"=",
"element",
".",
"css",
"(",
"\"position\"",
")",
",",
"position",
"=",
"element",
".",
"position",
"(",
")",
";",
"element",
".",
"css",
"(",
"{",
"marginTop",
":",
"element",
".",
"css",
"(",
"\"marginTop\"",
")",
",",
"marginBottom",
":",
"element",
".",
"css",
"(",
"\"marginBottom\"",
")",
",",
"marginLeft",
":",
"element",
".",
"css",
"(",
"\"marginLeft\"",
")",
",",
"marginRight",
":",
"element",
".",
"css",
"(",
"\"marginRight\"",
")",
"}",
")",
".",
"outerWidth",
"(",
"element",
".",
"outerWidth",
"(",
")",
")",
".",
"outerHeight",
"(",
"element",
".",
"outerHeight",
"(",
")",
")",
";",
"if",
"(",
"/",
"^(static|relative)",
"/",
".",
"test",
"(",
"cssPosition",
")",
")",
"{",
"cssPosition",
"=",
"\"absolute\"",
";",
"placeholder",
"=",
"$",
"(",
"\"<\"",
"+",
"element",
"[",
"0",
"]",
".",
"nodeName",
"+",
"\">\"",
")",
".",
"insertAfter",
"(",
"element",
")",
".",
"css",
"(",
"{",
"display",
":",
"/",
"^(inline|ruby)",
"/",
".",
"test",
"(",
"element",
".",
"css",
"(",
"\"display\"",
")",
")",
"?",
"\"inline-block\"",
":",
"\"block\"",
",",
"visibility",
":",
"\"hidden\"",
",",
"marginTop",
":",
"element",
".",
"css",
"(",
"\"marginTop\"",
")",
",",
"marginBottom",
":",
"element",
".",
"css",
"(",
"\"marginBottom\"",
")",
",",
"marginLeft",
":",
"element",
".",
"css",
"(",
"\"marginLeft\"",
")",
",",
"marginRight",
":",
"element",
".",
"css",
"(",
"\"marginRight\"",
")",
",",
"\"float\"",
":",
"element",
".",
"css",
"(",
"\"float\"",
")",
"}",
")",
".",
"outerWidth",
"(",
"element",
".",
"outerWidth",
"(",
")",
")",
".",
"outerHeight",
"(",
"element",
".",
"outerHeight",
"(",
")",
")",
".",
"addClass",
"(",
"\"ui-effects-placeholder\"",
")",
";",
"element",
".",
"data",
"(",
"dataSpace",
"+",
"\"placeholder\"",
",",
"placeholder",
")",
";",
"}",
"element",
".",
"css",
"(",
"{",
"position",
":",
"cssPosition",
",",
"left",
":",
"position",
".",
"left",
",",
"top",
":",
"position",
".",
"top",
"}",
")",
";",
"return",
"placeholder",
";",
"}"
] | Creates a placeholder element so that the original element can be made absolute | [
"Creates",
"a",
"placeholder",
"element",
"so",
"that",
"the",
"original",
"element",
"can",
"be",
"made",
"absolute"
] | 28eae564c6a8cdaf01d32ff5a1dffba58232f9c1 | https://github.com/nattreid/cms/blob/28eae564c6a8cdaf01d32ff5a1dffba58232f9c1/assets/js/cms.bundled.js#L13074-L13125 | train |
|
macalinao/preston | lib/preston.js | RestAPI | function RestAPI() {
this.models = {};
this.router = express.Router();
this.router.use(require('res-error')({
log: false
}));
} | javascript | function RestAPI() {
this.models = {};
this.router = express.Router();
this.router.use(require('res-error')({
log: false
}));
} | [
"function",
"RestAPI",
"(",
")",
"{",
"this",
".",
"models",
"=",
"{",
"}",
";",
"this",
".",
"router",
"=",
"express",
".",
"Router",
"(",
")",
";",
"this",
".",
"router",
".",
"use",
"(",
"require",
"(",
"'res-error'",
")",
"(",
"{",
"log",
":",
"false",
"}",
")",
")",
";",
"}"
] | Represents a RESTful API powered by Restifier.
@class | [
"Represents",
"a",
"RESTful",
"API",
"powered",
"by",
"Restifier",
"."
] | 87105425b2c30ce773be196c3f85872375099113 | https://github.com/macalinao/preston/blob/87105425b2c30ce773be196c3f85872375099113/lib/preston.js#L13-L19 | train |
strues/boldr | project/server/middleware/rbac.js | hasRole | function hasRole(user = null, role = null) {
return user && role && user.hasRole(role);
} | javascript | function hasRole(user = null, role = null) {
return user && role && user.hasRole(role);
} | [
"function",
"hasRole",
"(",
"user",
"=",
"null",
",",
"role",
"=",
"null",
")",
"{",
"return",
"user",
"&&",
"role",
"&&",
"user",
".",
"hasRole",
"(",
"role",
")",
";",
"}"
] | This checks to see if the user has the given role.
@param {object} user the user object
@param {string} role the role
@returns {boolean} whether or not the user has the role | [
"This",
"checks",
"to",
"see",
"if",
"the",
"user",
"has",
"the",
"given",
"role",
"."
] | 21f1ed9a5ed754e01c50827249e89087b788e660 | https://github.com/strues/boldr/blob/21f1ed9a5ed754e01c50827249e89087b788e660/project/server/middleware/rbac.js#L50-L52 | train |
mathiasvr/querystring | querystring.js | decodeStr | function decodeStr(s, decoder) {
try {
return decoder(s);
} catch (e) {
return QueryString.unescape(s, true);
}
} | javascript | function decodeStr(s, decoder) {
try {
return decoder(s);
} catch (e) {
return QueryString.unescape(s, true);
}
} | [
"function",
"decodeStr",
"(",
"s",
",",
"decoder",
")",
"{",
"try",
"{",
"return",
"decoder",
"(",
"s",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"QueryString",
".",
"unescape",
"(",
"s",
",",
"true",
")",
";",
"}",
"}"
] | v8 does not optimize functions with try-catch blocks, so we isolate them here to minimize the damage | [
"v8",
"does",
"not",
"optimize",
"functions",
"with",
"try",
"-",
"catch",
"blocks",
"so",
"we",
"isolate",
"them",
"here",
"to",
"minimize",
"the",
"damage"
] | d283ad9ae6a0b50b7c0bb69aaa0a4b5a887c1a4d | https://github.com/mathiasvr/querystring/blob/d283ad9ae6a0b50b7c0bb69aaa0a4b5a887c1a4d/querystring.js#L396-L402 | train |
kellym/smartquotes.js | lib/index.js | smartquotes | function smartquotes(context) {
if (typeof document !== 'undefined' && typeof context === 'undefined') {
listen.runOnReady(() => element(document.body));
return smartquotes;
} else if (typeof context === 'string') {
return string(context);
} else {
return element(context);
}
} | javascript | function smartquotes(context) {
if (typeof document !== 'undefined' && typeof context === 'undefined') {
listen.runOnReady(() => element(document.body));
return smartquotes;
} else if (typeof context === 'string') {
return string(context);
} else {
return element(context);
}
} | [
"function",
"smartquotes",
"(",
"context",
")",
"{",
"if",
"(",
"typeof",
"document",
"!==",
"'undefined'",
"&&",
"typeof",
"context",
"===",
"'undefined'",
")",
"{",
"listen",
".",
"runOnReady",
"(",
"(",
")",
"=>",
"element",
"(",
"document",
".",
"body",
")",
")",
";",
"return",
"smartquotes",
";",
"}",
"else",
"if",
"(",
"typeof",
"context",
"===",
"'string'",
")",
"{",
"return",
"string",
"(",
"context",
")",
";",
"}",
"else",
"{",
"return",
"element",
"(",
"context",
")",
";",
"}",
"}"
] | The smartquotes function should just delegate to the other functions | [
"The",
"smartquotes",
"function",
"should",
"just",
"delegate",
"to",
"the",
"other",
"functions"
] | 730d00cfe69955f818d1df432e0f18006a31f3d0 | https://github.com/kellym/smartquotes.js/blob/730d00cfe69955f818d1df432e0f18006a31f3d0/lib/index.js#L8-L17 | train |
JamesMessinger/json-schema-lib | lib/util/omit.js | omit | function omit (obj, props) {
props = Array.prototype.slice.call(arguments, 1);
var keys = Object.keys(obj);
var newObj = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (props.indexOf(key) === -1) {
newObj[key] = obj[key];
}
}
return newObj;
} | javascript | function omit (obj, props) {
props = Array.prototype.slice.call(arguments, 1);
var keys = Object.keys(obj);
var newObj = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (props.indexOf(key) === -1) {
newObj[key] = obj[key];
}
}
return newObj;
} | [
"function",
"omit",
"(",
"obj",
",",
"props",
")",
"{",
"props",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
";",
"var",
"newObj",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"if",
"(",
"props",
".",
"indexOf",
"(",
"key",
")",
"===",
"-",
"1",
")",
"{",
"newObj",
"[",
"key",
"]",
"=",
"obj",
"[",
"key",
"]",
";",
"}",
"}",
"return",
"newObj",
";",
"}"
] | Returns an object containing all properties of the given object,
except for the specified properties to be omitted.
@param {object} obj
@param {...string} props
@returns {object} | [
"Returns",
"an",
"object",
"containing",
"all",
"properties",
"of",
"the",
"given",
"object",
"except",
"for",
"the",
"specified",
"properties",
"to",
"be",
"omitted",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/util/omit.js#L13-L27 | train |
matteodelabre/midijs | lib/connect/output.js | Output | function Output(native) {
this.native = native;
this.id = native.id;
this.manufacturer = native.manufacturer;
this.name = native.name;
this.version = native.version;
} | javascript | function Output(native) {
this.native = native;
this.id = native.id;
this.manufacturer = native.manufacturer;
this.name = native.name;
this.version = native.version;
} | [
"function",
"Output",
"(",
"native",
")",
"{",
"this",
".",
"native",
"=",
"native",
";",
"this",
".",
"id",
"=",
"native",
".",
"id",
";",
"this",
".",
"manufacturer",
"=",
"native",
".",
"manufacturer",
";",
"this",
".",
"name",
"=",
"native",
".",
"name",
";",
"this",
".",
"version",
"=",
"native",
".",
"version",
";",
"}"
] | Construct a new Output
@class Output
@classdesc An output device to which we can send MIDI events
@param {MIDIOutput} native Native MIDI output | [
"Construct",
"a",
"new",
"Output"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/connect/output.js#L15-L22 | train |
JamesMessinger/json-schema-lib | lib/util/typeOf.js | typeOf | function typeOf (value) {
var type = {
hasValue: false,
isArray: false,
isPOJO: false,
isNumber: false,
};
if (value !== undefined && value !== null) {
type.hasValue = true;
var typeName = typeof value;
if (typeName === 'number') {
type.isNumber = !isNaN(value);
}
else if (Array.isArray(value)) {
type.isArray = true;
}
else {
type.isPOJO =
(typeName === 'object') &&
!(value instanceof RegExp) &&
!(value instanceof Date);
}
}
return type;
} | javascript | function typeOf (value) {
var type = {
hasValue: false,
isArray: false,
isPOJO: false,
isNumber: false,
};
if (value !== undefined && value !== null) {
type.hasValue = true;
var typeName = typeof value;
if (typeName === 'number') {
type.isNumber = !isNaN(value);
}
else if (Array.isArray(value)) {
type.isArray = true;
}
else {
type.isPOJO =
(typeName === 'object') &&
!(value instanceof RegExp) &&
!(value instanceof Date);
}
}
return type;
} | [
"function",
"typeOf",
"(",
"value",
")",
"{",
"var",
"type",
"=",
"{",
"hasValue",
":",
"false",
",",
"isArray",
":",
"false",
",",
"isPOJO",
":",
"false",
",",
"isNumber",
":",
"false",
",",
"}",
";",
"if",
"(",
"value",
"!==",
"undefined",
"&&",
"value",
"!==",
"null",
")",
"{",
"type",
".",
"hasValue",
"=",
"true",
";",
"var",
"typeName",
"=",
"typeof",
"value",
";",
"if",
"(",
"typeName",
"===",
"'number'",
")",
"{",
"type",
".",
"isNumber",
"=",
"!",
"isNaN",
"(",
"value",
")",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"type",
".",
"isArray",
"=",
"true",
";",
"}",
"else",
"{",
"type",
".",
"isPOJO",
"=",
"(",
"typeName",
"===",
"'object'",
")",
"&&",
"!",
"(",
"value",
"instanceof",
"RegExp",
")",
"&&",
"!",
"(",
"value",
"instanceof",
"Date",
")",
";",
"}",
"}",
"return",
"type",
";",
"}"
] | Returns information about the type of the given value
@param {*} value
@returns {{ hasValue: boolean, isArray: boolean, isPOJO: boolean, isNumber: boolean }} | [
"Returns",
"information",
"about",
"the",
"type",
"of",
"the",
"given",
"value"
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/util/typeOf.js#L11-L38 | train |
LivePersonInc/chronosjs | src/courier/PostMessageCourier.js | _registerProxy | function _registerProxy(eventChannel) {
if (eventChannel && "function" === typeof eventChannel.registerProxy) {
eventChannel.registerProxy({
trigger: function () {
_postMessage.call(this, Array.prototype.slice.apply(arguments), ACTION_TYPE.TRIGGER);
},
context: this
});
}
} | javascript | function _registerProxy(eventChannel) {
if (eventChannel && "function" === typeof eventChannel.registerProxy) {
eventChannel.registerProxy({
trigger: function () {
_postMessage.call(this, Array.prototype.slice.apply(arguments), ACTION_TYPE.TRIGGER);
},
context: this
});
}
} | [
"function",
"_registerProxy",
"(",
"eventChannel",
")",
"{",
"if",
"(",
"eventChannel",
"&&",
"\"function\"",
"===",
"typeof",
"eventChannel",
".",
"registerProxy",
")",
"{",
"eventChannel",
".",
"registerProxy",
"(",
"{",
"trigger",
":",
"function",
"(",
")",
"{",
"_postMessage",
".",
"call",
"(",
"this",
",",
"Array",
".",
"prototype",
".",
"slice",
".",
"apply",
"(",
"arguments",
")",
",",
"ACTION_TYPE",
".",
"TRIGGER",
")",
";",
"}",
",",
"context",
":",
"this",
"}",
")",
";",
"}",
"}"
] | Registers an external call to trigger for events to propagate calls to Channels.trigger automatically
@param eventChannel
@private | [
"Registers",
"an",
"external",
"call",
"to",
"trigger",
"for",
"events",
"to",
"propagate",
"calls",
"to",
"Channels",
".",
"trigger",
"automatically"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L201-L210 | train |
LivePersonInc/chronosjs | src/courier/PostMessageCourier.js | _initializeSerialization | function _initializeSerialization(options) {
this.useObjects = false === options.useObjects ? options.useObjects : _getUseObjectsUrlIndicator();
if ("undefined" === typeof this.useObjects) {
// Defaults to true
this.useObjects = true;
}
options.useObjects = this.useObjects;
// Define the serialize/deserialize methods to be used
if ("function" !== typeof options.serialize || "function" !== typeof options.deserialize) {
if (this.useObjects && PostMessageUtilities.hasPostMessageObjectsSupport()) {
this.serialize = _de$serializeDummy;
this.deserialize = _de$serializeDummy;
}
else {
this.serialize = PostMessageUtilities.stringify;
this.deserialize = JSON.parse;
}
options.serialize = this.serialize;
options.deserialize = this.deserialize;
}
else {
this.serialize = options.serialize;
this.deserialize = options.deserialize;
}
} | javascript | function _initializeSerialization(options) {
this.useObjects = false === options.useObjects ? options.useObjects : _getUseObjectsUrlIndicator();
if ("undefined" === typeof this.useObjects) {
// Defaults to true
this.useObjects = true;
}
options.useObjects = this.useObjects;
// Define the serialize/deserialize methods to be used
if ("function" !== typeof options.serialize || "function" !== typeof options.deserialize) {
if (this.useObjects && PostMessageUtilities.hasPostMessageObjectsSupport()) {
this.serialize = _de$serializeDummy;
this.deserialize = _de$serializeDummy;
}
else {
this.serialize = PostMessageUtilities.stringify;
this.deserialize = JSON.parse;
}
options.serialize = this.serialize;
options.deserialize = this.deserialize;
}
else {
this.serialize = options.serialize;
this.deserialize = options.deserialize;
}
} | [
"function",
"_initializeSerialization",
"(",
"options",
")",
"{",
"this",
".",
"useObjects",
"=",
"false",
"===",
"options",
".",
"useObjects",
"?",
"options",
".",
"useObjects",
":",
"_getUseObjectsUrlIndicator",
"(",
")",
";",
"if",
"(",
"\"undefined\"",
"===",
"typeof",
"this",
".",
"useObjects",
")",
"{",
"this",
".",
"useObjects",
"=",
"true",
";",
"}",
"options",
".",
"useObjects",
"=",
"this",
".",
"useObjects",
";",
"if",
"(",
"\"function\"",
"!==",
"typeof",
"options",
".",
"serialize",
"||",
"\"function\"",
"!==",
"typeof",
"options",
".",
"deserialize",
")",
"{",
"if",
"(",
"this",
".",
"useObjects",
"&&",
"PostMessageUtilities",
".",
"hasPostMessageObjectsSupport",
"(",
")",
")",
"{",
"this",
".",
"serialize",
"=",
"_de$serializeDummy",
";",
"this",
".",
"deserialize",
"=",
"_de$serializeDummy",
";",
"}",
"else",
"{",
"this",
".",
"serialize",
"=",
"PostMessageUtilities",
".",
"stringify",
";",
"this",
".",
"deserialize",
"=",
"JSON",
".",
"parse",
";",
"}",
"options",
".",
"serialize",
"=",
"this",
".",
"serialize",
";",
"options",
".",
"deserialize",
"=",
"this",
".",
"deserialize",
";",
"}",
"else",
"{",
"this",
".",
"serialize",
"=",
"options",
".",
"serialize",
";",
"this",
".",
"deserialize",
"=",
"options",
".",
"deserialize",
";",
"}",
"}"
] | Method for initializing the options for serialization of messages
@param {Boolean} [options.useObjects = true upon browser support] - optional indication for passing objects by reference
@param {Function} [options.serialize = JSON.stringify] - optional serialization method for post message
@param {Function} [options.deserialize = JSON.parse] - optional deserialization method for post message
@private | [
"Method",
"for",
"initializing",
"the",
"options",
"for",
"serialization",
"of",
"messages"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L346-L372 | train |
LivePersonInc/chronosjs | src/courier/PostMessageCourier.js | _initializeCommunication | function _initializeCommunication(options) {
var mapping;
var onmessage;
// Grab the event channel and initialize a new mapper
this.eventChannel = options.eventChannel || new Channels({
events: options.events,
commands: options.commands,
reqres: options.reqres
});
this.mapper = new PostMessageMapper(this.eventChannel);
// Bind the mapping method to the mapper
mapping = this.mapper.toEvent.bind(this.mapper);
// Create the message handler which uses the mapping method
onmessage = _createMessageHandler(mapping).bind(this);
// Initialize a message channel with the message handler
this.messageChannel = new PostMessageChannel(options, onmessage);
} | javascript | function _initializeCommunication(options) {
var mapping;
var onmessage;
// Grab the event channel and initialize a new mapper
this.eventChannel = options.eventChannel || new Channels({
events: options.events,
commands: options.commands,
reqres: options.reqres
});
this.mapper = new PostMessageMapper(this.eventChannel);
// Bind the mapping method to the mapper
mapping = this.mapper.toEvent.bind(this.mapper);
// Create the message handler which uses the mapping method
onmessage = _createMessageHandler(mapping).bind(this);
// Initialize a message channel with the message handler
this.messageChannel = new PostMessageChannel(options, onmessage);
} | [
"function",
"_initializeCommunication",
"(",
"options",
")",
"{",
"var",
"mapping",
";",
"var",
"onmessage",
";",
"this",
".",
"eventChannel",
"=",
"options",
".",
"eventChannel",
"||",
"new",
"Channels",
"(",
"{",
"events",
":",
"options",
".",
"events",
",",
"commands",
":",
"options",
".",
"commands",
",",
"reqres",
":",
"options",
".",
"reqres",
"}",
")",
";",
"this",
".",
"mapper",
"=",
"new",
"PostMessageMapper",
"(",
"this",
".",
"eventChannel",
")",
";",
"mapping",
"=",
"this",
".",
"mapper",
".",
"toEvent",
".",
"bind",
"(",
"this",
".",
"mapper",
")",
";",
"onmessage",
"=",
"_createMessageHandler",
"(",
"mapping",
")",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"messageChannel",
"=",
"new",
"PostMessageChannel",
"(",
"options",
",",
"onmessage",
")",
";",
"}"
] | Method for initializing the communication elements
@param {Object} [options.eventChannel] - optional events channel to be used (if not supplied, a new one will be created OR optional events, optional commands, optional reqres to be used
@private | [
"Method",
"for",
"initializing",
"the",
"communication",
"elements"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L379-L398 | train |
LivePersonInc/chronosjs | src/courier/PostMessageCourier.js | _initializeCache | function _initializeCache(options) {
this.callbackCache = new Cacher({
max: PostMessageUtilities.parseNumber(options.maxConcurrency, DEFAULT_CONCURRENCY),
ttl: PostMessageUtilities.parseNumber(options.timeout, DEFAULT_TIMEOUT),
interval: CACHE_EVICTION_INTERVAL
});
} | javascript | function _initializeCache(options) {
this.callbackCache = new Cacher({
max: PostMessageUtilities.parseNumber(options.maxConcurrency, DEFAULT_CONCURRENCY),
ttl: PostMessageUtilities.parseNumber(options.timeout, DEFAULT_TIMEOUT),
interval: CACHE_EVICTION_INTERVAL
});
} | [
"function",
"_initializeCache",
"(",
"options",
")",
"{",
"this",
".",
"callbackCache",
"=",
"new",
"Cacher",
"(",
"{",
"max",
":",
"PostMessageUtilities",
".",
"parseNumber",
"(",
"options",
".",
"maxConcurrency",
",",
"DEFAULT_CONCURRENCY",
")",
",",
"ttl",
":",
"PostMessageUtilities",
".",
"parseNumber",
"(",
"options",
".",
"timeout",
",",
"DEFAULT_TIMEOUT",
")",
",",
"interval",
":",
"CACHE_EVICTION_INTERVAL",
"}",
")",
";",
"}"
] | Method for initializing the cache for responses
@param {Number} [options.maxConcurrency = 100] - optional maximum concurrency that can be managed by the component before dropping
@param {Number} [options.timeout = 30000] - optional milliseconds parameter for waiting before timeout to responses (default is 30 seconds)
@private | [
"Method",
"for",
"initializing",
"the",
"cache",
"for",
"responses"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L406-L412 | train |
LivePersonInc/chronosjs | src/courier/PostMessageCourier.js | _initializeFailFast | function _initializeFailFast(options) {
var messureTime = PostMessageUtilities.parseNumber(options.messureTime, DEFAULT_MESSURE_TIME);
this.circuit = new CircuitBreaker({
timeWindow: messureTime,
slidesNumber: Math.ceil(messureTime / 100),
tolerance: PostMessageUtilities.parseNumber(options.messureTolerance, DEFAULT_MESSURE_TOLERANCE),
calibration: PostMessageUtilities.parseNumber(options.messureCalibration, DEFAULT_MESSURE_CALIBRATION),
onopen: PostMessageUtilities.parseFunction(options.ondisconnect, true),
onclose: PostMessageUtilities.parseFunction(options.onreconnect, true)
});
} | javascript | function _initializeFailFast(options) {
var messureTime = PostMessageUtilities.parseNumber(options.messureTime, DEFAULT_MESSURE_TIME);
this.circuit = new CircuitBreaker({
timeWindow: messureTime,
slidesNumber: Math.ceil(messureTime / 100),
tolerance: PostMessageUtilities.parseNumber(options.messureTolerance, DEFAULT_MESSURE_TOLERANCE),
calibration: PostMessageUtilities.parseNumber(options.messureCalibration, DEFAULT_MESSURE_CALIBRATION),
onopen: PostMessageUtilities.parseFunction(options.ondisconnect, true),
onclose: PostMessageUtilities.parseFunction(options.onreconnect, true)
});
} | [
"function",
"_initializeFailFast",
"(",
"options",
")",
"{",
"var",
"messureTime",
"=",
"PostMessageUtilities",
".",
"parseNumber",
"(",
"options",
".",
"messureTime",
",",
"DEFAULT_MESSURE_TIME",
")",
";",
"this",
".",
"circuit",
"=",
"new",
"CircuitBreaker",
"(",
"{",
"timeWindow",
":",
"messureTime",
",",
"slidesNumber",
":",
"Math",
".",
"ceil",
"(",
"messureTime",
"/",
"100",
")",
",",
"tolerance",
":",
"PostMessageUtilities",
".",
"parseNumber",
"(",
"options",
".",
"messureTolerance",
",",
"DEFAULT_MESSURE_TOLERANCE",
")",
",",
"calibration",
":",
"PostMessageUtilities",
".",
"parseNumber",
"(",
"options",
".",
"messureCalibration",
",",
"DEFAULT_MESSURE_CALIBRATION",
")",
",",
"onopen",
":",
"PostMessageUtilities",
".",
"parseFunction",
"(",
"options",
".",
"ondisconnect",
",",
"true",
")",
",",
"onclose",
":",
"PostMessageUtilities",
".",
"parseFunction",
"(",
"options",
".",
"onreconnect",
",",
"true",
")",
"}",
")",
";",
"}"
] | Method for initializing the fail fast mechanisms
@param {Number} [options.messureTime = 30000] - optional milliseconds parameter for time measurement indicating the time window to apply when implementing the internal fail fast mechanism (default is 30 seconds)
@param {Number} [options.messureTolerance = 30] - optional percentage parameter indicating the tolerance to apply on the measurements when implementing the internal fail fast mechanism (default is 30 percents)
@param {Number} [options.messureCalibration = 10] optional numeric parameter indicating the calibration of minimum calls before starting to validate measurements when implementing the internal fail fast mechanism (default is 10 calls)
@param {Function} [options.ondisconnect] - optional disconnect handler that will be invoked when the fail fast mechanism disconnects the component upon to many failures
@param {Function} [options.onreconnect] - optional reconnect handler that will be invoked when the fail fast mechanism reconnects the component upon back to normal behaviour
@private | [
"Method",
"for",
"initializing",
"the",
"fail",
"fast",
"mechanisms"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L423-L433 | train |
LivePersonInc/chronosjs | src/courier/PostMessageCourier.js | _postMessage | function _postMessage(args, name) {
return this.circuit.run(function (success, failure, timeout) {
var message = _prepare.call(this, args, name, timeout);
if (message) {
try {
var initiated = this.messageChannel.postMessage.call(this.messageChannel, message);
if (false === initiated) {
failure();
}
else {
success();
}
}
catch (ex) {
failure();
}
}
else {
// Cache is full, as a fail fast mechanism, we should not continue
failure();
}
}.bind(this));
} | javascript | function _postMessage(args, name) {
return this.circuit.run(function (success, failure, timeout) {
var message = _prepare.call(this, args, name, timeout);
if (message) {
try {
var initiated = this.messageChannel.postMessage.call(this.messageChannel, message);
if (false === initiated) {
failure();
}
else {
success();
}
}
catch (ex) {
failure();
}
}
else {
// Cache is full, as a fail fast mechanism, we should not continue
failure();
}
}.bind(this));
} | [
"function",
"_postMessage",
"(",
"args",
",",
"name",
")",
"{",
"return",
"this",
".",
"circuit",
".",
"run",
"(",
"function",
"(",
"success",
",",
"failure",
",",
"timeout",
")",
"{",
"var",
"message",
"=",
"_prepare",
".",
"call",
"(",
"this",
",",
"args",
",",
"name",
",",
"timeout",
")",
";",
"if",
"(",
"message",
")",
"{",
"try",
"{",
"var",
"initiated",
"=",
"this",
".",
"messageChannel",
".",
"postMessage",
".",
"call",
"(",
"this",
".",
"messageChannel",
",",
"message",
")",
";",
"if",
"(",
"false",
"===",
"initiated",
")",
"{",
"failure",
"(",
")",
";",
"}",
"else",
"{",
"success",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"ex",
")",
"{",
"failure",
"(",
")",
";",
"}",
"}",
"else",
"{",
"failure",
"(",
")",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | Method for posting the message via the circuit breaker
@param {Array} args - the arguments for the message to be processed.
@param {String} name - name of type of command.
@private | [
"Method",
"for",
"posting",
"the",
"message",
"via",
"the",
"circuit",
"breaker"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L463-L487 | train |
LivePersonInc/chronosjs | src/courier/PostMessageCourier.js | _returnMessage | function _returnMessage(message, target) {
return this.circuit.run(function (success, failure) {
try {
var initiated = this.messageChannel.postMessage.call(this.messageChannel, message, target);
if (false === initiated) {
failure();
}
else {
success();
}
}
catch (ex) {
failure();
}
}.bind(this));
} | javascript | function _returnMessage(message, target) {
return this.circuit.run(function (success, failure) {
try {
var initiated = this.messageChannel.postMessage.call(this.messageChannel, message, target);
if (false === initiated) {
failure();
}
else {
success();
}
}
catch (ex) {
failure();
}
}.bind(this));
} | [
"function",
"_returnMessage",
"(",
"message",
",",
"target",
")",
"{",
"return",
"this",
".",
"circuit",
".",
"run",
"(",
"function",
"(",
"success",
",",
"failure",
")",
"{",
"try",
"{",
"var",
"initiated",
"=",
"this",
".",
"messageChannel",
".",
"postMessage",
".",
"call",
"(",
"this",
".",
"messageChannel",
",",
"message",
",",
"target",
")",
";",
"if",
"(",
"false",
"===",
"initiated",
")",
"{",
"failure",
"(",
")",
";",
"}",
"else",
"{",
"success",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"ex",
")",
"{",
"failure",
"(",
")",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | Method for posting the returned message via the circuit breaker
@param {Object} message - the message to post.
@param {bject} [target] - optional target for post.
@private | [
"Method",
"for",
"posting",
"the",
"returned",
"message",
"via",
"the",
"circuit",
"breaker"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L495-L511 | train |
LivePersonInc/chronosjs | src/courier/PostMessageCourier.js | _prepare | function _prepare(args, name, ontimeout) {
var method;
var ttl;
var id = PostMessageUtilities.createUniqueSequence(MESSAGE_PREFIX + name + PostMessageUtilities.SEQUENCE_FORMAT);
args.unshift(id, name);
if (_isTwoWay(name)) {
if (1 < args.length && "function" === typeof args[args.length - 1]) {
method = args.pop();
}
else if (2 < args.length && !isNaN(args[args.length - 1]) && "function" === typeof args[args.length - 2]) {
ttl = parseInt(args.pop(), 10);
method = args.pop();
}
if (method) {
if (!this.callbackCache.set(id, method, ttl, function (id, callback) {
ontimeout();
_handleTimeout.call(this, id, callback);
}.bind(this))) {
// Cache is full, as a fail fast mechanism, we will not continue
return void 0;
}
}
}
return this.mapper.toMessage.apply(this.mapper, args);
} | javascript | function _prepare(args, name, ontimeout) {
var method;
var ttl;
var id = PostMessageUtilities.createUniqueSequence(MESSAGE_PREFIX + name + PostMessageUtilities.SEQUENCE_FORMAT);
args.unshift(id, name);
if (_isTwoWay(name)) {
if (1 < args.length && "function" === typeof args[args.length - 1]) {
method = args.pop();
}
else if (2 < args.length && !isNaN(args[args.length - 1]) && "function" === typeof args[args.length - 2]) {
ttl = parseInt(args.pop(), 10);
method = args.pop();
}
if (method) {
if (!this.callbackCache.set(id, method, ttl, function (id, callback) {
ontimeout();
_handleTimeout.call(this, id, callback);
}.bind(this))) {
// Cache is full, as a fail fast mechanism, we will not continue
return void 0;
}
}
}
return this.mapper.toMessage.apply(this.mapper, args);
} | [
"function",
"_prepare",
"(",
"args",
",",
"name",
",",
"ontimeout",
")",
"{",
"var",
"method",
";",
"var",
"ttl",
";",
"var",
"id",
"=",
"PostMessageUtilities",
".",
"createUniqueSequence",
"(",
"MESSAGE_PREFIX",
"+",
"name",
"+",
"PostMessageUtilities",
".",
"SEQUENCE_FORMAT",
")",
";",
"args",
".",
"unshift",
"(",
"id",
",",
"name",
")",
";",
"if",
"(",
"_isTwoWay",
"(",
"name",
")",
")",
"{",
"if",
"(",
"1",
"<",
"args",
".",
"length",
"&&",
"\"function\"",
"===",
"typeof",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
")",
"{",
"method",
"=",
"args",
".",
"pop",
"(",
")",
";",
"}",
"else",
"if",
"(",
"2",
"<",
"args",
".",
"length",
"&&",
"!",
"isNaN",
"(",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
")",
"&&",
"\"function\"",
"===",
"typeof",
"args",
"[",
"args",
".",
"length",
"-",
"2",
"]",
")",
"{",
"ttl",
"=",
"parseInt",
"(",
"args",
".",
"pop",
"(",
")",
",",
"10",
")",
";",
"method",
"=",
"args",
".",
"pop",
"(",
")",
";",
"}",
"if",
"(",
"method",
")",
"{",
"if",
"(",
"!",
"this",
".",
"callbackCache",
".",
"set",
"(",
"id",
",",
"method",
",",
"ttl",
",",
"function",
"(",
"id",
",",
"callback",
")",
"{",
"ontimeout",
"(",
")",
";",
"_handleTimeout",
".",
"call",
"(",
"this",
",",
"id",
",",
"callback",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
")",
"{",
"return",
"void",
"0",
";",
"}",
"}",
"}",
"return",
"this",
".",
"mapper",
".",
"toMessage",
".",
"apply",
"(",
"this",
".",
"mapper",
",",
"args",
")",
";",
"}"
] | Method for preparing the message to be posted via the postmessage and caching the callback to be called if needed
@param {Array} args - the arguments to pass to the message mapper
@param {String} name - the action type name (trigger, command, request)
@param {Function} [ontimeout] - the ontimeout measurement handler
@returns {Function} handler function for messages
@private | [
"Method",
"for",
"preparing",
"the",
"message",
"to",
"be",
"posted",
"via",
"the",
"postmessage",
"and",
"caching",
"the",
"callback",
"to",
"be",
"called",
"if",
"needed"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L521-L549 | train |
LivePersonInc/chronosjs | src/courier/PostMessageCourier.js | _handleTimeout | function _handleTimeout(id, callback) {
// Handle timeout
if (id && "function" === typeof callback) {
try {
callback.call(null, new Error("Callback: Operation Timeout!"));
}
catch (ex) {
/* istanbul ignore next */
PostMessageUtilities.log("Error while trying to handle the timeout using the callback", "ERROR", "PostMessageCourier");
}
}
} | javascript | function _handleTimeout(id, callback) {
// Handle timeout
if (id && "function" === typeof callback) {
try {
callback.call(null, new Error("Callback: Operation Timeout!"));
}
catch (ex) {
/* istanbul ignore next */
PostMessageUtilities.log("Error while trying to handle the timeout using the callback", "ERROR", "PostMessageCourier");
}
}
} | [
"function",
"_handleTimeout",
"(",
"id",
",",
"callback",
")",
"{",
"if",
"(",
"id",
"&&",
"\"function\"",
"===",
"typeof",
"callback",
")",
"{",
"try",
"{",
"callback",
".",
"call",
"(",
"null",
",",
"new",
"Error",
"(",
"\"Callback: Operation Timeout!\"",
")",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"PostMessageUtilities",
".",
"log",
"(",
"\"Error while trying to handle the timeout using the callback\"",
",",
"\"ERROR\"",
",",
"\"PostMessageCourier\"",
")",
";",
"}",
"}",
"}"
] | Method for handling timeout of a cached callback
@param {String} id - the id of the timed out callback
@param {Function} callback - the callback object from cache
@private | [
"Method",
"for",
"handling",
"timeout",
"of",
"a",
"cached",
"callback"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L567-L578 | train |
LivePersonInc/chronosjs | src/courier/PostMessageCourier.js | _handleReturnMessage | function _handleReturnMessage(id, method) {
var callback = this.callbackCache.get(id, true);
var args = method && method.args;
if ("function" === typeof callback) {
// First try to parse the first parameter in case the error is an object
if (args && args.length && args[0] && "Error" === args[0].type && "string" === typeof args[0].message) {
args[0] = new Error(args[0].message);
}
try {
callback.apply(null, args);
}
catch (ex) {
PostMessageUtilities.log("Error while trying to handle the returned message from request/command", "ERROR", "PostMessageCourier");
}
}
} | javascript | function _handleReturnMessage(id, method) {
var callback = this.callbackCache.get(id, true);
var args = method && method.args;
if ("function" === typeof callback) {
// First try to parse the first parameter in case the error is an object
if (args && args.length && args[0] && "Error" === args[0].type && "string" === typeof args[0].message) {
args[0] = new Error(args[0].message);
}
try {
callback.apply(null, args);
}
catch (ex) {
PostMessageUtilities.log("Error while trying to handle the returned message from request/command", "ERROR", "PostMessageCourier");
}
}
} | [
"function",
"_handleReturnMessage",
"(",
"id",
",",
"method",
")",
"{",
"var",
"callback",
"=",
"this",
".",
"callbackCache",
".",
"get",
"(",
"id",
",",
"true",
")",
";",
"var",
"args",
"=",
"method",
"&&",
"method",
".",
"args",
";",
"if",
"(",
"\"function\"",
"===",
"typeof",
"callback",
")",
"{",
"if",
"(",
"args",
"&&",
"args",
".",
"length",
"&&",
"args",
"[",
"0",
"]",
"&&",
"\"Error\"",
"===",
"args",
"[",
"0",
"]",
".",
"type",
"&&",
"\"string\"",
"===",
"typeof",
"args",
"[",
"0",
"]",
".",
"message",
")",
"{",
"args",
"[",
"0",
"]",
"=",
"new",
"Error",
"(",
"args",
"[",
"0",
"]",
".",
"message",
")",
";",
"}",
"try",
"{",
"callback",
".",
"apply",
"(",
"null",
",",
"args",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"PostMessageUtilities",
".",
"log",
"(",
"\"Error while trying to handle the returned message from request/command\"",
",",
"\"ERROR\"",
",",
"\"PostMessageCourier\"",
")",
";",
"}",
"}",
"}"
] | Method for handling return messages from the callee
@param {String} id - the id of the callback
@param {Object} method - the method object with needed args
@private | [
"Method",
"for",
"handling",
"return",
"messages",
"from",
"the",
"callee"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageCourier.js#L586-L603 | train |
emgeee/gulp-standard | reporters/stylish.js | reportFile | function reportFile (filepath, data) {
var lines = []
// Filename
lines.push(colors.magenta.underline(path.relative(appRoot.path, filepath)))
// Loop file specific error/warning messages
data.results.forEach(function (file) {
file.messages.forEach(function (msg) {
var context = colors.yellow((options.showFilePath ? filepath + ':' : 'line ') + msg.line + ':' + msg.column)
var message = colors.cyan(msg.message + (options.showRuleNames ? ' (' + msg.ruleId + ')' : ''))
lines.push(context + '\t' + message)
})
})
// Error/Warning count
lines.push(logSymbols.error + ' ' + colors.red(data.errorCount + ' error' + (data.errorCount === 1 ? 's' : '')) + '\t' + logSymbols.warning + ' ' + colors.yellow(data.warningCount + ' warning' + (data.errorCount === 1 ? 's' : '')))
return lines.join('\n') + '\n'
} | javascript | function reportFile (filepath, data) {
var lines = []
// Filename
lines.push(colors.magenta.underline(path.relative(appRoot.path, filepath)))
// Loop file specific error/warning messages
data.results.forEach(function (file) {
file.messages.forEach(function (msg) {
var context = colors.yellow((options.showFilePath ? filepath + ':' : 'line ') + msg.line + ':' + msg.column)
var message = colors.cyan(msg.message + (options.showRuleNames ? ' (' + msg.ruleId + ')' : ''))
lines.push(context + '\t' + message)
})
})
// Error/Warning count
lines.push(logSymbols.error + ' ' + colors.red(data.errorCount + ' error' + (data.errorCount === 1 ? 's' : '')) + '\t' + logSymbols.warning + ' ' + colors.yellow(data.warningCount + ' warning' + (data.errorCount === 1 ? 's' : '')))
return lines.join('\n') + '\n'
} | [
"function",
"reportFile",
"(",
"filepath",
",",
"data",
")",
"{",
"var",
"lines",
"=",
"[",
"]",
"lines",
".",
"push",
"(",
"colors",
".",
"magenta",
".",
"underline",
"(",
"path",
".",
"relative",
"(",
"appRoot",
".",
"path",
",",
"filepath",
")",
")",
")",
"data",
".",
"results",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"file",
".",
"messages",
".",
"forEach",
"(",
"function",
"(",
"msg",
")",
"{",
"var",
"context",
"=",
"colors",
".",
"yellow",
"(",
"(",
"options",
".",
"showFilePath",
"?",
"filepath",
"+",
"':'",
":",
"'line '",
")",
"+",
"msg",
".",
"line",
"+",
"':'",
"+",
"msg",
".",
"column",
")",
"var",
"message",
"=",
"colors",
".",
"cyan",
"(",
"msg",
".",
"message",
"+",
"(",
"options",
".",
"showRuleNames",
"?",
"' ('",
"+",
"msg",
".",
"ruleId",
"+",
"')'",
":",
"''",
")",
")",
"lines",
".",
"push",
"(",
"context",
"+",
"'\\t'",
"+",
"\\t",
")",
"}",
")",
"}",
")",
"message",
"lines",
".",
"push",
"(",
"logSymbols",
".",
"error",
"+",
"' '",
"+",
"colors",
".",
"red",
"(",
"data",
".",
"errorCount",
"+",
"' error'",
"+",
"(",
"data",
".",
"errorCount",
"===",
"1",
"?",
"'s'",
":",
"''",
")",
")",
"+",
"'\\t'",
"+",
"\\t",
"+",
"logSymbols",
".",
"warning",
"+",
"' '",
")",
"}"
] | File specific reporter | [
"File",
"specific",
"reporter"
] | 6c9c7c0c1adf26424f39ca8f591cd3ab310a7615 | https://github.com/emgeee/gulp-standard/blob/6c9c7c0c1adf26424f39ca8f591cd3ab310a7615/reporters/stylish.js#L17-L36 | train |
JamesMessinger/json-schema-lib | lib/plugins/XMLHttpRequestPlugin.js | readFileSync | function readFileSync (args) {
var file = args.file;
var config = args.config;
var error, response;
safeCall(sendRequest, false, file.url, config, function handleResponse (err, res) {
error = err;
response = res;
});
if (error) {
throw error;
}
else {
setHttpMetadata(file, response);
return response.data;
}
} | javascript | function readFileSync (args) {
var file = args.file;
var config = args.config;
var error, response;
safeCall(sendRequest, false, file.url, config, function handleResponse (err, res) {
error = err;
response = res;
});
if (error) {
throw error;
}
else {
setHttpMetadata(file, response);
return response.data;
}
} | [
"function",
"readFileSync",
"(",
"args",
")",
"{",
"var",
"file",
"=",
"args",
".",
"file",
";",
"var",
"config",
"=",
"args",
".",
"config",
";",
"var",
"error",
",",
"response",
";",
"safeCall",
"(",
"sendRequest",
",",
"false",
",",
"file",
".",
"url",
",",
"config",
",",
"function",
"handleResponse",
"(",
"err",
",",
"res",
")",
"{",
"error",
"=",
"err",
";",
"response",
"=",
"res",
";",
"}",
")",
";",
"if",
"(",
"error",
")",
"{",
"throw",
"error",
";",
"}",
"else",
"{",
"setHttpMetadata",
"(",
"file",
",",
"response",
")",
";",
"return",
"response",
".",
"data",
";",
"}",
"}"
] | Synchronously downlaods a file.
@param {File} args.file - The {@link File} to read
@param {function} args.next - Calls the next plugin, if the file is not a local filesystem file | [
"Synchronously",
"downlaods",
"a",
"file",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/XMLHttpRequestPlugin.js#L25-L42 | train |
JamesMessinger/json-schema-lib | lib/plugins/XMLHttpRequestPlugin.js | readFileAsync | function readFileAsync (args) {
var file = args.file;
var config = args.config;
var next = args.next;
safeCall(sendRequest, false, file.url, config, function handleResponse (err, res) {
if (err) {
next(err);
}
else {
setHttpMetadata(file, res);
next(null, res.data);
}
});
} | javascript | function readFileAsync (args) {
var file = args.file;
var config = args.config;
var next = args.next;
safeCall(sendRequest, false, file.url, config, function handleResponse (err, res) {
if (err) {
next(err);
}
else {
setHttpMetadata(file, res);
next(null, res.data);
}
});
} | [
"function",
"readFileAsync",
"(",
"args",
")",
"{",
"var",
"file",
"=",
"args",
".",
"file",
";",
"var",
"config",
"=",
"args",
".",
"config",
";",
"var",
"next",
"=",
"args",
".",
"next",
";",
"safeCall",
"(",
"sendRequest",
",",
"false",
",",
"file",
".",
"url",
",",
"config",
",",
"function",
"handleResponse",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"{",
"next",
"(",
"err",
")",
";",
"}",
"else",
"{",
"setHttpMetadata",
"(",
"file",
",",
"res",
")",
";",
"next",
"(",
"null",
",",
"res",
".",
"data",
")",
";",
"}",
"}",
")",
";",
"}"
] | Asynchronously downlaods a file.
@param {File} args.file - The {@link File} to read
@param {function} args.next - Calls the next plugin, if the file is not a local filesystem file | [
"Asynchronously",
"downlaods",
"a",
"file",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/XMLHttpRequestPlugin.js#L50-L64 | train |
JamesMessinger/json-schema-lib | lib/plugins/XMLHttpRequestPlugin.js | sendRequest | function sendRequest (async, url, config, callback) {
var req = new XMLHttpRequest();
req.open('GET', url, async);
req.onerror = handleError;
req.ontimeout = handleError;
req.onload = handleResponse;
setXHRConfig(req, config);
req.send();
function handleResponse () {
var res = {
status: getResponseStatus(req.status, url),
headers: parseResponseHeaders(req.getAllResponseHeaders()),
data: req.response || req.responseText,
};
if (res.status >= 200 && res.status < 300) {
callback(null, res);
}
else if (res.status < 200 || res.status < 400) {
callback(ono('Invalid/unsupported HTTP %d response', res.status));
}
else {
callback(ono('HTTP %d error occurred (%s)', res.status, req.statusText));
}
}
function handleError (err) {
callback(err);
}
} | javascript | function sendRequest (async, url, config, callback) {
var req = new XMLHttpRequest();
req.open('GET', url, async);
req.onerror = handleError;
req.ontimeout = handleError;
req.onload = handleResponse;
setXHRConfig(req, config);
req.send();
function handleResponse () {
var res = {
status: getResponseStatus(req.status, url),
headers: parseResponseHeaders(req.getAllResponseHeaders()),
data: req.response || req.responseText,
};
if (res.status >= 200 && res.status < 300) {
callback(null, res);
}
else if (res.status < 200 || res.status < 400) {
callback(ono('Invalid/unsupported HTTP %d response', res.status));
}
else {
callback(ono('HTTP %d error occurred (%s)', res.status, req.statusText));
}
}
function handleError (err) {
callback(err);
}
} | [
"function",
"sendRequest",
"(",
"async",
",",
"url",
",",
"config",
",",
"callback",
")",
"{",
"var",
"req",
"=",
"new",
"XMLHttpRequest",
"(",
")",
";",
"req",
".",
"open",
"(",
"'GET'",
",",
"url",
",",
"async",
")",
";",
"req",
".",
"onerror",
"=",
"handleError",
";",
"req",
".",
"ontimeout",
"=",
"handleError",
";",
"req",
".",
"onload",
"=",
"handleResponse",
";",
"setXHRConfig",
"(",
"req",
",",
"config",
")",
";",
"req",
".",
"send",
"(",
")",
";",
"function",
"handleResponse",
"(",
")",
"{",
"var",
"res",
"=",
"{",
"status",
":",
"getResponseStatus",
"(",
"req",
".",
"status",
",",
"url",
")",
",",
"headers",
":",
"parseResponseHeaders",
"(",
"req",
".",
"getAllResponseHeaders",
"(",
")",
")",
",",
"data",
":",
"req",
".",
"response",
"||",
"req",
".",
"responseText",
",",
"}",
";",
"if",
"(",
"res",
".",
"status",
">=",
"200",
"&&",
"res",
".",
"status",
"<",
"300",
")",
"{",
"callback",
"(",
"null",
",",
"res",
")",
";",
"}",
"else",
"if",
"(",
"res",
".",
"status",
"<",
"200",
"||",
"res",
".",
"status",
"<",
"400",
")",
"{",
"callback",
"(",
"ono",
"(",
"'Invalid/unsupported HTTP %d response'",
",",
"res",
".",
"status",
")",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"ono",
"(",
"'HTTP %d error occurred (%s)'",
",",
"res",
".",
"status",
",",
"req",
".",
"statusText",
")",
")",
";",
"}",
"}",
"function",
"handleError",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"}"
] | Sends an HTTP GET request using XMLHttpRequest.
@param {boolean} async - Whether to send the request synchronously or asynchronously
@param {string} url - The absolute URL to request
@param {Config} config - Configuration settings, such as timeout, headers, etc.
@param {function} callback - Called with an error or response object | [
"Sends",
"an",
"HTTP",
"GET",
"request",
"using",
"XMLHttpRequest",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/XMLHttpRequestPlugin.js#L76-L109 | train |
JamesMessinger/json-schema-lib | lib/plugins/XMLHttpRequestPlugin.js | setXHRConfig | function setXHRConfig (req, config) {
try {
req.withCredentials = config.http.withCredentials;
}
catch (err) {
// Some browsers don't allow `withCredentials` to be set for synchronous requests
}
try {
req.timeout = config.http.timeout;
}
catch (err) {
// Some browsers don't allow `timeout` to be set for synchronous requests
}
// Set request headers
Object.keys(config.http.headers).forEach(function (key) {
var value = config.http.headers[key];
if (value !== undefined) {
req.setRequestHeader(key, value);
}
});
} | javascript | function setXHRConfig (req, config) {
try {
req.withCredentials = config.http.withCredentials;
}
catch (err) {
// Some browsers don't allow `withCredentials` to be set for synchronous requests
}
try {
req.timeout = config.http.timeout;
}
catch (err) {
// Some browsers don't allow `timeout` to be set for synchronous requests
}
// Set request headers
Object.keys(config.http.headers).forEach(function (key) {
var value = config.http.headers[key];
if (value !== undefined) {
req.setRequestHeader(key, value);
}
});
} | [
"function",
"setXHRConfig",
"(",
"req",
",",
"config",
")",
"{",
"try",
"{",
"req",
".",
"withCredentials",
"=",
"config",
".",
"http",
".",
"withCredentials",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"try",
"{",
"req",
".",
"timeout",
"=",
"config",
".",
"http",
".",
"timeout",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"Object",
".",
"keys",
"(",
"config",
".",
"http",
".",
"headers",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"var",
"value",
"=",
"config",
".",
"http",
".",
"headers",
"[",
"key",
"]",
";",
"if",
"(",
"value",
"!==",
"undefined",
")",
"{",
"req",
".",
"setRequestHeader",
"(",
"key",
",",
"value",
")",
";",
"}",
"}",
")",
";",
"}"
] | Sets the XMLHttpRequest properties, per the specified configuration.
@param {XMLHttpRequest} req
@param {Config} config | [
"Sets",
"the",
"XMLHttpRequest",
"properties",
"per",
"the",
"specified",
"configuration",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/XMLHttpRequestPlugin.js#L117-L139 | train |
JamesMessinger/json-schema-lib | lib/plugins/XMLHttpRequestPlugin.js | parseResponseHeaders | function parseResponseHeaders (headers) {
var parsed = {};
if (headers) {
headers.split('\n').forEach(function (line) {
var separatorIndex = line.indexOf(':');
var key = line.substr(0, separatorIndex).trim().toLowerCase();
var value = line.substr(separatorIndex + 1).trim().toLowerCase();
if (key) {
parsed[key] = value;
}
});
}
return parsed;
} | javascript | function parseResponseHeaders (headers) {
var parsed = {};
if (headers) {
headers.split('\n').forEach(function (line) {
var separatorIndex = line.indexOf(':');
var key = line.substr(0, separatorIndex).trim().toLowerCase();
var value = line.substr(separatorIndex + 1).trim().toLowerCase();
if (key) {
parsed[key] = value;
}
});
}
return parsed;
} | [
"function",
"parseResponseHeaders",
"(",
"headers",
")",
"{",
"var",
"parsed",
"=",
"{",
"}",
";",
"if",
"(",
"headers",
")",
"{",
"headers",
".",
"split",
"(",
"'\\n'",
")",
".",
"\\n",
"forEach",
";",
"}",
"(",
"function",
"(",
"line",
")",
"{",
"var",
"separatorIndex",
"=",
"line",
".",
"indexOf",
"(",
"':'",
")",
";",
"var",
"key",
"=",
"line",
".",
"substr",
"(",
"0",
",",
"separatorIndex",
")",
".",
"trim",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"var",
"value",
"=",
"line",
".",
"substr",
"(",
"separatorIndex",
"+",
"1",
")",
".",
"trim",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"key",
")",
"{",
"parsed",
"[",
"key",
"]",
"=",
"value",
";",
"}",
"}",
")",
"}"
] | Parses HTTP response headers, and returns them as an object with header names as keys
and header values as values.
@param {?string} headers - Response headers, separated by CRLF
@returns {object} | [
"Parses",
"HTTP",
"response",
"headers",
"and",
"returns",
"them",
"as",
"an",
"object",
"with",
"header",
"names",
"as",
"keys",
"and",
"header",
"values",
"as",
"values",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/XMLHttpRequestPlugin.js#L174-L190 | train |
JamesMessinger/json-schema-lib | lib/api/Config.js | validateConfig | function validateConfig (config) {
var type = typeOf(config);
if (type.hasValue && !type.isPOJO) {
throw ono('Invalid arguments. Expected a configuration object.');
}
} | javascript | function validateConfig (config) {
var type = typeOf(config);
if (type.hasValue && !type.isPOJO) {
throw ono('Invalid arguments. Expected a configuration object.');
}
} | [
"function",
"validateConfig",
"(",
"config",
")",
"{",
"var",
"type",
"=",
"typeOf",
"(",
"config",
")",
";",
"if",
"(",
"type",
".",
"hasValue",
"&&",
"!",
"type",
".",
"isPOJO",
")",
"{",
"throw",
"ono",
"(",
"'Invalid arguments. Expected a configuration object.'",
")",
";",
"}",
"}"
] | Ensures that a user-supplied value is a valid configuration POJO.
An error is thrown if the value is invalid.
@param {*} config - The user-supplied value to validate | [
"Ensures",
"that",
"a",
"user",
"-",
"supplied",
"value",
"is",
"a",
"valid",
"configuration",
"POJO",
".",
"An",
"error",
"is",
"thrown",
"if",
"the",
"value",
"is",
"invalid",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/Config.js#L85-L91 | train |
matteodelabre/midijs | lib/file/encoder/header.js | encodeHeader | function encodeHeader(header) {
var cursor = new BufferCursor(new buffer.Buffer(6));
cursor.writeUInt16BE(header.getFileType());
cursor.writeUInt16BE(header._trackCount);
cursor.writeUInt16BE(header.getTicksPerBeat() & 0x7FFF);
return encodeChunk('MThd', cursor.buffer);
} | javascript | function encodeHeader(header) {
var cursor = new BufferCursor(new buffer.Buffer(6));
cursor.writeUInt16BE(header.getFileType());
cursor.writeUInt16BE(header._trackCount);
cursor.writeUInt16BE(header.getTicksPerBeat() & 0x7FFF);
return encodeChunk('MThd', cursor.buffer);
} | [
"function",
"encodeHeader",
"(",
"header",
")",
"{",
"var",
"cursor",
"=",
"new",
"BufferCursor",
"(",
"new",
"buffer",
".",
"Buffer",
"(",
"6",
")",
")",
";",
"cursor",
".",
"writeUInt16BE",
"(",
"header",
".",
"getFileType",
"(",
")",
")",
";",
"cursor",
".",
"writeUInt16BE",
"(",
"header",
".",
"_trackCount",
")",
";",
"cursor",
".",
"writeUInt16BE",
"(",
"header",
".",
"getTicksPerBeat",
"(",
")",
"&",
"0x7FFF",
")",
";",
"return",
"encodeChunk",
"(",
"'MThd'",
",",
"cursor",
".",
"buffer",
")",
";",
"}"
] | Encode a MIDI header chunk
@param {module:midijs/lib/file/header~Header} header Header to encode
@return {Buffer} Encoded header | [
"Encode",
"a",
"MIDI",
"header",
"chunk"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/encoder/header.js#L13-L21 | train |
silverbucket/webfinger.js | src/webfinger.js | isSecure | function isSecure(url) {
if (typeof url !== 'string') {
return false;
}
var parts = url.split('://');
if (parts[0] === 'https') {
return true;
}
return false;
} | javascript | function isSecure(url) {
if (typeof url !== 'string') {
return false;
}
var parts = url.split('://');
if (parts[0] === 'https') {
return true;
}
return false;
} | [
"function",
"isSecure",
"(",
"url",
")",
"{",
"if",
"(",
"typeof",
"url",
"!==",
"'string'",
")",
"{",
"return",
"false",
";",
"}",
"var",
"parts",
"=",
"url",
".",
"split",
"(",
"'://'",
")",
";",
"if",
"(",
"parts",
"[",
"0",
"]",
"===",
"'https'",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | given a URL ensures it's HTTPS. returns false for null string or non-HTTPS URL. | [
"given",
"a",
"URL",
"ensures",
"it",
"s",
"HTTPS",
".",
"returns",
"false",
"for",
"null",
"string",
"or",
"non",
"-",
"HTTPS",
"URL",
"."
] | d99ae22d55b37b517cf1f0713735104c23b0743d | https://github.com/silverbucket/webfinger.js/blob/d99ae22d55b37b517cf1f0713735104c23b0743d/src/webfinger.js#L68-L77 | train |
silverbucket/webfinger.js | src/webfinger.js | __fallbackChecks | function __fallbackChecks(err) {
if ((self.config.uri_fallback) && (host !== 'webfist.org') && (uri_index !== URIS.length - 1)) { // we have uris left to try
uri_index = uri_index + 1;
return __call();
} else if ((!self.config.tls_only) && (protocol === 'https')) { // try normal http
uri_index = 0;
protocol = 'http';
return __call();
} else if ((self.config.webfist_fallback) && (host !== 'webfist.org')) { // webfist attempt
uri_index = 0;
protocol = 'http';
host = 'webfist.org';
// webfist will
// 1. make a query to the webfist server for the users account
// 2. from the response, get a link to the actual webfinger json data
// (stored somewhere in control of the user)
// 3. make a request to that url and get the json
// 4. process it like a normal webfinger response
var URL = __buildURL();
self.__fetchJRD(URL, cb, function (data) { // get link to users JRD
self.__processJRD(URL, data, cb, function (result) {
if ((typeof result.idx.links.webfist === 'object') &&
(typeof result.idx.links.webfist[0].href === 'string')) {
self.__fetchJRD(result.idx.links.webfist[0].href, cb, function (JRD) {
self.__processJRD(URL, JRD, cb, function (result) {
return cb(null, cb);
});
});
}
});
});
} else {
return cb(err);
}
} | javascript | function __fallbackChecks(err) {
if ((self.config.uri_fallback) && (host !== 'webfist.org') && (uri_index !== URIS.length - 1)) { // we have uris left to try
uri_index = uri_index + 1;
return __call();
} else if ((!self.config.tls_only) && (protocol === 'https')) { // try normal http
uri_index = 0;
protocol = 'http';
return __call();
} else if ((self.config.webfist_fallback) && (host !== 'webfist.org')) { // webfist attempt
uri_index = 0;
protocol = 'http';
host = 'webfist.org';
// webfist will
// 1. make a query to the webfist server for the users account
// 2. from the response, get a link to the actual webfinger json data
// (stored somewhere in control of the user)
// 3. make a request to that url and get the json
// 4. process it like a normal webfinger response
var URL = __buildURL();
self.__fetchJRD(URL, cb, function (data) { // get link to users JRD
self.__processJRD(URL, data, cb, function (result) {
if ((typeof result.idx.links.webfist === 'object') &&
(typeof result.idx.links.webfist[0].href === 'string')) {
self.__fetchJRD(result.idx.links.webfist[0].href, cb, function (JRD) {
self.__processJRD(URL, JRD, cb, function (result) {
return cb(null, cb);
});
});
}
});
});
} else {
return cb(err);
}
} | [
"function",
"__fallbackChecks",
"(",
"err",
")",
"{",
"if",
"(",
"(",
"self",
".",
"config",
".",
"uri_fallback",
")",
"&&",
"(",
"host",
"!==",
"'webfist.org'",
")",
"&&",
"(",
"uri_index",
"!==",
"URIS",
".",
"length",
"-",
"1",
")",
")",
"{",
"uri_index",
"=",
"uri_index",
"+",
"1",
";",
"return",
"__call",
"(",
")",
";",
"}",
"else",
"if",
"(",
"(",
"!",
"self",
".",
"config",
".",
"tls_only",
")",
"&&",
"(",
"protocol",
"===",
"'https'",
")",
")",
"{",
"uri_index",
"=",
"0",
";",
"protocol",
"=",
"'http'",
";",
"return",
"__call",
"(",
")",
";",
"}",
"else",
"if",
"(",
"(",
"self",
".",
"config",
".",
"webfist_fallback",
")",
"&&",
"(",
"host",
"!==",
"'webfist.org'",
")",
")",
"{",
"uri_index",
"=",
"0",
";",
"protocol",
"=",
"'http'",
";",
"host",
"=",
"'webfist.org'",
";",
"var",
"URL",
"=",
"__buildURL",
"(",
")",
";",
"self",
".",
"__fetchJRD",
"(",
"URL",
",",
"cb",
",",
"function",
"(",
"data",
")",
"{",
"self",
".",
"__processJRD",
"(",
"URL",
",",
"data",
",",
"cb",
",",
"function",
"(",
"result",
")",
"{",
"if",
"(",
"(",
"typeof",
"result",
".",
"idx",
".",
"links",
".",
"webfist",
"===",
"'object'",
")",
"&&",
"(",
"typeof",
"result",
".",
"idx",
".",
"links",
".",
"webfist",
"[",
"0",
"]",
".",
"href",
"===",
"'string'",
")",
")",
"{",
"self",
".",
"__fetchJRD",
"(",
"result",
".",
"idx",
".",
"links",
".",
"webfist",
"[",
"0",
"]",
".",
"href",
",",
"cb",
",",
"function",
"(",
"JRD",
")",
"{",
"self",
".",
"__processJRD",
"(",
"URL",
",",
"JRD",
",",
"cb",
",",
"function",
"(",
"result",
")",
"{",
"return",
"cb",
"(",
"null",
",",
"cb",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"}"
] | control flow for failures, what to do in various cases, etc. | [
"control",
"flow",
"for",
"failures",
"what",
"to",
"do",
"in",
"various",
"cases",
"etc",
"."
] | d99ae22d55b37b517cf1f0713735104c23b0743d | https://github.com/silverbucket/webfinger.js/blob/d99ae22d55b37b517cf1f0713735104c23b0743d/src/webfinger.js#L356-L390 | train |
LivePersonInc/chronosjs | src/Channels.js | _wrapCalls | function _wrapCalls(options){
return function(){
var api;
options.func.apply(options.context, Array.prototype.slice.call(arguments, 0));
for (var i = 0; i < externalAPIS.length; i++) {
api = externalAPIS[i];
if (api[options.triggerType]) {
try {
api[options.triggerType].apply(api.context,Array.prototype.slice.call(arguments, 0));
}
catch (exc) {}
}
}
};
} | javascript | function _wrapCalls(options){
return function(){
var api;
options.func.apply(options.context, Array.prototype.slice.call(arguments, 0));
for (var i = 0; i < externalAPIS.length; i++) {
api = externalAPIS[i];
if (api[options.triggerType]) {
try {
api[options.triggerType].apply(api.context,Array.prototype.slice.call(arguments, 0));
}
catch (exc) {}
}
}
};
} | [
"function",
"_wrapCalls",
"(",
"options",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"api",
";",
"options",
".",
"func",
".",
"apply",
"(",
"options",
".",
"context",
",",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"externalAPIS",
".",
"length",
";",
"i",
"++",
")",
"{",
"api",
"=",
"externalAPIS",
"[",
"i",
"]",
";",
"if",
"(",
"api",
"[",
"options",
".",
"triggerType",
"]",
")",
"{",
"try",
"{",
"api",
"[",
"options",
".",
"triggerType",
"]",
".",
"apply",
"(",
"api",
".",
"context",
",",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
")",
";",
"}",
"catch",
"(",
"exc",
")",
"{",
"}",
"}",
"}",
"}",
";",
"}"
] | Wraps API calls to trigger other registered functions
@param options
@returns {Function}
@private | [
"Wraps",
"API",
"calls",
"to",
"trigger",
"other",
"registered",
"functions"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/Channels.js#L79-L95 | train |
JamesMessinger/json-schema-lib | lib/api/PluginHelper/callAsyncPlugin.js | callAsyncPlugin | function callAsyncPlugin (pluginHelper, methodName, args, callback) {
var plugins = pluginHelper.filter(filterByMethod(methodName));
args.schema = pluginHelper[__internal].schema;
args.config = args.schema.config;
safeCall(callNextPlugin, plugins, methodName, args, callback);
} | javascript | function callAsyncPlugin (pluginHelper, methodName, args, callback) {
var plugins = pluginHelper.filter(filterByMethod(methodName));
args.schema = pluginHelper[__internal].schema;
args.config = args.schema.config;
safeCall(callNextPlugin, plugins, methodName, args, callback);
} | [
"function",
"callAsyncPlugin",
"(",
"pluginHelper",
",",
"methodName",
",",
"args",
",",
"callback",
")",
"{",
"var",
"plugins",
"=",
"pluginHelper",
".",
"filter",
"(",
"filterByMethod",
"(",
"methodName",
")",
")",
";",
"args",
".",
"schema",
"=",
"pluginHelper",
"[",
"__internal",
"]",
".",
"schema",
";",
"args",
".",
"config",
"=",
"args",
".",
"schema",
".",
"config",
";",
"safeCall",
"(",
"callNextPlugin",
",",
"plugins",
",",
"methodName",
",",
"args",
",",
"callback",
")",
";",
"}"
] | Calls an asynchronous plugin method with the given arguments.
@param {PluginHelper} pluginHelper - The {@link PluginHelper} whose plugins are called
@param {string} methodName - The name of the plugin method to call
@param {object} args - The arguments to pass to the method
@param {function} callback - The callback to call when the method finishes | [
"Calls",
"an",
"asynchronous",
"plugin",
"method",
"with",
"the",
"given",
"arguments",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/PluginHelper/callAsyncPlugin.js#L18-L24 | train |
glennjones/elsewhere-profiles | lib/utilities.js | getNodeVaue | function getNodeVaue(path, obj) {
// Gets a value from a JSON object
// vcard[0].url[0]
var output = null;
try {
var arrayDots = path.split(".");
for (var i = 0; i < arrayDots.length; i++) {
if (arrayDots[i].indexOf('[') > -1) {
// Reconstructs and adds access to array of objects
var arrayAB = arrayDots[i].split("[");
var arrayName = arrayAB[0];
var arrayPosition = Number(arrayAB[1].substring(0, arrayAB[1].length - 1));
if (obj[arrayName] != null || obj[arrayName] != 'undefined') {
if (obj[arrayName][arrayPosition] != null || obj[arrayName][arrayPosition] != 'undefined')
obj = obj[arrayName][arrayPosition];
}
else {
currentObject = null;
}
}
else {
// Adds access to a property using property array ["given-name"]
if (obj[arrayDots[i]] != null || obj[arrayDots[i]] != 'undefined')
obj = obj[arrayDots[i]];
}
}
output = obj;
} catch (err) {
// Add error capture
output = null;
}
return output;
} | javascript | function getNodeVaue(path, obj) {
// Gets a value from a JSON object
// vcard[0].url[0]
var output = null;
try {
var arrayDots = path.split(".");
for (var i = 0; i < arrayDots.length; i++) {
if (arrayDots[i].indexOf('[') > -1) {
// Reconstructs and adds access to array of objects
var arrayAB = arrayDots[i].split("[");
var arrayName = arrayAB[0];
var arrayPosition = Number(arrayAB[1].substring(0, arrayAB[1].length - 1));
if (obj[arrayName] != null || obj[arrayName] != 'undefined') {
if (obj[arrayName][arrayPosition] != null || obj[arrayName][arrayPosition] != 'undefined')
obj = obj[arrayName][arrayPosition];
}
else {
currentObject = null;
}
}
else {
// Adds access to a property using property array ["given-name"]
if (obj[arrayDots[i]] != null || obj[arrayDots[i]] != 'undefined')
obj = obj[arrayDots[i]];
}
}
output = obj;
} catch (err) {
// Add error capture
output = null;
}
return output;
} | [
"function",
"getNodeVaue",
"(",
"path",
",",
"obj",
")",
"{",
"var",
"output",
"=",
"null",
";",
"try",
"{",
"var",
"arrayDots",
"=",
"path",
".",
"split",
"(",
"\".\"",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"arrayDots",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"arrayDots",
"[",
"i",
"]",
".",
"indexOf",
"(",
"'['",
")",
">",
"-",
"1",
")",
"{",
"var",
"arrayAB",
"=",
"arrayDots",
"[",
"i",
"]",
".",
"split",
"(",
"\"[\"",
")",
";",
"var",
"arrayName",
"=",
"arrayAB",
"[",
"0",
"]",
";",
"var",
"arrayPosition",
"=",
"Number",
"(",
"arrayAB",
"[",
"1",
"]",
".",
"substring",
"(",
"0",
",",
"arrayAB",
"[",
"1",
"]",
".",
"length",
"-",
"1",
")",
")",
";",
"if",
"(",
"obj",
"[",
"arrayName",
"]",
"!=",
"null",
"||",
"obj",
"[",
"arrayName",
"]",
"!=",
"'undefined'",
")",
"{",
"if",
"(",
"obj",
"[",
"arrayName",
"]",
"[",
"arrayPosition",
"]",
"!=",
"null",
"||",
"obj",
"[",
"arrayName",
"]",
"[",
"arrayPosition",
"]",
"!=",
"'undefined'",
")",
"obj",
"=",
"obj",
"[",
"arrayName",
"]",
"[",
"arrayPosition",
"]",
";",
"}",
"else",
"{",
"currentObject",
"=",
"null",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"obj",
"[",
"arrayDots",
"[",
"i",
"]",
"]",
"!=",
"null",
"||",
"obj",
"[",
"arrayDots",
"[",
"i",
"]",
"]",
"!=",
"'undefined'",
")",
"obj",
"=",
"obj",
"[",
"arrayDots",
"[",
"i",
"]",
"]",
";",
"}",
"}",
"output",
"=",
"obj",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"output",
"=",
"null",
";",
"}",
"return",
"output",
";",
"}"
] | a helper function, finds a property value of a given object literal | [
"a",
"helper",
"function",
"finds",
"a",
"property",
"value",
"of",
"a",
"given",
"object",
"literal"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/utilities.js#L27-L62 | train |
glennjones/elsewhere-profiles | lib/utilities.js | getIdentity | function getIdentity(urlStr, urlTemplates, www) {
var identity = {};
urlObj = urlParser.parse(urlStr);
// Loop all the urlMappings for site object
for(var y = 0; y <= urlTemplates.length-1; y++){
urlTemplate = urlTemplates[y];
// remove http protocol
urlTemplate = removeHttpHttps(urlTemplate);
// if the urlTemplate contains a username or userid parse it
if (urlTemplate != '' && (urlTemplate.indexOf('{username}') > -1 || urlTemplate.indexOf('{userid}') > -1)) {
// break up url template
var parts = urlTemplate.split(/\{userid\}|\{username\}/),
startMatch = false,
endMatch = false,
user = urlObj.href
// remove protocol, querystring and fragment
user = user.replace(urlObj.hash, '');
user = user.replace(urlObj.search, '');
user = removeHttpHttps(user);
// remove www if subdomain is optional
if(www){
user = user.replace('www.', '') ;
urlStr = urlStr.replace('www.', '') ;
}
// remove any trailing /
if (endsWith(user,'/'))
user = user.substring(0, user.length - 1);
// remove unwanted front section of url string
if (user.indexOf(parts[0]) === 0){
startMatch = true;
part = parts[0];
user = user.substring(part.length, user.length);
}
// remove unwanted end section of url string
if (parts.length === 2){
// if no end part or its just and trailing /
if (parts[1].length > 0 && parts[1] !== '/'){
// end part matches template
if (endsWith(user,parts[1])){
endMatch = true;
user = user.replace(parts[1], '');
} else if (endsWith(user,parts[1] + '/')) {
// end part matches template with a trailing /
endMatch = true;
user = user.replace(parts[1] + '/', '');
}
} else {
endMatch = true;
}
}
// if the user contain anymore / then do not use it
if (user.indexOf("/") > -1)
endMatch = false;
if (startMatch && endMatch){
identity = {};
identity.domain = urlObj.host;
identity.matchedUrl = urlStr;
if (urlTemplate.indexOf("{username}") > -1){
identity.userName = user;
identity.sgn = "sgn://" + urlObj.host + "/?ident=" + user;
}
if (urlTemplate.indexOf("{userid}") > -1){
identity.userId = user;
identity.sgn = "sgn://" + urlObj.host + "/?pk=" + user;
}
break;
}
}
}
return identity;
} | javascript | function getIdentity(urlStr, urlTemplates, www) {
var identity = {};
urlObj = urlParser.parse(urlStr);
// Loop all the urlMappings for site object
for(var y = 0; y <= urlTemplates.length-1; y++){
urlTemplate = urlTemplates[y];
// remove http protocol
urlTemplate = removeHttpHttps(urlTemplate);
// if the urlTemplate contains a username or userid parse it
if (urlTemplate != '' && (urlTemplate.indexOf('{username}') > -1 || urlTemplate.indexOf('{userid}') > -1)) {
// break up url template
var parts = urlTemplate.split(/\{userid\}|\{username\}/),
startMatch = false,
endMatch = false,
user = urlObj.href
// remove protocol, querystring and fragment
user = user.replace(urlObj.hash, '');
user = user.replace(urlObj.search, '');
user = removeHttpHttps(user);
// remove www if subdomain is optional
if(www){
user = user.replace('www.', '') ;
urlStr = urlStr.replace('www.', '') ;
}
// remove any trailing /
if (endsWith(user,'/'))
user = user.substring(0, user.length - 1);
// remove unwanted front section of url string
if (user.indexOf(parts[0]) === 0){
startMatch = true;
part = parts[0];
user = user.substring(part.length, user.length);
}
// remove unwanted end section of url string
if (parts.length === 2){
// if no end part or its just and trailing /
if (parts[1].length > 0 && parts[1] !== '/'){
// end part matches template
if (endsWith(user,parts[1])){
endMatch = true;
user = user.replace(parts[1], '');
} else if (endsWith(user,parts[1] + '/')) {
// end part matches template with a trailing /
endMatch = true;
user = user.replace(parts[1] + '/', '');
}
} else {
endMatch = true;
}
}
// if the user contain anymore / then do not use it
if (user.indexOf("/") > -1)
endMatch = false;
if (startMatch && endMatch){
identity = {};
identity.domain = urlObj.host;
identity.matchedUrl = urlStr;
if (urlTemplate.indexOf("{username}") > -1){
identity.userName = user;
identity.sgn = "sgn://" + urlObj.host + "/?ident=" + user;
}
if (urlTemplate.indexOf("{userid}") > -1){
identity.userId = user;
identity.sgn = "sgn://" + urlObj.host + "/?pk=" + user;
}
break;
}
}
}
return identity;
} | [
"function",
"getIdentity",
"(",
"urlStr",
",",
"urlTemplates",
",",
"www",
")",
"{",
"var",
"identity",
"=",
"{",
"}",
";",
"urlObj",
"=",
"urlParser",
".",
"parse",
"(",
"urlStr",
")",
";",
"for",
"(",
"var",
"y",
"=",
"0",
";",
"y",
"<=",
"urlTemplates",
".",
"length",
"-",
"1",
";",
"y",
"++",
")",
"{",
"urlTemplate",
"=",
"urlTemplates",
"[",
"y",
"]",
";",
"urlTemplate",
"=",
"removeHttpHttps",
"(",
"urlTemplate",
")",
";",
"if",
"(",
"urlTemplate",
"!=",
"''",
"&&",
"(",
"urlTemplate",
".",
"indexOf",
"(",
"'{username}'",
")",
">",
"-",
"1",
"||",
"urlTemplate",
".",
"indexOf",
"(",
"'{userid}'",
")",
">",
"-",
"1",
")",
")",
"{",
"var",
"parts",
"=",
"urlTemplate",
".",
"split",
"(",
"/",
"\\{userid\\}|\\{username\\}",
"/",
")",
",",
"startMatch",
"=",
"false",
",",
"endMatch",
"=",
"false",
",",
"user",
"=",
"urlObj",
".",
"href",
"user",
"=",
"user",
".",
"replace",
"(",
"urlObj",
".",
"hash",
",",
"''",
")",
";",
"user",
"=",
"user",
".",
"replace",
"(",
"urlObj",
".",
"search",
",",
"''",
")",
";",
"user",
"=",
"removeHttpHttps",
"(",
"user",
")",
";",
"if",
"(",
"www",
")",
"{",
"user",
"=",
"user",
".",
"replace",
"(",
"'www.'",
",",
"''",
")",
";",
"urlStr",
"=",
"urlStr",
".",
"replace",
"(",
"'www.'",
",",
"''",
")",
";",
"}",
"if",
"(",
"endsWith",
"(",
"user",
",",
"'/'",
")",
")",
"user",
"=",
"user",
".",
"substring",
"(",
"0",
",",
"user",
".",
"length",
"-",
"1",
")",
";",
"if",
"(",
"user",
".",
"indexOf",
"(",
"parts",
"[",
"0",
"]",
")",
"===",
"0",
")",
"{",
"startMatch",
"=",
"true",
";",
"part",
"=",
"parts",
"[",
"0",
"]",
";",
"user",
"=",
"user",
".",
"substring",
"(",
"part",
".",
"length",
",",
"user",
".",
"length",
")",
";",
"}",
"if",
"(",
"parts",
".",
"length",
"===",
"2",
")",
"{",
"if",
"(",
"parts",
"[",
"1",
"]",
".",
"length",
">",
"0",
"&&",
"parts",
"[",
"1",
"]",
"!==",
"'/'",
")",
"{",
"if",
"(",
"endsWith",
"(",
"user",
",",
"parts",
"[",
"1",
"]",
")",
")",
"{",
"endMatch",
"=",
"true",
";",
"user",
"=",
"user",
".",
"replace",
"(",
"parts",
"[",
"1",
"]",
",",
"''",
")",
";",
"}",
"else",
"if",
"(",
"endsWith",
"(",
"user",
",",
"parts",
"[",
"1",
"]",
"+",
"'/'",
")",
")",
"{",
"endMatch",
"=",
"true",
";",
"user",
"=",
"user",
".",
"replace",
"(",
"parts",
"[",
"1",
"]",
"+",
"'/'",
",",
"''",
")",
";",
"}",
"}",
"else",
"{",
"endMatch",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"user",
".",
"indexOf",
"(",
"\"/\"",
")",
">",
"-",
"1",
")",
"endMatch",
"=",
"false",
";",
"if",
"(",
"startMatch",
"&&",
"endMatch",
")",
"{",
"identity",
"=",
"{",
"}",
";",
"identity",
".",
"domain",
"=",
"urlObj",
".",
"host",
";",
"identity",
".",
"matchedUrl",
"=",
"urlStr",
";",
"if",
"(",
"urlTemplate",
".",
"indexOf",
"(",
"\"{username}\"",
")",
">",
"-",
"1",
")",
"{",
"identity",
".",
"userName",
"=",
"user",
";",
"identity",
".",
"sgn",
"=",
"\"sgn://\"",
"+",
"urlObj",
".",
"host",
"+",
"\"/?ident=\"",
"+",
"user",
";",
"}",
"if",
"(",
"urlTemplate",
".",
"indexOf",
"(",
"\"{userid}\"",
")",
">",
"-",
"1",
")",
"{",
"identity",
".",
"userId",
"=",
"user",
";",
"identity",
".",
"sgn",
"=",
"\"sgn://\"",
"+",
"urlObj",
".",
"host",
"+",
"\"/?pk=\"",
"+",
"user",
";",
"}",
"break",
";",
"}",
"}",
"}",
"return",
"identity",
";",
"}"
] | find the sgn and builds the identity object | [
"find",
"the",
"sgn",
"and",
"builds",
"the",
"identity",
"object"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/utilities.js#L66-L158 | train |
glennjones/elsewhere-profiles | lib/utilities.js | endsWith | function endsWith(str,test){
var lastIndex = str.lastIndexOf(test);
return (lastIndex != -1) && (lastIndex + test.length == str.length);
} | javascript | function endsWith(str,test){
var lastIndex = str.lastIndexOf(test);
return (lastIndex != -1) && (lastIndex + test.length == str.length);
} | [
"function",
"endsWith",
"(",
"str",
",",
"test",
")",
"{",
"var",
"lastIndex",
"=",
"str",
".",
"lastIndexOf",
"(",
"test",
")",
";",
"return",
"(",
"lastIndex",
"!=",
"-",
"1",
")",
"&&",
"(",
"lastIndex",
"+",
"test",
".",
"length",
"==",
"str",
".",
"length",
")",
";",
"}"
] | simple endsWith function. Use with care | [
"simple",
"endsWith",
"function",
".",
"Use",
"with",
"care"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/utilities.js#L199-L202 | train |
glennjones/elsewhere-profiles | lib/utilities.js | isUrl | function isUrl (obj) {
if(isString(obj)){
if((obj.indexOf('http://') > -1 || obj.indexOf('https://') > -1)
&& obj.indexOf('.') > -1)
return true
else
return false
}else{
return false;
}
} | javascript | function isUrl (obj) {
if(isString(obj)){
if((obj.indexOf('http://') > -1 || obj.indexOf('https://') > -1)
&& obj.indexOf('.') > -1)
return true
else
return false
}else{
return false;
}
} | [
"function",
"isUrl",
"(",
"obj",
")",
"{",
"if",
"(",
"isString",
"(",
"obj",
")",
")",
"{",
"if",
"(",
"(",
"obj",
".",
"indexOf",
"(",
"'http://'",
")",
">",
"-",
"1",
"||",
"obj",
".",
"indexOf",
"(",
"'https://'",
")",
">",
"-",
"1",
")",
"&&",
"obj",
".",
"indexOf",
"(",
"'.'",
")",
">",
"-",
"1",
")",
"return",
"true",
"else",
"return",
"false",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | is an object a URL - very simple version | [
"is",
"an",
"object",
"a",
"URL",
"-",
"very",
"simple",
"version"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/utilities.js#L227-L237 | train |
matteodelabre/midijs | lib/file/encoder/track.js | encodeTrack | function encodeTrack(track) {
var events = track.getEvents(), data = [],
length = events.length, i,
runningStatus = null, result;
for (i = 0; i < length; i += 1) {
result = encodeEvent(events[i], runningStatus);
runningStatus = result.runningStatus;
data[i] = result.data;
}
return encodeChunk('MTrk', buffer.Buffer.concat(data));
} | javascript | function encodeTrack(track) {
var events = track.getEvents(), data = [],
length = events.length, i,
runningStatus = null, result;
for (i = 0; i < length; i += 1) {
result = encodeEvent(events[i], runningStatus);
runningStatus = result.runningStatus;
data[i] = result.data;
}
return encodeChunk('MTrk', buffer.Buffer.concat(data));
} | [
"function",
"encodeTrack",
"(",
"track",
")",
"{",
"var",
"events",
"=",
"track",
".",
"getEvents",
"(",
")",
",",
"data",
"=",
"[",
"]",
",",
"length",
"=",
"events",
".",
"length",
",",
"i",
",",
"runningStatus",
"=",
"null",
",",
"result",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"result",
"=",
"encodeEvent",
"(",
"events",
"[",
"i",
"]",
",",
"runningStatus",
")",
";",
"runningStatus",
"=",
"result",
".",
"runningStatus",
";",
"data",
"[",
"i",
"]",
"=",
"result",
".",
"data",
";",
"}",
"return",
"encodeChunk",
"(",
"'MTrk'",
",",
"buffer",
".",
"Buffer",
".",
"concat",
"(",
"data",
")",
")",
";",
"}"
] | Encode a MIDI track chunk
@param {module:midijs/lib/file/track~Track} track Track to encode
@return {Buffer} Encoded track | [
"Encode",
"a",
"MIDI",
"track",
"chunk"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/encoder/track.js#L13-L26 | train |
claudio-silva/grunt-angular-builder | tasks/middleware/analyzeSourceCode.js | AnalyzeSourceCodeMiddleware | function AnalyzeSourceCodeMiddleware (context)
{
var grunt = context.grunt;
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
var src = util.sortFilesBeforeSubfolders (filesArray.src);
// Load the script files and scan them for module definitions.
src.forEach (function (path)
{
if (!grunt.file.exists (path)) {
warn ('Source file "' + path + '" not found.');
return;
}
// Read the script and scan it for module declarations.
var script = grunt.file.read (path);
/** @type {ModuleHeaderInfo[]} */
var moduleHeaders;
try {
moduleHeaders = sourceExtract.extractModuleHeaders (script);
}
catch (e) {
if (typeof e === 'string')
return warn (e + NL + reportErrorLocation (path));
throw e;
}
// Ignore irrelevant files.
if (!moduleHeaders.length) {
if (!filesArray.forceInclude || !grunt.file.isMatch ({matchBase: true}, filesArray.forceInclude, path)) {
info ('Ignored file: %', path.cyan);
return;
}
context.standaloneScripts.push ({
path: path,
content: script
});
}
else moduleHeaders.forEach (function (header)
{
setupModuleInfo (header, script, path);
});
});
};
this.trace = function (module)
{
/* jshint unused: vars */
// Do nothing
};
this.build = function (targetScript)
{
/* jshint unused: vars */
// Do nothing
};
//--------------------------------------------------------------------------------------------------------------------
// PRIVATE
//--------------------------------------------------------------------------------------------------------------------
/**
* Store information about the specified module retrieved from the given source code on the specified file.
*
* @param {ModuleHeaderInfo} moduleHeader
* @param {string} fileContent
* @param {string} filePath
*/
function setupModuleInfo (moduleHeader, fileContent, filePath)
{
// Get information about the specified module.
var module = context.modules[moduleHeader.name];
// If this is the first time a specific module is mentioned, create the respective information record.
if (!module)
module = context.modules[moduleHeader.name] = new ModuleDef (moduleHeader.name);
// Skip the file if it defines an external module.
else if (module.external)
return;
// Reject additional attempts to redeclare a module (only appending is allowed).
else if (module.head && !moduleHeader.append)
fatal ('Can\'t redeclare module <cyan>%</cyan>', moduleHeader.name);
// The file is appending definitions to a module declared elsewhere.
if (moduleHeader.append) {
// Append the file path to the paths list.
if (!~module.bodyPaths.indexOf (filePath)) {
module.bodies.push (fileContent);
module.bodyPaths.push (filePath);
}
}
// Otherwise, the file contains a module declaration.
else {
if (module.head)
fatal ('Duplicate module definition: <cyan>%</cyan>', moduleHeader.name);
module.head = fileContent;
module.headPath = filePath;
module.requires = moduleHeader.requires;
}
module.configFn = moduleHeader.configFn;
}
} | javascript | function AnalyzeSourceCodeMiddleware (context)
{
var grunt = context.grunt;
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
var src = util.sortFilesBeforeSubfolders (filesArray.src);
// Load the script files and scan them for module definitions.
src.forEach (function (path)
{
if (!grunt.file.exists (path)) {
warn ('Source file "' + path + '" not found.');
return;
}
// Read the script and scan it for module declarations.
var script = grunt.file.read (path);
/** @type {ModuleHeaderInfo[]} */
var moduleHeaders;
try {
moduleHeaders = sourceExtract.extractModuleHeaders (script);
}
catch (e) {
if (typeof e === 'string')
return warn (e + NL + reportErrorLocation (path));
throw e;
}
// Ignore irrelevant files.
if (!moduleHeaders.length) {
if (!filesArray.forceInclude || !grunt.file.isMatch ({matchBase: true}, filesArray.forceInclude, path)) {
info ('Ignored file: %', path.cyan);
return;
}
context.standaloneScripts.push ({
path: path,
content: script
});
}
else moduleHeaders.forEach (function (header)
{
setupModuleInfo (header, script, path);
});
});
};
this.trace = function (module)
{
/* jshint unused: vars */
// Do nothing
};
this.build = function (targetScript)
{
/* jshint unused: vars */
// Do nothing
};
//--------------------------------------------------------------------------------------------------------------------
// PRIVATE
//--------------------------------------------------------------------------------------------------------------------
/**
* Store information about the specified module retrieved from the given source code on the specified file.
*
* @param {ModuleHeaderInfo} moduleHeader
* @param {string} fileContent
* @param {string} filePath
*/
function setupModuleInfo (moduleHeader, fileContent, filePath)
{
// Get information about the specified module.
var module = context.modules[moduleHeader.name];
// If this is the first time a specific module is mentioned, create the respective information record.
if (!module)
module = context.modules[moduleHeader.name] = new ModuleDef (moduleHeader.name);
// Skip the file if it defines an external module.
else if (module.external)
return;
// Reject additional attempts to redeclare a module (only appending is allowed).
else if (module.head && !moduleHeader.append)
fatal ('Can\'t redeclare module <cyan>%</cyan>', moduleHeader.name);
// The file is appending definitions to a module declared elsewhere.
if (moduleHeader.append) {
// Append the file path to the paths list.
if (!~module.bodyPaths.indexOf (filePath)) {
module.bodies.push (fileContent);
module.bodyPaths.push (filePath);
}
}
// Otherwise, the file contains a module declaration.
else {
if (module.head)
fatal ('Duplicate module definition: <cyan>%</cyan>', moduleHeader.name);
module.head = fileContent;
module.headPath = filePath;
module.requires = moduleHeader.requires;
}
module.configFn = moduleHeader.configFn;
}
} | [
"function",
"AnalyzeSourceCodeMiddleware",
"(",
"context",
")",
"{",
"var",
"grunt",
"=",
"context",
".",
"grunt",
";",
"this",
".",
"analyze",
"=",
"function",
"(",
"filesArray",
")",
"{",
"var",
"src",
"=",
"util",
".",
"sortFilesBeforeSubfolders",
"(",
"filesArray",
".",
"src",
")",
";",
"src",
".",
"forEach",
"(",
"function",
"(",
"path",
")",
"{",
"if",
"(",
"!",
"grunt",
".",
"file",
".",
"exists",
"(",
"path",
")",
")",
"{",
"warn",
"(",
"'Source file \"'",
"+",
"path",
"+",
"'\" not found.'",
")",
";",
"return",
";",
"}",
"var",
"script",
"=",
"grunt",
".",
"file",
".",
"read",
"(",
"path",
")",
";",
"var",
"moduleHeaders",
";",
"try",
"{",
"moduleHeaders",
"=",
"sourceExtract",
".",
"extractModuleHeaders",
"(",
"script",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"typeof",
"e",
"===",
"'string'",
")",
"return",
"warn",
"(",
"e",
"+",
"NL",
"+",
"reportErrorLocation",
"(",
"path",
")",
")",
";",
"throw",
"e",
";",
"}",
"if",
"(",
"!",
"moduleHeaders",
".",
"length",
")",
"{",
"if",
"(",
"!",
"filesArray",
".",
"forceInclude",
"||",
"!",
"grunt",
".",
"file",
".",
"isMatch",
"(",
"{",
"matchBase",
":",
"true",
"}",
",",
"filesArray",
".",
"forceInclude",
",",
"path",
")",
")",
"{",
"info",
"(",
"'Ignored file: %'",
",",
"path",
".",
"cyan",
")",
";",
"return",
";",
"}",
"context",
".",
"standaloneScripts",
".",
"push",
"(",
"{",
"path",
":",
"path",
",",
"content",
":",
"script",
"}",
")",
";",
"}",
"else",
"moduleHeaders",
".",
"forEach",
"(",
"function",
"(",
"header",
")",
"{",
"setupModuleInfo",
"(",
"header",
",",
"script",
",",
"path",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
";",
"this",
".",
"trace",
"=",
"function",
"(",
"module",
")",
"{",
"}",
";",
"this",
".",
"build",
"=",
"function",
"(",
"targetScript",
")",
"{",
"}",
";",
"function",
"setupModuleInfo",
"(",
"moduleHeader",
",",
"fileContent",
",",
"filePath",
")",
"{",
"var",
"module",
"=",
"context",
".",
"modules",
"[",
"moduleHeader",
".",
"name",
"]",
";",
"if",
"(",
"!",
"module",
")",
"module",
"=",
"context",
".",
"modules",
"[",
"moduleHeader",
".",
"name",
"]",
"=",
"new",
"ModuleDef",
"(",
"moduleHeader",
".",
"name",
")",
";",
"else",
"if",
"(",
"module",
".",
"external",
")",
"return",
";",
"else",
"if",
"(",
"module",
".",
"head",
"&&",
"!",
"moduleHeader",
".",
"append",
")",
"fatal",
"(",
"'Can\\'t redeclare module <cyan>%</cyan>'",
",",
"\\'",
")",
";",
"moduleHeader",
".",
"name",
"if",
"(",
"moduleHeader",
".",
"append",
")",
"{",
"if",
"(",
"!",
"~",
"module",
".",
"bodyPaths",
".",
"indexOf",
"(",
"filePath",
")",
")",
"{",
"module",
".",
"bodies",
".",
"push",
"(",
"fileContent",
")",
";",
"module",
".",
"bodyPaths",
".",
"push",
"(",
"filePath",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"module",
".",
"head",
")",
"fatal",
"(",
"'Duplicate module definition: <cyan>%</cyan>'",
",",
"moduleHeader",
".",
"name",
")",
";",
"module",
".",
"head",
"=",
"fileContent",
";",
"module",
".",
"headPath",
"=",
"filePath",
";",
"module",
".",
"requires",
"=",
"moduleHeader",
".",
"requires",
";",
"}",
"}",
"}"
] | An AngularJS source code loader and analyser middleware.
@constructor
@implements {MiddlewareInterface}
@param {Context} context The execution context for the middleware stack. | [
"An",
"AngularJS",
"source",
"code",
"loader",
"and",
"analyser",
"middleware",
"."
] | 0aa4232257e4ae95d0aa9258ff0a91395383d8b7 | https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/analyzeSourceCode.js#L33-L140 | train |
JamesMessinger/json-schema-lib | lib/plugins/FileSystemPlugin.js | resolveURL | function resolveURL (args) {
var from = args.from;
var to = args.to;
var next = args.next;
if (protocolPattern.test(from) || protocolPattern.test(to)) {
// It's a URL, not a filesystem path, so let some other plugin resolve it
return next();
}
if (from) {
// The `from` path needs to be a directory, not a file. So, if the last character is NOT a
// path separator, then we need to remove the filename from the path
if (pathSeparators.indexOf(from[from.length - 1]) === -1) {
from = path.dirname(from);
}
return path.resolve(from, to);
}
else {
// Resolve the `to` path against the current working directory
return path.resolve(to);
}
} | javascript | function resolveURL (args) {
var from = args.from;
var to = args.to;
var next = args.next;
if (protocolPattern.test(from) || protocolPattern.test(to)) {
// It's a URL, not a filesystem path, so let some other plugin resolve it
return next();
}
if (from) {
// The `from` path needs to be a directory, not a file. So, if the last character is NOT a
// path separator, then we need to remove the filename from the path
if (pathSeparators.indexOf(from[from.length - 1]) === -1) {
from = path.dirname(from);
}
return path.resolve(from, to);
}
else {
// Resolve the `to` path against the current working directory
return path.resolve(to);
}
} | [
"function",
"resolveURL",
"(",
"args",
")",
"{",
"var",
"from",
"=",
"args",
".",
"from",
";",
"var",
"to",
"=",
"args",
".",
"to",
";",
"var",
"next",
"=",
"args",
".",
"next",
";",
"if",
"(",
"protocolPattern",
".",
"test",
"(",
"from",
")",
"||",
"protocolPattern",
".",
"test",
"(",
"to",
")",
")",
"{",
"return",
"next",
"(",
")",
";",
"}",
"if",
"(",
"from",
")",
"{",
"if",
"(",
"pathSeparators",
".",
"indexOf",
"(",
"from",
"[",
"from",
".",
"length",
"-",
"1",
"]",
")",
"===",
"-",
"1",
")",
"{",
"from",
"=",
"path",
".",
"dirname",
"(",
"from",
")",
";",
"}",
"return",
"path",
".",
"resolve",
"(",
"from",
",",
"to",
")",
";",
"}",
"else",
"{",
"return",
"path",
".",
"resolve",
"(",
"to",
")",
";",
"}",
"}"
] | Resolves a local filesystem path, relative to a base path.
@param {?string} args.from
The base path to resolve against. If unset, then the current working directory is used.
@param {string} args.to
The path to resolve. This may be absolute or relative. If relative, then it will be resolved
against {@link args.from}
@param {function} args.next
Calls the next plugin, if the path is not a filesystem path.
@returns {string|undefined} | [
"Resolves",
"a",
"local",
"filesystem",
"path",
"relative",
"to",
"a",
"base",
"path",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/FileSystemPlugin.js#L45-L68 | train |
JamesMessinger/json-schema-lib | lib/plugins/FileSystemPlugin.js | readFileSync | function readFileSync (args) {
var file = args.file;
var next = args.next;
if (isUnsupportedPath(file.url)) {
// It's not a filesystem path, so let some other plugin handle it
return next();
}
var filepath = getFileSystemPath(file.url);
inferFileMetadata(file);
return fs.readFileSync(filepath);
} | javascript | function readFileSync (args) {
var file = args.file;
var next = args.next;
if (isUnsupportedPath(file.url)) {
// It's not a filesystem path, so let some other plugin handle it
return next();
}
var filepath = getFileSystemPath(file.url);
inferFileMetadata(file);
return fs.readFileSync(filepath);
} | [
"function",
"readFileSync",
"(",
"args",
")",
"{",
"var",
"file",
"=",
"args",
".",
"file",
";",
"var",
"next",
"=",
"args",
".",
"next",
";",
"if",
"(",
"isUnsupportedPath",
"(",
"file",
".",
"url",
")",
")",
"{",
"return",
"next",
"(",
")",
";",
"}",
"var",
"filepath",
"=",
"getFileSystemPath",
"(",
"file",
".",
"url",
")",
";",
"inferFileMetadata",
"(",
"file",
")",
";",
"return",
"fs",
".",
"readFileSync",
"(",
"filepath",
")",
";",
"}"
] | Synchronously reads a file from the local filesystem.
@param {File} args.file - The {@link File} to read
@param {function} args.next - Calls the next plugin, if the file is not a local filesystem file
@returns {Buffer|undefined} | [
"Synchronously",
"reads",
"a",
"file",
"from",
"the",
"local",
"filesystem",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/FileSystemPlugin.js#L77-L90 | train |
JamesMessinger/json-schema-lib | lib/plugins/FileSystemPlugin.js | inferFileMetadata | function inferFileMetadata (file) {
file.mimeType = lowercase(mime.lookup(file.url) || null);
file.encoding = lowercase(mime.charset(file.mimeType) || null);
} | javascript | function inferFileMetadata (file) {
file.mimeType = lowercase(mime.lookup(file.url) || null);
file.encoding = lowercase(mime.charset(file.mimeType) || null);
} | [
"function",
"inferFileMetadata",
"(",
"file",
")",
"{",
"file",
".",
"mimeType",
"=",
"lowercase",
"(",
"mime",
".",
"lookup",
"(",
"file",
".",
"url",
")",
"||",
"null",
")",
";",
"file",
".",
"encoding",
"=",
"lowercase",
"(",
"mime",
".",
"charset",
"(",
"file",
".",
"mimeType",
")",
"||",
"null",
")",
";",
"}"
] | Infers the file's MIME type and encoding, based on its file extension.
@param {File} file | [
"Infers",
"the",
"file",
"s",
"MIME",
"type",
"and",
"encoding",
"based",
"on",
"its",
"file",
"extension",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/plugins/FileSystemPlugin.js#L131-L134 | train |
JamesMessinger/json-schema-lib | lib/api/PluginHelper/validatePlugins.js | validatePlugins | function validatePlugins (plugins) {
var type = typeOf(plugins);
if (type.hasValue) {
if (type.isArray) {
// Make sure all the items in the array are valid plugins
plugins.forEach(validatePlugin);
}
else {
throw ono('Invalid arguments. Expected an array of plugins.');
}
}
} | javascript | function validatePlugins (plugins) {
var type = typeOf(plugins);
if (type.hasValue) {
if (type.isArray) {
// Make sure all the items in the array are valid plugins
plugins.forEach(validatePlugin);
}
else {
throw ono('Invalid arguments. Expected an array of plugins.');
}
}
} | [
"function",
"validatePlugins",
"(",
"plugins",
")",
"{",
"var",
"type",
"=",
"typeOf",
"(",
"plugins",
")",
";",
"if",
"(",
"type",
".",
"hasValue",
")",
"{",
"if",
"(",
"type",
".",
"isArray",
")",
"{",
"plugins",
".",
"forEach",
"(",
"validatePlugin",
")",
";",
"}",
"else",
"{",
"throw",
"ono",
"(",
"'Invalid arguments. Expected an array of plugins.'",
")",
";",
"}",
"}",
"}"
] | Ensures that a user-supplied value is a valid array of plugins.
An error is thrown if the value is invalid.
@param {*} plugins - The user-supplied value to validate | [
"Ensures",
"that",
"a",
"user",
"-",
"supplied",
"value",
"is",
"a",
"valid",
"array",
"of",
"plugins",
".",
"An",
"error",
"is",
"thrown",
"if",
"the",
"value",
"is",
"invalid",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/PluginHelper/validatePlugins.js#L15-L27 | train |
0of/chinesegen | index.js | generate | function generate (opts) {
var options = opts || {},
genCount = Math.abs(options.count) >>> 0,
// min/max word count in a sentence
minCount = Math.abs(options.minCount) || 5,
maxCount = Math.abs(options.maxCount) || 20,
formater = options.format == '\\uXXXX' ? formatOutput : undefined,
periods = extendPeriod(options.toleratedPeriods || '');
var avail = 0;
var genHelper = function (genFn) {
return formater === undefined ? genFn : function () {
return formatOutput(genFn.apply(undefined, arguments));
};
},
genWords = genHelper(options.freq === true ? freqUsedWordsGen : wordsGen),
wordCountFn = function () {
var count = rand(minCount, maxCount);
return count >= avail ? avail - 1 : count;
},
genPeriod = genHelper(function () {
return periods[rand(0, periods.length)];
}),
genSentences = function (genEachSentenceFn) {
var gen = {
text: '',
total: 0,
sentenceCount: 0
};
while ((avail = genCount - gen.total) > 0) {
gen.total += genEachSentenceFn(gen);
gen.sentenceCount++;
}
return gen;
};
return genSentences(function (gen) {
var currentWordCount = wordCountFn();
gen.text += genWords(currentWordCount);
gen.text += genPeriod();
return currentWordCount + 1;
});
} | javascript | function generate (opts) {
var options = opts || {},
genCount = Math.abs(options.count) >>> 0,
// min/max word count in a sentence
minCount = Math.abs(options.minCount) || 5,
maxCount = Math.abs(options.maxCount) || 20,
formater = options.format == '\\uXXXX' ? formatOutput : undefined,
periods = extendPeriod(options.toleratedPeriods || '');
var avail = 0;
var genHelper = function (genFn) {
return formater === undefined ? genFn : function () {
return formatOutput(genFn.apply(undefined, arguments));
};
},
genWords = genHelper(options.freq === true ? freqUsedWordsGen : wordsGen),
wordCountFn = function () {
var count = rand(minCount, maxCount);
return count >= avail ? avail - 1 : count;
},
genPeriod = genHelper(function () {
return periods[rand(0, periods.length)];
}),
genSentences = function (genEachSentenceFn) {
var gen = {
text: '',
total: 0,
sentenceCount: 0
};
while ((avail = genCount - gen.total) > 0) {
gen.total += genEachSentenceFn(gen);
gen.sentenceCount++;
}
return gen;
};
return genSentences(function (gen) {
var currentWordCount = wordCountFn();
gen.text += genWords(currentWordCount);
gen.text += genPeriod();
return currentWordCount + 1;
});
} | [
"function",
"generate",
"(",
"opts",
")",
"{",
"var",
"options",
"=",
"opts",
"||",
"{",
"}",
",",
"genCount",
"=",
"Math",
".",
"abs",
"(",
"options",
".",
"count",
")",
">>>",
"0",
",",
"minCount",
"=",
"Math",
".",
"abs",
"(",
"options",
".",
"minCount",
")",
"||",
"5",
",",
"maxCount",
"=",
"Math",
".",
"abs",
"(",
"options",
".",
"maxCount",
")",
"||",
"20",
",",
"formater",
"=",
"options",
".",
"format",
"==",
"'\\\\uXXXX'",
"?",
"\\\\",
":",
"undefined",
",",
"formatOutput",
";",
"periods",
"=",
"extendPeriod",
"(",
"options",
".",
"toleratedPeriods",
"||",
"''",
")",
"var",
"avail",
"=",
"0",
";",
"var",
"genHelper",
"=",
"function",
"(",
"genFn",
")",
"{",
"return",
"formater",
"===",
"undefined",
"?",
"genFn",
":",
"function",
"(",
")",
"{",
"return",
"formatOutput",
"(",
"genFn",
".",
"apply",
"(",
"undefined",
",",
"arguments",
")",
")",
";",
"}",
";",
"}",
",",
"genWords",
"=",
"genHelper",
"(",
"options",
".",
"freq",
"===",
"true",
"?",
"freqUsedWordsGen",
":",
"wordsGen",
")",
",",
"wordCountFn",
"=",
"function",
"(",
")",
"{",
"var",
"count",
"=",
"rand",
"(",
"minCount",
",",
"maxCount",
")",
";",
"return",
"count",
">=",
"avail",
"?",
"avail",
"-",
"1",
":",
"count",
";",
"}",
",",
"genPeriod",
"=",
"genHelper",
"(",
"function",
"(",
")",
"{",
"return",
"periods",
"[",
"rand",
"(",
"0",
",",
"periods",
".",
"length",
")",
"]",
";",
"}",
")",
",",
"genSentences",
"=",
"function",
"(",
"genEachSentenceFn",
")",
"{",
"var",
"gen",
"=",
"{",
"text",
":",
"''",
",",
"total",
":",
"0",
",",
"sentenceCount",
":",
"0",
"}",
";",
"while",
"(",
"(",
"avail",
"=",
"genCount",
"-",
"gen",
".",
"total",
")",
">",
"0",
")",
"{",
"gen",
".",
"total",
"+=",
"genEachSentenceFn",
"(",
"gen",
")",
";",
"gen",
".",
"sentenceCount",
"++",
";",
"}",
"return",
"gen",
";",
"}",
";",
"}"
] | generate random paragraph in Chinese
@param {Object} [opts]
@param {Number} [opts.count] the total word count of the generated paragraph
@param {Boolean} [opts.freq] use frequently used words
@param {String} [opts.format] support '\uXXXX'
@param {String} [opts.toleratedPeriods]
@return {Object}
{String} [text] random text
{Number} [total] text total length
{Number} [sentenceCount] sentence count
@public | [
"generate",
"random",
"paragraph",
"in",
"Chinese"
] | fb0dd294950183243edcb83c27e249f129dc9923 | https://github.com/0of/chinesegen/blob/fb0dd294950183243edcb83c27e249f129dc9923/index.js#L21-L67 | train |
0of/chinesegen | index.js | getCharAt | function getCharAt (index) {
var code = this.charCodeAt(index);
// BMP
if (code < 0xD800 || code > 0xDFFF) {
return String.fromCharCode(code);
}
// high surrogate
if (code < 0xDC00) {
// access the low surrogate
var nextCode = this.charCodeAt(index + 1);
if (isNaN(nextCode)) return false;
if (nextCode < 0xDC00 || nextCode > 0xDFFF) return false;
return String.fromCharCode(code, nextCode);
} else {
// low surrogate
return false;
}
} | javascript | function getCharAt (index) {
var code = this.charCodeAt(index);
// BMP
if (code < 0xD800 || code > 0xDFFF) {
return String.fromCharCode(code);
}
// high surrogate
if (code < 0xDC00) {
// access the low surrogate
var nextCode = this.charCodeAt(index + 1);
if (isNaN(nextCode)) return false;
if (nextCode < 0xDC00 || nextCode > 0xDFFF) return false;
return String.fromCharCode(code, nextCode);
} else {
// low surrogate
return false;
}
} | [
"function",
"getCharAt",
"(",
"index",
")",
"{",
"var",
"code",
"=",
"this",
".",
"charCodeAt",
"(",
"index",
")",
";",
"if",
"(",
"code",
"<",
"0xD800",
"||",
"code",
">",
"0xDFFF",
")",
"{",
"return",
"String",
".",
"fromCharCode",
"(",
"code",
")",
";",
"}",
"if",
"(",
"code",
"<",
"0xDC00",
")",
"{",
"var",
"nextCode",
"=",
"this",
".",
"charCodeAt",
"(",
"index",
"+",
"1",
")",
";",
"if",
"(",
"isNaN",
"(",
"nextCode",
")",
")",
"return",
"false",
";",
"if",
"(",
"nextCode",
"<",
"0xDC00",
"||",
"nextCode",
">",
"0xDFFF",
")",
"return",
"false",
";",
"return",
"String",
".",
"fromCharCode",
"(",
"code",
",",
"nextCode",
")",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | no bound checking return false when unknown character or iterating at the low surrogate | [
"no",
"bound",
"checking",
"return",
"false",
"when",
"unknown",
"character",
"or",
"iterating",
"at",
"the",
"low",
"surrogate"
] | fb0dd294950183243edcb83c27e249f129dc9923 | https://github.com/0of/chinesegen/blob/fb0dd294950183243edcb83c27e249f129dc9923/index.js#L87-L107 | train |
JamesMessinger/json-schema-lib | lib/api/File.js | File | function File (schema) {
/**
* The {@link Schema} that this file belongs to.
*
* @type {Schema}
*/
this.schema = schema;
/**
* The file's full (absolute) URL, without any hash
*
* @type {string}
*/
this.url = '';
/**
* The file's data. This can be any data type, including a string, object, array, binary, etc.
*
* @type {*}
*/
this.data = undefined;
/**
* The file's MIME type (e.g. "application/json", "text/html", etc.), if known.
*
* @type {?string}
*/
this.mimeType = undefined;
/**
* The file's encoding (e.g. "utf-8", "iso-8859-2", "windows-1251", etc.), if known
*
* @type {?string}
*/
this.encoding = undefined;
/**
* Internal stuff. Use at your own risk!
*
* @private
*/
this[__internal] = {
/**
* Keeps track of the state of each file as the schema is being read.
*
* @type {number}
*/
state: 0,
};
} | javascript | function File (schema) {
/**
* The {@link Schema} that this file belongs to.
*
* @type {Schema}
*/
this.schema = schema;
/**
* The file's full (absolute) URL, without any hash
*
* @type {string}
*/
this.url = '';
/**
* The file's data. This can be any data type, including a string, object, array, binary, etc.
*
* @type {*}
*/
this.data = undefined;
/**
* The file's MIME type (e.g. "application/json", "text/html", etc.), if known.
*
* @type {?string}
*/
this.mimeType = undefined;
/**
* The file's encoding (e.g. "utf-8", "iso-8859-2", "windows-1251", etc.), if known
*
* @type {?string}
*/
this.encoding = undefined;
/**
* Internal stuff. Use at your own risk!
*
* @private
*/
this[__internal] = {
/**
* Keeps track of the state of each file as the schema is being read.
*
* @type {number}
*/
state: 0,
};
} | [
"function",
"File",
"(",
"schema",
")",
"{",
"this",
".",
"schema",
"=",
"schema",
";",
"this",
".",
"url",
"=",
"''",
";",
"this",
".",
"data",
"=",
"undefined",
";",
"this",
".",
"mimeType",
"=",
"undefined",
";",
"this",
".",
"encoding",
"=",
"undefined",
";",
"this",
"[",
"__internal",
"]",
"=",
"{",
"state",
":",
"0",
",",
"}",
";",
"}"
] | Contains information about a file, such as its path, type, and contents.
@param {Schema} schema - The JSON Schema that the file is part of
@class | [
"Contains",
"information",
"about",
"a",
"file",
"such",
"as",
"its",
"path",
"type",
"and",
"contents",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/File.js#L15-L64 | train |
beebotte/bbt_node | lib/socketio.js | authNeeded | function authNeeded () {
if (args.write === true) {
return true
}
if (args.channel.indexOf('private-') === 0) {
return true
}
if (args.channel.indexOf('presence-') === 0) {
return true
}
return false;
} | javascript | function authNeeded () {
if (args.write === true) {
return true
}
if (args.channel.indexOf('private-') === 0) {
return true
}
if (args.channel.indexOf('presence-') === 0) {
return true
}
return false;
} | [
"function",
"authNeeded",
"(",
")",
"{",
"if",
"(",
"args",
".",
"write",
"===",
"true",
")",
"{",
"return",
"true",
"}",
"if",
"(",
"args",
".",
"channel",
".",
"indexOf",
"(",
"'private-'",
")",
"===",
"0",
")",
"{",
"return",
"true",
"}",
"if",
"(",
"args",
".",
"channel",
".",
"indexOf",
"(",
"'presence-'",
")",
"===",
"0",
")",
"{",
"return",
"true",
"}",
"return",
"false",
";",
"}"
] | Authentication required for write access and for read access to private or presence resources | [
"Authentication",
"required",
"for",
"write",
"access",
"and",
"for",
"read",
"access",
"to",
"private",
"or",
"presence",
"resources"
] | be3fe5d934258866b701e5f2361f219d09506180 | https://github.com/beebotte/bbt_node/blob/be3fe5d934258866b701e5f2361f219d09506180/lib/socketio.js#L236-L251 | train |
claudio-silva/grunt-angular-builder | tasks/middleware/buildForeignScripts.js | BuildForeignScriptsMiddleware | function BuildForeignScriptsMiddleware (context)
{
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
// Do nothing
};
this.trace = function (module)
{
/* jshint unused: vars */
// Do nothing
};
this.build = function (targetScript)
{
// Output the standalone scripts (if any).
if (context.standaloneScripts.length) {
// Debug Build
if (context.options.debugBuild && context.options.debugBuild.enabled) {
var rep = context.options.debugBuild.rebaseDebugUrls;
context.prependOutput += (context.standaloneScripts.map (function (e)
{
var path = e.path.replace (MATCH_PATH_SEP, '/'); // Convert file paths to URLs.
if (rep)
for (var i = 0, m = rep.length; i < m; ++i)
path = path.replace (rep[i].match, rep[i].replaceWith);
if (path) // Ignore empty path; it means that this middleware should not output a script tag.
return util.sprintf ('<script src=\"%\"></script>', path);
return '';
})
.filter (function (x) {return x;}) // Remove empty paths.
.join ('\\\n'));
}
// Release Build
else if (context.options.releaseBuild && context.options.releaseBuild.enabled) {
/** @type {string[]} */
var output = context.standaloneScripts.map (function (e) { return e.content; }).join (NL);
util.writeFile (targetScript, output);
//Note: the ensuing release/debug build step will append to the file created here.
}
}
};
} | javascript | function BuildForeignScriptsMiddleware (context)
{
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
// Do nothing
};
this.trace = function (module)
{
/* jshint unused: vars */
// Do nothing
};
this.build = function (targetScript)
{
// Output the standalone scripts (if any).
if (context.standaloneScripts.length) {
// Debug Build
if (context.options.debugBuild && context.options.debugBuild.enabled) {
var rep = context.options.debugBuild.rebaseDebugUrls;
context.prependOutput += (context.standaloneScripts.map (function (e)
{
var path = e.path.replace (MATCH_PATH_SEP, '/'); // Convert file paths to URLs.
if (rep)
for (var i = 0, m = rep.length; i < m; ++i)
path = path.replace (rep[i].match, rep[i].replaceWith);
if (path) // Ignore empty path; it means that this middleware should not output a script tag.
return util.sprintf ('<script src=\"%\"></script>', path);
return '';
})
.filter (function (x) {return x;}) // Remove empty paths.
.join ('\\\n'));
}
// Release Build
else if (context.options.releaseBuild && context.options.releaseBuild.enabled) {
/** @type {string[]} */
var output = context.standaloneScripts.map (function (e) { return e.content; }).join (NL);
util.writeFile (targetScript, output);
//Note: the ensuing release/debug build step will append to the file created here.
}
}
};
} | [
"function",
"BuildForeignScriptsMiddleware",
"(",
"context",
")",
"{",
"this",
".",
"analyze",
"=",
"function",
"(",
"filesArray",
")",
"{",
"}",
";",
"this",
".",
"trace",
"=",
"function",
"(",
"module",
")",
"{",
"}",
";",
"this",
".",
"build",
"=",
"function",
"(",
"targetScript",
")",
"{",
"if",
"(",
"context",
".",
"standaloneScripts",
".",
"length",
")",
"{",
"if",
"(",
"context",
".",
"options",
".",
"debugBuild",
"&&",
"context",
".",
"options",
".",
"debugBuild",
".",
"enabled",
")",
"{",
"var",
"rep",
"=",
"context",
".",
"options",
".",
"debugBuild",
".",
"rebaseDebugUrls",
";",
"context",
".",
"prependOutput",
"+=",
"(",
"context",
".",
"standaloneScripts",
".",
"map",
"(",
"function",
"(",
"e",
")",
"{",
"var",
"path",
"=",
"e",
".",
"path",
".",
"replace",
"(",
"MATCH_PATH_SEP",
",",
"'/'",
")",
";",
"if",
"(",
"rep",
")",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"m",
"=",
"rep",
".",
"length",
";",
"i",
"<",
"m",
";",
"++",
"i",
")",
"path",
"=",
"path",
".",
"replace",
"(",
"rep",
"[",
"i",
"]",
".",
"match",
",",
"rep",
"[",
"i",
"]",
".",
"replaceWith",
")",
";",
"if",
"(",
"path",
")",
"return",
"util",
".",
"sprintf",
"(",
"'<script src=\\\"%\\\"></script>'",
",",
"\\\"",
")",
";",
"\\\"",
"}",
")",
".",
"path",
"return",
"''",
";",
".",
"filter",
"(",
"function",
"(",
"x",
")",
"{",
"return",
"x",
";",
"}",
")",
")",
";",
"}",
"else",
"join",
"}",
"}",
";",
"}"
] | Builds non-angular-module scripts.
On release builds, this extension saves all non-module script files required by the application into a
single output file, in the correct loading order.
On debug builds, it appends SCRIPT tags to the head of the html document, which will load the original
source scripts in the correct order.
@constructor
@implements {MiddlewareInterface}
@param {Context} context The execution context for the middleware stack. | [
"Builds",
"non",
"-",
"angular",
"-",
"module",
"scripts",
"."
] | 0aa4232257e4ae95d0aa9258ff0a91395383d8b7 | https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/buildForeignScripts.js#L35-L88 | train |
matteodelabre/midijs | lib/file/parser/header.js | parseHeader | function parseHeader(cursor) {
var chunk, fileType, trackCount, timeDivision;
try {
chunk = parseChunk('MThd', cursor);
} catch (e) {
if (e instanceof error.MIDIParserError) {
throw new error.MIDINotMIDIError();
}
}
fileType = chunk.readUInt16BE();
trackCount = chunk.readUInt16BE();
timeDivision = chunk.readUInt16BE();
if ((timeDivision & 0x8000) === 0) {
timeDivision = timeDivision & 0x7FFF;
} else {
throw new error.MIDINotSupportedError(
'Expressing time in SMPTE format is not supported yet'
);
}
return new Header(fileType, trackCount, timeDivision);
} | javascript | function parseHeader(cursor) {
var chunk, fileType, trackCount, timeDivision;
try {
chunk = parseChunk('MThd', cursor);
} catch (e) {
if (e instanceof error.MIDIParserError) {
throw new error.MIDINotMIDIError();
}
}
fileType = chunk.readUInt16BE();
trackCount = chunk.readUInt16BE();
timeDivision = chunk.readUInt16BE();
if ((timeDivision & 0x8000) === 0) {
timeDivision = timeDivision & 0x7FFF;
} else {
throw new error.MIDINotSupportedError(
'Expressing time in SMPTE format is not supported yet'
);
}
return new Header(fileType, trackCount, timeDivision);
} | [
"function",
"parseHeader",
"(",
"cursor",
")",
"{",
"var",
"chunk",
",",
"fileType",
",",
"trackCount",
",",
"timeDivision",
";",
"try",
"{",
"chunk",
"=",
"parseChunk",
"(",
"'MThd'",
",",
"cursor",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"e",
"instanceof",
"error",
".",
"MIDIParserError",
")",
"{",
"throw",
"new",
"error",
".",
"MIDINotMIDIError",
"(",
")",
";",
"}",
"}",
"fileType",
"=",
"chunk",
".",
"readUInt16BE",
"(",
")",
";",
"trackCount",
"=",
"chunk",
".",
"readUInt16BE",
"(",
")",
";",
"timeDivision",
"=",
"chunk",
".",
"readUInt16BE",
"(",
")",
";",
"if",
"(",
"(",
"timeDivision",
"&",
"0x8000",
")",
"===",
"0",
")",
"{",
"timeDivision",
"=",
"timeDivision",
"&",
"0x7FFF",
";",
"}",
"else",
"{",
"throw",
"new",
"error",
".",
"MIDINotSupportedError",
"(",
"'Expressing time in SMPTE format is not supported yet'",
")",
";",
"}",
"return",
"new",
"Header",
"(",
"fileType",
",",
"trackCount",
",",
"timeDivision",
")",
";",
"}"
] | Parse a MIDI header chunk
@param {module:buffercursor} cursor Buffer to parse
@throws {module:midijs/lib/error~MIDINotMIDIError}
If the file is not a MIDI file
@throws {module:midijs/lib/error~MIDIParserError}
If time is expressed in unsupported SMPTE format
@return {module:midijs/lib/file/header~Header} Parsed header | [
"Parse",
"a",
"MIDI",
"header",
"chunk"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file/parser/header.js#L17-L41 | train |
matteodelabre/midijs | lib/file.js | File | function File(data, callback) {
stream.Duplex.call(this);
this._header = new Header();
this._tracks = [];
if (data && buffer.Buffer.isBuffer(data)) {
this.setData(data, callback || noop);
}
} | javascript | function File(data, callback) {
stream.Duplex.call(this);
this._header = new Header();
this._tracks = [];
if (data && buffer.Buffer.isBuffer(data)) {
this.setData(data, callback || noop);
}
} | [
"function",
"File",
"(",
"data",
",",
"callback",
")",
"{",
"stream",
".",
"Duplex",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"_header",
"=",
"new",
"Header",
"(",
")",
";",
"this",
".",
"_tracks",
"=",
"[",
"]",
";",
"if",
"(",
"data",
"&&",
"buffer",
".",
"Buffer",
".",
"isBuffer",
"(",
"data",
")",
")",
"{",
"this",
".",
"setData",
"(",
"data",
",",
"callback",
"||",
"noop",
")",
";",
"}",
"}"
] | Construct a new File
@class File
@extends stream.Duplex
@classdesc Parse and encode MIDI data
@param {Buffer} [data] Shortcut for calling setData()
@param {Function} [callback] Callback for setData() shortcut | [
"Construct",
"a",
"new",
"File"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/file.js#L32-L41 | train |
Skellington-Closet/skellington | lib/debug-logger.js | defaultFormatter | function defaultFormatter (message) {
return `team: ${message.team} channel: ${message.channel} user: ${message.user} text: ${message.text}`
} | javascript | function defaultFormatter (message) {
return `team: ${message.team} channel: ${message.channel} user: ${message.user} text: ${message.text}`
} | [
"function",
"defaultFormatter",
"(",
"message",
")",
"{",
"return",
"`",
"${",
"message",
".",
"team",
"}",
"${",
"message",
".",
"channel",
"}",
"${",
"message",
".",
"user",
"}",
"${",
"message",
".",
"text",
"}",
"`",
"}"
] | Default log message formatter
@param message
@returns {string} | [
"Default",
"log",
"message",
"formatter"
] | fa660c0864ab13188c0b663cd57ccbcc979683f1 | https://github.com/Skellington-Closet/skellington/blob/fa660c0864ab13188c0b663cd57ccbcc979683f1/lib/debug-logger.js#L42-L44 | train |
claudio-silva/grunt-angular-builder | tasks/middleware/makeReleaseBuild.js | MakeReleaseBuildMiddleware | function MakeReleaseBuildMiddleware (context)
{
var options = context.options.releaseBuild;
/**
* Grunt's verbose output API.
* @type {Object}
*/
var verboseOut = context.grunt.log.verbose;
/** @type {string[]} */
var traceOutput = [];
//--------------------------------------------------------------------------------------------------------------------
// EVENTS
//--------------------------------------------------------------------------------------------------------------------
context.listen (ContextEvent.ON_AFTER_ANALYZE, function ()
{
if (options.enabled) {
var space = context.verbose ? NL : '';
writeln ('%Generating the <cyan>release</cyan> build...%', space, space);
scanForOptimization (context);
}
});
context.listen (ContextEvent.ON_BEFORE_DEPS, function (/*ModuleDef*/ module)
{
if (options.enabled) {
if (module.nonOptimizedContainer)
traceOutput.push ('(function () {\n');
}
});
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
// Do nothing
};
this.trace = function (/*ModuleDef*/ module)
{
if (!options.enabled) return;
if (module.nonOptimizedContainer)
traceOutput.push ('\n}) ();');
// Fist process the head module declaration.
if (!module.head)
return util.warn ('Module <cyan>%</cyan> has no declaration.', module.name);
var headPath = module.headPath;
var head, headWasOutput = context.outputtedFiles[headPath];
if (!headWasOutput) {
head = module.optimize ?
optimize (module.head, headPath, module)
: {status: STAT.INDENTED, data: module.head};
context.outputtedFiles[headPath] = true;
}
var isEmpty = headWasOutput ? true : sourceExtract.matchWhiteSpaceOrComments (head.data);
outputModuleHeader (module, headWasOutput, headPath);
if (!headWasOutput) {
// Prevent the creation of an empty (or comments-only) self-invoking function.
// In that case, the head content will be output without a wrapping closure.
if (!module.bodies.length && isEmpty) {
// Output the comments (if any).
if (head.data.trim ())
traceOutput.push (head.data);
// Output a module declaration with no definitions.
traceOutput.push (sprintf ('angular.module (\'%\', %);%', module.name,
util.toQuotedList (module.requires), options.moduleFooter)
);
return;
}
}
// Enclose the module contents in a self-invoking function which receives the module instance as an argument.
if (module.optimize)
// Begin closure.
traceOutput.push ('(function (' + options.moduleVar + ') {\n');
// Insert module declaration.
if (!headWasOutput)
traceOutput.push (conditionalIndent (head));
outputModuleDefinitions (module, headWasOutput);
// End closure.
if (module.optimize)
traceOutput.push (sprintf ('\n}) (angular.module (\'%\', %%));%', module.name,
util.toQuotedList (module.requires), module.configFn || '', options.moduleFooter));
};
this.build = function (targetScript)
{
if (!options.enabled) return;
if (context.prependOutput)
traceOutput.unshift (context.prependOutput);
if (context.appendOutput)
traceOutput.push (context.appendOutput);
util.writeFile (targetScript, traceOutput.join (NL));
};
//--------------------------------------------------------------------------------------------------------------------
// PRIVATE
//--------------------------------------------------------------------------------------------------------------------
/**
* Outputs a module information header.
*
* @param {ModuleDef} module
* @param {boolean} headWasOutput
* @param {string} headPath
*/
function outputModuleHeader (module, headWasOutput, headPath)
{
if (module.bodies.length || !headWasOutput) {
traceOutput.push (LINE2, '// Module: ' + module.name, '// Optimized: ' + (module.optimize ? 'Yes' : 'No'));
if (!headWasOutput)
traceOutput.push ('// File: ' + headPath);
else {
for (var i = 0, m = module.bodies.length; i < m; ++i) {
var bodyPath = module.bodyPaths[i];
// Find first body who's corresponding file was not yet output.
if (!context.outputtedFiles[bodyPath]) {
traceOutput.push ('// File: ' + bodyPath);
break;
}
}
}
traceOutput.push (LINE2, '');
}
}
/**
* Insert additional module definitions.
*
* @param {ModuleDef} module
* @param {boolean} headWasOutput
*/
function outputModuleDefinitions (module, headWasOutput)
{
for (var i = 0, m = module.bodies.length; i < m; ++i) {
var bodyPath = module.bodyPaths[i];
if (!bodyPath)
console.log (module.name, i, module.bodies.length, module.bodyPaths);
// Skip bodies who's corresponding file was already output.
if (context.outputtedFiles[bodyPath])
continue;
context.outputtedFiles[bodyPath] = true;
var body = module.optimize ?
optimize (module.bodies[i], bodyPath, module)
: {status: STAT.INDENTED, data: module.bodies[i]};
if (i || !headWasOutput)
traceOutput.push (LINE, '// File: ' + bodyPath, LINE, '');
traceOutput.push (conditionalIndent (body));
}
}
/**
* Calls sourceTrans.optimize() and handles the result.
*
* @param {string} source
* @param {string} path For error messages.
* @param {ModuleDef} module
* @returns {OperationResult} The transformed source code.
* @throws Error Sanity check.
*/
function optimize (source, path, module)
{
var result = sourceTrans.optimize (source, module.name, options.moduleVar);
var stat = sourceTrans.TRANS_STAT;
switch (result.status) {
case stat.OK:
//----------------------------------------------------------
// Module already enclosed in a closure with no arguments.
//----------------------------------------------------------
return /** @type {OperationResult} */ {
status: STAT.INDENTED,
data: sourceTrans.renameModuleRefExps (module, options.indent + result.data, options.moduleVar)
};
case stat.NO_CLOSURE_FOUND:
//----------------------------------------------------------
// Unwrapped source code.
// It must be validated to make sure it's safe.
//----------------------------------------------------------
if (path)
verboseOut.write ('Validating ' + path.cyan + '...');
var valid = sourceTrans.validateUnwrappedCode (source);
if (valid)
// The code passed validation.
verboseOut.ok ();
else {
verboseOut.writeln ('FAILED'.yellow);
warnAboutGlobalCode (valid, path);
// If --force, continue.
}
// Either the code is valid or --force was used, so process it.
return /** @type {OperationResult} */ {
status: STAT.OK,
data: sourceTrans.renameModuleRefExps (module, source, options.moduleVar)
};
case stat.RENAME_REQUIRED:
//----------------------------------------------------------
// Module already enclosed in a closure, with its reference
// passed in as the function's argument.
//----------------------------------------------------------
/** @type {ModuleClosureInfo} */
var modInfo = result.data;
if (!options.renameModuleRefs) {
warn ('The module variable reference <cyan>%</cyan> doesn\'t match the preset name on the config setting ' +
'<cyan>moduleVar=\'%\'</cyan>.%%%',
modInfo.moduleVar, options.moduleVar, NL, reportErrorLocation (path),
getExplanation ('Either rename the variable or enable <cyan>renameModuleRefs</cyan>.')
);
// If --force, continue.
}
return /** @type {OperationResult} */ {
status: STAT.OK,
data: sourceTrans.renameModuleVariableRefs (modInfo.closureBody, modInfo.moduleVar, options.moduleVar)
};
case stat.INVALID_DECLARATION:
warn ('Wrong module declaration: <cyan>%</cyan>', result.data);
// If --force, continue.
break;
default:
throw new Error ('Optimize failed. It returned ' + JSON.stringify (result));
}
// Optimization failed. Return the unaltered source code.
return /** @type {OperationResult} */ {status: STAT.OK, data: source};
}
/**
* Returns the given text indented unless it was already indented.
* @param {OperationResult} result
* @return {string}
*/
function conditionalIndent (result)
{
return result.status === STAT.INDENTED ? result.data : indent (result.data, 1, options.indent);
}
/**
* Isses a warning about problematic code found on the global scope.
* @param {Object} sandbox
* @param {string} path
*/
function warnAboutGlobalCode (sandbox, path)
{
var msg = csprintf ('yellow', 'Incompatible code found on the global scope!'.red + NL +
(path ? reportErrorLocation (path) : '') +
getExplanation (
'This kind of code will behave differently between release and debug builds.' + NL +
'You should wrap it in a self-invoking function and/or assign global variables/functions ' +
'directly to the window object.'
)
);
if (context.verbose) {
var found = false;
util.forEachProperty (sandbox, function (k, v)
{
if (!found) {
found = true;
msg += ' Detected globals:'.yellow + NL;
}
msg += (typeof v === 'function' ? ' function '.blue : ' var '.blue) + k.cyan + NL;
});
}
warn (msg + '>>'.yellow);
}
} | javascript | function MakeReleaseBuildMiddleware (context)
{
var options = context.options.releaseBuild;
/**
* Grunt's verbose output API.
* @type {Object}
*/
var verboseOut = context.grunt.log.verbose;
/** @type {string[]} */
var traceOutput = [];
//--------------------------------------------------------------------------------------------------------------------
// EVENTS
//--------------------------------------------------------------------------------------------------------------------
context.listen (ContextEvent.ON_AFTER_ANALYZE, function ()
{
if (options.enabled) {
var space = context.verbose ? NL : '';
writeln ('%Generating the <cyan>release</cyan> build...%', space, space);
scanForOptimization (context);
}
});
context.listen (ContextEvent.ON_BEFORE_DEPS, function (/*ModuleDef*/ module)
{
if (options.enabled) {
if (module.nonOptimizedContainer)
traceOutput.push ('(function () {\n');
}
});
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
// Do nothing
};
this.trace = function (/*ModuleDef*/ module)
{
if (!options.enabled) return;
if (module.nonOptimizedContainer)
traceOutput.push ('\n}) ();');
// Fist process the head module declaration.
if (!module.head)
return util.warn ('Module <cyan>%</cyan> has no declaration.', module.name);
var headPath = module.headPath;
var head, headWasOutput = context.outputtedFiles[headPath];
if (!headWasOutput) {
head = module.optimize ?
optimize (module.head, headPath, module)
: {status: STAT.INDENTED, data: module.head};
context.outputtedFiles[headPath] = true;
}
var isEmpty = headWasOutput ? true : sourceExtract.matchWhiteSpaceOrComments (head.data);
outputModuleHeader (module, headWasOutput, headPath);
if (!headWasOutput) {
// Prevent the creation of an empty (or comments-only) self-invoking function.
// In that case, the head content will be output without a wrapping closure.
if (!module.bodies.length && isEmpty) {
// Output the comments (if any).
if (head.data.trim ())
traceOutput.push (head.data);
// Output a module declaration with no definitions.
traceOutput.push (sprintf ('angular.module (\'%\', %);%', module.name,
util.toQuotedList (module.requires), options.moduleFooter)
);
return;
}
}
// Enclose the module contents in a self-invoking function which receives the module instance as an argument.
if (module.optimize)
// Begin closure.
traceOutput.push ('(function (' + options.moduleVar + ') {\n');
// Insert module declaration.
if (!headWasOutput)
traceOutput.push (conditionalIndent (head));
outputModuleDefinitions (module, headWasOutput);
// End closure.
if (module.optimize)
traceOutput.push (sprintf ('\n}) (angular.module (\'%\', %%));%', module.name,
util.toQuotedList (module.requires), module.configFn || '', options.moduleFooter));
};
this.build = function (targetScript)
{
if (!options.enabled) return;
if (context.prependOutput)
traceOutput.unshift (context.prependOutput);
if (context.appendOutput)
traceOutput.push (context.appendOutput);
util.writeFile (targetScript, traceOutput.join (NL));
};
//--------------------------------------------------------------------------------------------------------------------
// PRIVATE
//--------------------------------------------------------------------------------------------------------------------
/**
* Outputs a module information header.
*
* @param {ModuleDef} module
* @param {boolean} headWasOutput
* @param {string} headPath
*/
function outputModuleHeader (module, headWasOutput, headPath)
{
if (module.bodies.length || !headWasOutput) {
traceOutput.push (LINE2, '// Module: ' + module.name, '// Optimized: ' + (module.optimize ? 'Yes' : 'No'));
if (!headWasOutput)
traceOutput.push ('// File: ' + headPath);
else {
for (var i = 0, m = module.bodies.length; i < m; ++i) {
var bodyPath = module.bodyPaths[i];
// Find first body who's corresponding file was not yet output.
if (!context.outputtedFiles[bodyPath]) {
traceOutput.push ('// File: ' + bodyPath);
break;
}
}
}
traceOutput.push (LINE2, '');
}
}
/**
* Insert additional module definitions.
*
* @param {ModuleDef} module
* @param {boolean} headWasOutput
*/
function outputModuleDefinitions (module, headWasOutput)
{
for (var i = 0, m = module.bodies.length; i < m; ++i) {
var bodyPath = module.bodyPaths[i];
if (!bodyPath)
console.log (module.name, i, module.bodies.length, module.bodyPaths);
// Skip bodies who's corresponding file was already output.
if (context.outputtedFiles[bodyPath])
continue;
context.outputtedFiles[bodyPath] = true;
var body = module.optimize ?
optimize (module.bodies[i], bodyPath, module)
: {status: STAT.INDENTED, data: module.bodies[i]};
if (i || !headWasOutput)
traceOutput.push (LINE, '// File: ' + bodyPath, LINE, '');
traceOutput.push (conditionalIndent (body));
}
}
/**
* Calls sourceTrans.optimize() and handles the result.
*
* @param {string} source
* @param {string} path For error messages.
* @param {ModuleDef} module
* @returns {OperationResult} The transformed source code.
* @throws Error Sanity check.
*/
function optimize (source, path, module)
{
var result = sourceTrans.optimize (source, module.name, options.moduleVar);
var stat = sourceTrans.TRANS_STAT;
switch (result.status) {
case stat.OK:
//----------------------------------------------------------
// Module already enclosed in a closure with no arguments.
//----------------------------------------------------------
return /** @type {OperationResult} */ {
status: STAT.INDENTED,
data: sourceTrans.renameModuleRefExps (module, options.indent + result.data, options.moduleVar)
};
case stat.NO_CLOSURE_FOUND:
//----------------------------------------------------------
// Unwrapped source code.
// It must be validated to make sure it's safe.
//----------------------------------------------------------
if (path)
verboseOut.write ('Validating ' + path.cyan + '...');
var valid = sourceTrans.validateUnwrappedCode (source);
if (valid)
// The code passed validation.
verboseOut.ok ();
else {
verboseOut.writeln ('FAILED'.yellow);
warnAboutGlobalCode (valid, path);
// If --force, continue.
}
// Either the code is valid or --force was used, so process it.
return /** @type {OperationResult} */ {
status: STAT.OK,
data: sourceTrans.renameModuleRefExps (module, source, options.moduleVar)
};
case stat.RENAME_REQUIRED:
//----------------------------------------------------------
// Module already enclosed in a closure, with its reference
// passed in as the function's argument.
//----------------------------------------------------------
/** @type {ModuleClosureInfo} */
var modInfo = result.data;
if (!options.renameModuleRefs) {
warn ('The module variable reference <cyan>%</cyan> doesn\'t match the preset name on the config setting ' +
'<cyan>moduleVar=\'%\'</cyan>.%%%',
modInfo.moduleVar, options.moduleVar, NL, reportErrorLocation (path),
getExplanation ('Either rename the variable or enable <cyan>renameModuleRefs</cyan>.')
);
// If --force, continue.
}
return /** @type {OperationResult} */ {
status: STAT.OK,
data: sourceTrans.renameModuleVariableRefs (modInfo.closureBody, modInfo.moduleVar, options.moduleVar)
};
case stat.INVALID_DECLARATION:
warn ('Wrong module declaration: <cyan>%</cyan>', result.data);
// If --force, continue.
break;
default:
throw new Error ('Optimize failed. It returned ' + JSON.stringify (result));
}
// Optimization failed. Return the unaltered source code.
return /** @type {OperationResult} */ {status: STAT.OK, data: source};
}
/**
* Returns the given text indented unless it was already indented.
* @param {OperationResult} result
* @return {string}
*/
function conditionalIndent (result)
{
return result.status === STAT.INDENTED ? result.data : indent (result.data, 1, options.indent);
}
/**
* Isses a warning about problematic code found on the global scope.
* @param {Object} sandbox
* @param {string} path
*/
function warnAboutGlobalCode (sandbox, path)
{
var msg = csprintf ('yellow', 'Incompatible code found on the global scope!'.red + NL +
(path ? reportErrorLocation (path) : '') +
getExplanation (
'This kind of code will behave differently between release and debug builds.' + NL +
'You should wrap it in a self-invoking function and/or assign global variables/functions ' +
'directly to the window object.'
)
);
if (context.verbose) {
var found = false;
util.forEachProperty (sandbox, function (k, v)
{
if (!found) {
found = true;
msg += ' Detected globals:'.yellow + NL;
}
msg += (typeof v === 'function' ? ' function '.blue : ' var '.blue) + k.cyan + NL;
});
}
warn (msg + '>>'.yellow);
}
} | [
"function",
"MakeReleaseBuildMiddleware",
"(",
"context",
")",
"{",
"var",
"options",
"=",
"context",
".",
"options",
".",
"releaseBuild",
";",
"var",
"verboseOut",
"=",
"context",
".",
"grunt",
".",
"log",
".",
"verbose",
";",
"var",
"traceOutput",
"=",
"[",
"]",
";",
"context",
".",
"listen",
"(",
"ContextEvent",
".",
"ON_AFTER_ANALYZE",
",",
"function",
"(",
")",
"{",
"if",
"(",
"options",
".",
"enabled",
")",
"{",
"var",
"space",
"=",
"context",
".",
"verbose",
"?",
"NL",
":",
"''",
";",
"writeln",
"(",
"'%Generating the <cyan>release</cyan> build...%'",
",",
"space",
",",
"space",
")",
";",
"scanForOptimization",
"(",
"context",
")",
";",
"}",
"}",
")",
";",
"context",
".",
"listen",
"(",
"ContextEvent",
".",
"ON_BEFORE_DEPS",
",",
"function",
"(",
"module",
")",
"{",
"if",
"(",
"options",
".",
"enabled",
")",
"{",
"if",
"(",
"module",
".",
"nonOptimizedContainer",
")",
"traceOutput",
".",
"push",
"(",
"'(function () {\\n'",
")",
";",
"}",
"}",
")",
";",
"\\n",
"this",
".",
"analyze",
"=",
"function",
"(",
"filesArray",
")",
"{",
"}",
";",
"this",
".",
"trace",
"=",
"function",
"(",
"module",
")",
"{",
"if",
"(",
"!",
"options",
".",
"enabled",
")",
"return",
";",
"if",
"(",
"module",
".",
"nonOptimizedContainer",
")",
"traceOutput",
".",
"push",
"(",
"'\\n}) ();'",
")",
";",
"\\n",
"if",
"(",
"!",
"module",
".",
"head",
")",
"return",
"util",
".",
"warn",
"(",
"'Module <cyan>%</cyan> has no declaration.'",
",",
"module",
".",
"name",
")",
";",
"var",
"headPath",
"=",
"module",
".",
"headPath",
";",
"var",
"head",
",",
"headWasOutput",
"=",
"context",
".",
"outputtedFiles",
"[",
"headPath",
"]",
";",
"if",
"(",
"!",
"headWasOutput",
")",
"{",
"head",
"=",
"module",
".",
"optimize",
"?",
"optimize",
"(",
"module",
".",
"head",
",",
"headPath",
",",
"module",
")",
":",
"{",
"status",
":",
"STAT",
".",
"INDENTED",
",",
"data",
":",
"module",
".",
"head",
"}",
";",
"context",
".",
"outputtedFiles",
"[",
"headPath",
"]",
"=",
"true",
";",
"}",
"var",
"isEmpty",
"=",
"headWasOutput",
"?",
"true",
":",
"sourceExtract",
".",
"matchWhiteSpaceOrComments",
"(",
"head",
".",
"data",
")",
";",
"outputModuleHeader",
"(",
"module",
",",
"headWasOutput",
",",
"headPath",
")",
";",
"if",
"(",
"!",
"headWasOutput",
")",
"{",
"if",
"(",
"!",
"module",
".",
"bodies",
".",
"length",
"&&",
"isEmpty",
")",
"{",
"if",
"(",
"head",
".",
"data",
".",
"trim",
"(",
")",
")",
"traceOutput",
".",
"push",
"(",
"head",
".",
"data",
")",
";",
"traceOutput",
".",
"push",
"(",
"sprintf",
"(",
"'angular.module (\\'%\\', %);%'",
",",
"\\'",
",",
"\\'",
",",
"module",
".",
"name",
")",
")",
";",
"util",
".",
"toQuotedList",
"(",
"module",
".",
"requires",
")",
"}",
"}",
"options",
".",
"moduleFooter",
"return",
";",
"if",
"(",
"module",
".",
"optimize",
")",
"traceOutput",
".",
"push",
"(",
"'(function ('",
"+",
"options",
".",
"moduleVar",
"+",
"') {\\n'",
")",
";",
"}",
";",
"\\n",
"if",
"(",
"!",
"headWasOutput",
")",
"traceOutput",
".",
"push",
"(",
"conditionalIndent",
"(",
"head",
")",
")",
";",
"outputModuleDefinitions",
"(",
"module",
",",
"headWasOutput",
")",
";",
"if",
"(",
"module",
".",
"optimize",
")",
"traceOutput",
".",
"push",
"(",
"sprintf",
"(",
"'\\n}) (angular.module (\\'%\\', %%));%'",
",",
"\\n",
",",
"\\'",
",",
"\\'",
",",
"module",
".",
"name",
")",
")",
";",
"util",
".",
"toQuotedList",
"(",
"module",
".",
"requires",
")",
"}"
] | Saves all script files required by the specified module into a single output file, in the correct
loading order. This is used on release builds.
@constructor
@implements {MiddlewareInterface}
@param {Context} context The execution context for the middleware stack. | [
"Saves",
"all",
"script",
"files",
"required",
"by",
"the",
"specified",
"module",
"into",
"a",
"single",
"output",
"file",
"in",
"the",
"correct",
"loading",
"order",
".",
"This",
"is",
"used",
"on",
"release",
"builds",
"."
] | 0aa4232257e4ae95d0aa9258ff0a91395383d8b7 | https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/makeReleaseBuild.js#L133-L426 | train |
claudio-silva/grunt-angular-builder | tasks/middleware/makeReleaseBuild.js | outputModuleDefinitions | function outputModuleDefinitions (module, headWasOutput)
{
for (var i = 0, m = module.bodies.length; i < m; ++i) {
var bodyPath = module.bodyPaths[i];
if (!bodyPath)
console.log (module.name, i, module.bodies.length, module.bodyPaths);
// Skip bodies who's corresponding file was already output.
if (context.outputtedFiles[bodyPath])
continue;
context.outputtedFiles[bodyPath] = true;
var body = module.optimize ?
optimize (module.bodies[i], bodyPath, module)
: {status: STAT.INDENTED, data: module.bodies[i]};
if (i || !headWasOutput)
traceOutput.push (LINE, '// File: ' + bodyPath, LINE, '');
traceOutput.push (conditionalIndent (body));
}
} | javascript | function outputModuleDefinitions (module, headWasOutput)
{
for (var i = 0, m = module.bodies.length; i < m; ++i) {
var bodyPath = module.bodyPaths[i];
if (!bodyPath)
console.log (module.name, i, module.bodies.length, module.bodyPaths);
// Skip bodies who's corresponding file was already output.
if (context.outputtedFiles[bodyPath])
continue;
context.outputtedFiles[bodyPath] = true;
var body = module.optimize ?
optimize (module.bodies[i], bodyPath, module)
: {status: STAT.INDENTED, data: module.bodies[i]};
if (i || !headWasOutput)
traceOutput.push (LINE, '// File: ' + bodyPath, LINE, '');
traceOutput.push (conditionalIndent (body));
}
} | [
"function",
"outputModuleDefinitions",
"(",
"module",
",",
"headWasOutput",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"m",
"=",
"module",
".",
"bodies",
".",
"length",
";",
"i",
"<",
"m",
";",
"++",
"i",
")",
"{",
"var",
"bodyPath",
"=",
"module",
".",
"bodyPaths",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"bodyPath",
")",
"console",
".",
"log",
"(",
"module",
".",
"name",
",",
"i",
",",
"module",
".",
"bodies",
".",
"length",
",",
"module",
".",
"bodyPaths",
")",
";",
"if",
"(",
"context",
".",
"outputtedFiles",
"[",
"bodyPath",
"]",
")",
"continue",
";",
"context",
".",
"outputtedFiles",
"[",
"bodyPath",
"]",
"=",
"true",
";",
"var",
"body",
"=",
"module",
".",
"optimize",
"?",
"optimize",
"(",
"module",
".",
"bodies",
"[",
"i",
"]",
",",
"bodyPath",
",",
"module",
")",
":",
"{",
"status",
":",
"STAT",
".",
"INDENTED",
",",
"data",
":",
"module",
".",
"bodies",
"[",
"i",
"]",
"}",
";",
"if",
"(",
"i",
"||",
"!",
"headWasOutput",
")",
"traceOutput",
".",
"push",
"(",
"LINE",
",",
"'// File: '",
"+",
"bodyPath",
",",
"LINE",
",",
"''",
")",
";",
"traceOutput",
".",
"push",
"(",
"conditionalIndent",
"(",
"body",
")",
")",
";",
"}",
"}"
] | Insert additional module definitions.
@param {ModuleDef} module
@param {boolean} headWasOutput | [
"Insert",
"additional",
"module",
"definitions",
"."
] | 0aa4232257e4ae95d0aa9258ff0a91395383d8b7 | https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/makeReleaseBuild.js#L281-L300 | train |
claudio-silva/grunt-angular-builder | tasks/middleware/makeReleaseBuild.js | conditionalIndent | function conditionalIndent (result)
{
return result.status === STAT.INDENTED ? result.data : indent (result.data, 1, options.indent);
} | javascript | function conditionalIndent (result)
{
return result.status === STAT.INDENTED ? result.data : indent (result.data, 1, options.indent);
} | [
"function",
"conditionalIndent",
"(",
"result",
")",
"{",
"return",
"result",
".",
"status",
"===",
"STAT",
".",
"INDENTED",
"?",
"result",
".",
"data",
":",
"indent",
"(",
"result",
".",
"data",
",",
"1",
",",
"options",
".",
"indent",
")",
";",
"}"
] | Returns the given text indented unless it was already indented.
@param {OperationResult} result
@return {string} | [
"Returns",
"the",
"given",
"text",
"indented",
"unless",
"it",
"was",
"already",
"indented",
"."
] | 0aa4232257e4ae95d0aa9258ff0a91395383d8b7 | https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/makeReleaseBuild.js#L393-L396 | train |
claudio-silva/grunt-angular-builder | tasks/middleware/makeReleaseBuild.js | warnAboutGlobalCode | function warnAboutGlobalCode (sandbox, path)
{
var msg = csprintf ('yellow', 'Incompatible code found on the global scope!'.red + NL +
(path ? reportErrorLocation (path) : '') +
getExplanation (
'This kind of code will behave differently between release and debug builds.' + NL +
'You should wrap it in a self-invoking function and/or assign global variables/functions ' +
'directly to the window object.'
)
);
if (context.verbose) {
var found = false;
util.forEachProperty (sandbox, function (k, v)
{
if (!found) {
found = true;
msg += ' Detected globals:'.yellow + NL;
}
msg += (typeof v === 'function' ? ' function '.blue : ' var '.blue) + k.cyan + NL;
});
}
warn (msg + '>>'.yellow);
} | javascript | function warnAboutGlobalCode (sandbox, path)
{
var msg = csprintf ('yellow', 'Incompatible code found on the global scope!'.red + NL +
(path ? reportErrorLocation (path) : '') +
getExplanation (
'This kind of code will behave differently between release and debug builds.' + NL +
'You should wrap it in a self-invoking function and/or assign global variables/functions ' +
'directly to the window object.'
)
);
if (context.verbose) {
var found = false;
util.forEachProperty (sandbox, function (k, v)
{
if (!found) {
found = true;
msg += ' Detected globals:'.yellow + NL;
}
msg += (typeof v === 'function' ? ' function '.blue : ' var '.blue) + k.cyan + NL;
});
}
warn (msg + '>>'.yellow);
} | [
"function",
"warnAboutGlobalCode",
"(",
"sandbox",
",",
"path",
")",
"{",
"var",
"msg",
"=",
"csprintf",
"(",
"'yellow'",
",",
"'Incompatible code found on the global scope!'",
".",
"red",
"+",
"NL",
"+",
"(",
"path",
"?",
"reportErrorLocation",
"(",
"path",
")",
":",
"''",
")",
"+",
"getExplanation",
"(",
"'This kind of code will behave differently between release and debug builds.'",
"+",
"NL",
"+",
"'You should wrap it in a self-invoking function and/or assign global variables/functions '",
"+",
"'directly to the window object.'",
")",
")",
";",
"if",
"(",
"context",
".",
"verbose",
")",
"{",
"var",
"found",
"=",
"false",
";",
"util",
".",
"forEachProperty",
"(",
"sandbox",
",",
"function",
"(",
"k",
",",
"v",
")",
"{",
"if",
"(",
"!",
"found",
")",
"{",
"found",
"=",
"true",
";",
"msg",
"+=",
"' Detected globals:'",
".",
"yellow",
"+",
"NL",
";",
"}",
"msg",
"+=",
"(",
"typeof",
"v",
"===",
"'function'",
"?",
"' function '",
".",
"blue",
":",
"' var '",
".",
"blue",
")",
"+",
"k",
".",
"cyan",
"+",
"NL",
";",
"}",
")",
";",
"}",
"warn",
"(",
"msg",
"+",
"'>>'",
".",
"yellow",
")",
";",
"}"
] | Isses a warning about problematic code found on the global scope.
@param {Object} sandbox
@param {string} path | [
"Isses",
"a",
"warning",
"about",
"problematic",
"code",
"found",
"on",
"the",
"global",
"scope",
"."
] | 0aa4232257e4ae95d0aa9258ff0a91395383d8b7 | https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/makeReleaseBuild.js#L403-L425 | train |
claudio-silva/grunt-angular-builder | tasks/middleware/makeReleaseBuild.js | scanForOptimization | function scanForOptimization (context)
{
var module, verboseOut = context.grunt.log.verbose;
// Track repeated files to determine which modules can be optimized.
Object.keys (context.modules).forEach (function (name)
{
if (context.modules.hasOwnProperty (name)) {
module = context.modules[name];
if (!module.external)
module.filePaths ().forEach (function (path)
{
if (!context.filesRefCount[path])
context.filesRefCount[path] = 1;
else {
verboseOut.writeln (util.csprintf ('white',
'Not optimizing <cyan>%</cyan> because it shares some/all of its files with other modules.', name));
++context.filesRefCount[path];
module.optimize = false;
}
});
}
});
// Determine which modules can act as containers for non-optimized sections of code.
scan (context.options.mainModule, true);
/**
* Search for unoptimizable modules.
* @param {string} moduleName
* @param {boolean?} first=false Is this the root module?
* @returns {boolean} `true` if the module is not optimizable.
*/
function scan (moduleName, first)
{
var module = context.modules[moduleName];
if (!module)
throw new Error (sprintf ("Module '%' was not found.", moduleName));
// Ignore the module if it's external.
if (module.external)
return false;
if (!module.optimize) {
if (first)
module.nonOptimizedContainer = true;
disableOptimizationsForChildrenOf (module);
return true;
}
for (var i = 0, m = module.requires.length, any = false; i < m; ++i)
if (scan (module.requires[i])) //Note: scan() still must be called for ALL submodules!
any = true;
if (any)
module.nonOptimizedContainer = true;
return false;
}
function disableOptimizationsForChildrenOf (module)
{
if (module.external)
return;
for (var i = 0, m = module.requires.length; i < m; ++i) {
var sub = context.modules[module.requires[i]];
if (sub.external)
continue;
if (sub.optimize)
verboseOut.writeln (util.csprintf ('white', "Also disabling optimizations for <cyan>%</cyan>.", sub.name.cyan));
sub.optimize = false;
disableOptimizationsForChildrenOf (sub);
}
}
} | javascript | function scanForOptimization (context)
{
var module, verboseOut = context.grunt.log.verbose;
// Track repeated files to determine which modules can be optimized.
Object.keys (context.modules).forEach (function (name)
{
if (context.modules.hasOwnProperty (name)) {
module = context.modules[name];
if (!module.external)
module.filePaths ().forEach (function (path)
{
if (!context.filesRefCount[path])
context.filesRefCount[path] = 1;
else {
verboseOut.writeln (util.csprintf ('white',
'Not optimizing <cyan>%</cyan> because it shares some/all of its files with other modules.', name));
++context.filesRefCount[path];
module.optimize = false;
}
});
}
});
// Determine which modules can act as containers for non-optimized sections of code.
scan (context.options.mainModule, true);
/**
* Search for unoptimizable modules.
* @param {string} moduleName
* @param {boolean?} first=false Is this the root module?
* @returns {boolean} `true` if the module is not optimizable.
*/
function scan (moduleName, first)
{
var module = context.modules[moduleName];
if (!module)
throw new Error (sprintf ("Module '%' was not found.", moduleName));
// Ignore the module if it's external.
if (module.external)
return false;
if (!module.optimize) {
if (first)
module.nonOptimizedContainer = true;
disableOptimizationsForChildrenOf (module);
return true;
}
for (var i = 0, m = module.requires.length, any = false; i < m; ++i)
if (scan (module.requires[i])) //Note: scan() still must be called for ALL submodules!
any = true;
if (any)
module.nonOptimizedContainer = true;
return false;
}
function disableOptimizationsForChildrenOf (module)
{
if (module.external)
return;
for (var i = 0, m = module.requires.length; i < m; ++i) {
var sub = context.modules[module.requires[i]];
if (sub.external)
continue;
if (sub.optimize)
verboseOut.writeln (util.csprintf ('white', "Also disabling optimizations for <cyan>%</cyan>.", sub.name.cyan));
sub.optimize = false;
disableOptimizationsForChildrenOf (sub);
}
}
} | [
"function",
"scanForOptimization",
"(",
"context",
")",
"{",
"var",
"module",
",",
"verboseOut",
"=",
"context",
".",
"grunt",
".",
"log",
".",
"verbose",
";",
"Object",
".",
"keys",
"(",
"context",
".",
"modules",
")",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"if",
"(",
"context",
".",
"modules",
".",
"hasOwnProperty",
"(",
"name",
")",
")",
"{",
"module",
"=",
"context",
".",
"modules",
"[",
"name",
"]",
";",
"if",
"(",
"!",
"module",
".",
"external",
")",
"module",
".",
"filePaths",
"(",
")",
".",
"forEach",
"(",
"function",
"(",
"path",
")",
"{",
"if",
"(",
"!",
"context",
".",
"filesRefCount",
"[",
"path",
"]",
")",
"context",
".",
"filesRefCount",
"[",
"path",
"]",
"=",
"1",
";",
"else",
"{",
"verboseOut",
".",
"writeln",
"(",
"util",
".",
"csprintf",
"(",
"'white'",
",",
"'Not optimizing <cyan>%</cyan> because it shares some/all of its files with other modules.'",
",",
"name",
")",
")",
";",
"++",
"context",
".",
"filesRefCount",
"[",
"path",
"]",
";",
"module",
".",
"optimize",
"=",
"false",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"scan",
"(",
"context",
".",
"options",
".",
"mainModule",
",",
"true",
")",
";",
"function",
"scan",
"(",
"moduleName",
",",
"first",
")",
"{",
"var",
"module",
"=",
"context",
".",
"modules",
"[",
"moduleName",
"]",
";",
"if",
"(",
"!",
"module",
")",
"throw",
"new",
"Error",
"(",
"sprintf",
"(",
"\"Module '%' was not found.\"",
",",
"moduleName",
")",
")",
";",
"if",
"(",
"module",
".",
"external",
")",
"return",
"false",
";",
"if",
"(",
"!",
"module",
".",
"optimize",
")",
"{",
"if",
"(",
"first",
")",
"module",
".",
"nonOptimizedContainer",
"=",
"true",
";",
"disableOptimizationsForChildrenOf",
"(",
"module",
")",
";",
"return",
"true",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"m",
"=",
"module",
".",
"requires",
".",
"length",
",",
"any",
"=",
"false",
";",
"i",
"<",
"m",
";",
"++",
"i",
")",
"if",
"(",
"scan",
"(",
"module",
".",
"requires",
"[",
"i",
"]",
")",
")",
"any",
"=",
"true",
";",
"if",
"(",
"any",
")",
"module",
".",
"nonOptimizedContainer",
"=",
"true",
";",
"return",
"false",
";",
"}",
"function",
"disableOptimizationsForChildrenOf",
"(",
"module",
")",
"{",
"if",
"(",
"module",
".",
"external",
")",
"return",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"m",
"=",
"module",
".",
"requires",
".",
"length",
";",
"i",
"<",
"m",
";",
"++",
"i",
")",
"{",
"var",
"sub",
"=",
"context",
".",
"modules",
"[",
"module",
".",
"requires",
"[",
"i",
"]",
"]",
";",
"if",
"(",
"sub",
".",
"external",
")",
"continue",
";",
"if",
"(",
"sub",
".",
"optimize",
")",
"verboseOut",
".",
"writeln",
"(",
"util",
".",
"csprintf",
"(",
"'white'",
",",
"\"Also disabling optimizations for <cyan>%</cyan>.\"",
",",
"sub",
".",
"name",
".",
"cyan",
")",
")",
";",
"sub",
".",
"optimize",
"=",
"false",
";",
"disableOptimizationsForChildrenOf",
"(",
"sub",
")",
";",
"}",
"}",
"}"
] | Determine which modules can be optimized.
@param {Context} context The execution context for the middleware stack. | [
"Determine",
"which",
"modules",
"can",
"be",
"optimized",
"."
] | 0aa4232257e4ae95d0aa9258ff0a91395383d8b7 | https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/makeReleaseBuild.js#L432-L503 | train |
claudio-silva/grunt-angular-builder | tasks/middleware/makeReleaseBuild.js | scan | function scan (moduleName, first)
{
var module = context.modules[moduleName];
if (!module)
throw new Error (sprintf ("Module '%' was not found.", moduleName));
// Ignore the module if it's external.
if (module.external)
return false;
if (!module.optimize) {
if (first)
module.nonOptimizedContainer = true;
disableOptimizationsForChildrenOf (module);
return true;
}
for (var i = 0, m = module.requires.length, any = false; i < m; ++i)
if (scan (module.requires[i])) //Note: scan() still must be called for ALL submodules!
any = true;
if (any)
module.nonOptimizedContainer = true;
return false;
} | javascript | function scan (moduleName, first)
{
var module = context.modules[moduleName];
if (!module)
throw new Error (sprintf ("Module '%' was not found.", moduleName));
// Ignore the module if it's external.
if (module.external)
return false;
if (!module.optimize) {
if (first)
module.nonOptimizedContainer = true;
disableOptimizationsForChildrenOf (module);
return true;
}
for (var i = 0, m = module.requires.length, any = false; i < m; ++i)
if (scan (module.requires[i])) //Note: scan() still must be called for ALL submodules!
any = true;
if (any)
module.nonOptimizedContainer = true;
return false;
} | [
"function",
"scan",
"(",
"moduleName",
",",
"first",
")",
"{",
"var",
"module",
"=",
"context",
".",
"modules",
"[",
"moduleName",
"]",
";",
"if",
"(",
"!",
"module",
")",
"throw",
"new",
"Error",
"(",
"sprintf",
"(",
"\"Module '%' was not found.\"",
",",
"moduleName",
")",
")",
";",
"if",
"(",
"module",
".",
"external",
")",
"return",
"false",
";",
"if",
"(",
"!",
"module",
".",
"optimize",
")",
"{",
"if",
"(",
"first",
")",
"module",
".",
"nonOptimizedContainer",
"=",
"true",
";",
"disableOptimizationsForChildrenOf",
"(",
"module",
")",
";",
"return",
"true",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"m",
"=",
"module",
".",
"requires",
".",
"length",
",",
"any",
"=",
"false",
";",
"i",
"<",
"m",
";",
"++",
"i",
")",
"if",
"(",
"scan",
"(",
"module",
".",
"requires",
"[",
"i",
"]",
")",
")",
"any",
"=",
"true",
";",
"if",
"(",
"any",
")",
"module",
".",
"nonOptimizedContainer",
"=",
"true",
";",
"return",
"false",
";",
"}"
] | Search for unoptimizable modules.
@param {string} moduleName
@param {boolean?} first=false Is this the root module?
@returns {boolean} `true` if the module is not optimizable. | [
"Search",
"for",
"unoptimizable",
"modules",
"."
] | 0aa4232257e4ae95d0aa9258ff0a91395383d8b7 | https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/makeReleaseBuild.js#L467-L487 | train |
JamesMessinger/json-schema-lib | lib/api/PluginManager.js | validatePriority | function validatePriority (priority) {
var type = typeOf(priority);
if (type.hasValue && !type.isNumber) {
throw ono('Invalid arguments. Expected a priority number.');
}
} | javascript | function validatePriority (priority) {
var type = typeOf(priority);
if (type.hasValue && !type.isNumber) {
throw ono('Invalid arguments. Expected a priority number.');
}
} | [
"function",
"validatePriority",
"(",
"priority",
")",
"{",
"var",
"type",
"=",
"typeOf",
"(",
"priority",
")",
";",
"if",
"(",
"type",
".",
"hasValue",
"&&",
"!",
"type",
".",
"isNumber",
")",
"{",
"throw",
"ono",
"(",
"'Invalid arguments. Expected a priority number.'",
")",
";",
"}",
"}"
] | Ensures that a user-supplied value is a valid plugin priority.
An error is thrown if the value is invalid.
@param {*} priority - The user-supplied value to validate | [
"Ensures",
"that",
"a",
"user",
"-",
"supplied",
"value",
"is",
"a",
"valid",
"plugin",
"priority",
".",
"An",
"error",
"is",
"thrown",
"if",
"the",
"value",
"is",
"invalid",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/PluginManager.js#L64-L70 | train |
JamesMessinger/json-schema-lib | lib/util/deepAssign.js | deepAssign | function deepAssign (target, source) {
var keys = Object.keys(source);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var oldValue = target[key];
var newValue = source[key];
target[key] = deepClone(newValue, oldValue);
}
return target;
} | javascript | function deepAssign (target, source) {
var keys = Object.keys(source);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var oldValue = target[key];
var newValue = source[key];
target[key] = deepClone(newValue, oldValue);
}
return target;
} | [
"function",
"deepAssign",
"(",
"target",
",",
"source",
")",
"{",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"source",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"var",
"oldValue",
"=",
"target",
"[",
"key",
"]",
";",
"var",
"newValue",
"=",
"source",
"[",
"key",
"]",
";",
"target",
"[",
"key",
"]",
"=",
"deepClone",
"(",
"newValue",
",",
"oldValue",
")",
";",
"}",
"return",
"target",
";",
"}"
] | Deeply assigns the properties of the source object to the target object
@param {object} target
@param {object} source | [
"Deeply",
"assigns",
"the",
"properties",
"of",
"the",
"source",
"object",
"to",
"the",
"target",
"object"
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/util/deepAssign.js#L13-L25 | train |
JamesMessinger/json-schema-lib | lib/util/deepAssign.js | deepClone | function deepClone (value, oldValue) {
var type = typeOf(value);
var clone;
if (type.isPOJO) {
var oldType = typeOf(oldValue);
if (oldType.isPOJO) {
// Return a merged clone of the old POJO and the new POJO
clone = deepAssign({}, oldValue);
return deepAssign(clone, value);
}
else {
return deepAssign({}, value);
}
}
else if (type.isArray) {
clone = [];
for (var i = 0; i < value.length; i++) {
clone.push(deepClone(value[i]));
}
}
else if (type.hasValue) {
// string, boolean, number, function, Date, RegExp, etc.
// Just return it as-is
return value;
}
} | javascript | function deepClone (value, oldValue) {
var type = typeOf(value);
var clone;
if (type.isPOJO) {
var oldType = typeOf(oldValue);
if (oldType.isPOJO) {
// Return a merged clone of the old POJO and the new POJO
clone = deepAssign({}, oldValue);
return deepAssign(clone, value);
}
else {
return deepAssign({}, value);
}
}
else if (type.isArray) {
clone = [];
for (var i = 0; i < value.length; i++) {
clone.push(deepClone(value[i]));
}
}
else if (type.hasValue) {
// string, boolean, number, function, Date, RegExp, etc.
// Just return it as-is
return value;
}
} | [
"function",
"deepClone",
"(",
"value",
",",
"oldValue",
")",
"{",
"var",
"type",
"=",
"typeOf",
"(",
"value",
")",
";",
"var",
"clone",
";",
"if",
"(",
"type",
".",
"isPOJO",
")",
"{",
"var",
"oldType",
"=",
"typeOf",
"(",
"oldValue",
")",
";",
"if",
"(",
"oldType",
".",
"isPOJO",
")",
"{",
"clone",
"=",
"deepAssign",
"(",
"{",
"}",
",",
"oldValue",
")",
";",
"return",
"deepAssign",
"(",
"clone",
",",
"value",
")",
";",
"}",
"else",
"{",
"return",
"deepAssign",
"(",
"{",
"}",
",",
"value",
")",
";",
"}",
"}",
"else",
"if",
"(",
"type",
".",
"isArray",
")",
"{",
"clone",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"value",
".",
"length",
";",
"i",
"++",
")",
"{",
"clone",
".",
"push",
"(",
"deepClone",
"(",
"value",
"[",
"i",
"]",
")",
")",
";",
"}",
"}",
"else",
"if",
"(",
"type",
".",
"hasValue",
")",
"{",
"return",
"value",
";",
"}",
"}"
] | Returns a deep clone of the given value
@param {*} value
@param {*} oldValue
@returns {*} | [
"Returns",
"a",
"deep",
"clone",
"of",
"the",
"given",
"value"
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/util/deepAssign.js#L34-L60 | train |
JamesMessinger/json-schema-lib | lib/api/JsonSchemaLib/resolveFileReferences.js | crawl | function crawl (obj, file) {
var type = typeOf(obj);
if (!type.isPOJO && !type.isArray) {
return;
}
if (type.isPOJO && isFileReference(obj)) {
// We found a file reference, so resolve it
resolveFileReference(obj.$ref, file);
}
// Crawl this POJO or Array, looking for nested JSON References
//
// NOTE: According to the spec, JSON References should not have any properties other than "$ref".
// However, in practice, many schema authors DO add additional properties. Because of this,
// we crawl JSON Reference objects just like normal POJOs. If the schema author has added
// additional properties, then they have opted-into this non-spec-compliant behavior.
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = obj[key];
crawl(value, file);
}
} | javascript | function crawl (obj, file) {
var type = typeOf(obj);
if (!type.isPOJO && !type.isArray) {
return;
}
if (type.isPOJO && isFileReference(obj)) {
// We found a file reference, so resolve it
resolveFileReference(obj.$ref, file);
}
// Crawl this POJO or Array, looking for nested JSON References
//
// NOTE: According to the spec, JSON References should not have any properties other than "$ref".
// However, in practice, many schema authors DO add additional properties. Because of this,
// we crawl JSON Reference objects just like normal POJOs. If the schema author has added
// additional properties, then they have opted-into this non-spec-compliant behavior.
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = obj[key];
crawl(value, file);
}
} | [
"function",
"crawl",
"(",
"obj",
",",
"file",
")",
"{",
"var",
"type",
"=",
"typeOf",
"(",
"obj",
")",
";",
"if",
"(",
"!",
"type",
".",
"isPOJO",
"&&",
"!",
"type",
".",
"isArray",
")",
"{",
"return",
";",
"}",
"if",
"(",
"type",
".",
"isPOJO",
"&&",
"isFileReference",
"(",
"obj",
")",
")",
"{",
"resolveFileReference",
"(",
"obj",
".",
"$ref",
",",
"file",
")",
";",
"}",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"var",
"value",
"=",
"obj",
"[",
"key",
"]",
";",
"crawl",
"(",
"value",
",",
"file",
")",
";",
"}",
"}"
] | Recursively crawls the given value, and resolves any external JSON References.
@param {*} obj - The value to crawl. If it's not an object or array, it will be ignored.
@param {File} file - The file that the value is part of | [
"Recursively",
"crawls",
"the",
"given",
"value",
"and",
"resolves",
"any",
"external",
"JSON",
"References",
"."
] | 6a30b2be496b82eda61d050b30e64b44fa42734a | https://github.com/JamesMessinger/json-schema-lib/blob/6a30b2be496b82eda61d050b30e64b44fa42734a/lib/api/JsonSchemaLib/resolveFileReferences.js#L26-L51 | train |
commenthol/markedpp | src/anchorSlugger.js | getBitbucketId | function getBitbucketId (text) {
text = 'markdown-header-' + text
.toLowerCase()
.replace(/\\(.)/g, (_m, c) => c.charCodeAt(0)) // add escaped chars with their charcode
.normalize('NFKD').replace(/[\u0300-\u036f]/g, '')
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-') // whitespace
.replace(/-+/g, '-') // duplicated hyphen
.replace(/^-+|-+$/g, '') // heading/ tailing hyphen
return text
} | javascript | function getBitbucketId (text) {
text = 'markdown-header-' + text
.toLowerCase()
.replace(/\\(.)/g, (_m, c) => c.charCodeAt(0)) // add escaped chars with their charcode
.normalize('NFKD').replace(/[\u0300-\u036f]/g, '')
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-') // whitespace
.replace(/-+/g, '-') // duplicated hyphen
.replace(/^-+|-+$/g, '') // heading/ tailing hyphen
return text
} | [
"function",
"getBitbucketId",
"(",
"text",
")",
"{",
"text",
"=",
"'markdown-header-'",
"+",
"text",
".",
"toLowerCase",
"(",
")",
".",
"replace",
"(",
"/",
"\\\\(.)",
"/",
"g",
",",
"(",
"_m",
",",
"c",
")",
"=>",
"c",
".",
"charCodeAt",
"(",
"0",
")",
")",
".",
"normalize",
"(",
"'NFKD'",
")",
".",
"replace",
"(",
"/",
"[\\u0300-\\u036f]",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"/",
"[^\\w\\s-]",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"/",
"\\s+",
"/",
"g",
",",
"'-'",
")",
".",
"replace",
"(",
"/",
"-+",
"/",
"g",
",",
"'-'",
")",
".",
"replace",
"(",
"/",
"^-+|-+$",
"/",
"g",
",",
"''",
")",
"return",
"text",
"}"
] | getBitbucketId - anchors used at bitbucket.org
@private
@see: https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/toc.py#L25
There seams to be some "magic" preprocessor which could not be handled here.
@see: https://github.com/Python-Markdown/markdown/issues/222
If no repetition, or if the repetition is 0 then ignore. Otherwise append '_' and the number.
https://groups.google.com/d/msg/bitbucket-users/XnEWbbzs5wU/Fat0UdIecZkJ | [
"getBitbucketId",
"-",
"anchors",
"used",
"at",
"bitbucket",
".",
"org"
] | f72db5aa2c1b858a9d5403c6103f24227d74c611 | https://github.com/commenthol/markedpp/blob/f72db5aa2c1b858a9d5403c6103f24227d74c611/src/anchorSlugger.js#L64-L74 | train |
commenthol/markedpp | src/anchorSlugger.js | getPandocId | function getPandocId (text) {
text = text
.replace(emojiRegex(), '') // Strip emojis
.toLowerCase()
.trim()
.replace(/%25|%/ig, '') // remove single % signs
.replace(RE_ENTITIES, '') // remove xml/html entities
.replace(RE_SPECIALS, '') // single chars that are removed but not [.-]
.replace(/\s+/g, '-') // whitespaces
.replace(/^-+|-+$/g, '') // heading/ tailing hyphen
.replace(RE_CJK, '') // CJK punctuations that are removed
if (/^[0-9-]+$/.test(text)) {
text = 'section'
}
return text
} | javascript | function getPandocId (text) {
text = text
.replace(emojiRegex(), '') // Strip emojis
.toLowerCase()
.trim()
.replace(/%25|%/ig, '') // remove single % signs
.replace(RE_ENTITIES, '') // remove xml/html entities
.replace(RE_SPECIALS, '') // single chars that are removed but not [.-]
.replace(/\s+/g, '-') // whitespaces
.replace(/^-+|-+$/g, '') // heading/ tailing hyphen
.replace(RE_CJK, '') // CJK punctuations that are removed
if (/^[0-9-]+$/.test(text)) {
text = 'section'
}
return text
} | [
"function",
"getPandocId",
"(",
"text",
")",
"{",
"text",
"=",
"text",
".",
"replace",
"(",
"emojiRegex",
"(",
")",
",",
"''",
")",
".",
"toLowerCase",
"(",
")",
".",
"trim",
"(",
")",
".",
"replace",
"(",
"/",
"%25|%",
"/",
"ig",
",",
"''",
")",
".",
"replace",
"(",
"RE_ENTITIES",
",",
"''",
")",
".",
"replace",
"(",
"RE_SPECIALS",
",",
"''",
")",
".",
"replace",
"(",
"/",
"\\s+",
"/",
"g",
",",
"'-'",
")",
".",
"replace",
"(",
"/",
"^-+|-+$",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"RE_CJK",
",",
"''",
")",
"if",
"(",
"/",
"^[0-9-]+$",
"/",
".",
"test",
"(",
"text",
")",
")",
"{",
"text",
"=",
"'section'",
"}",
"return",
"text",
"}"
] | getPandocId - anchors used at pandoc
@private | [
"getPandocId",
"-",
"anchors",
"used",
"at",
"pandoc"
] | f72db5aa2c1b858a9d5403c6103f24227d74c611 | https://github.com/commenthol/markedpp/blob/f72db5aa2c1b858a9d5403c6103f24227d74c611/src/anchorSlugger.js#L104-L120 | train |
commenthol/markedpp | src/anchorSlugger.js | getMarkedId | function getMarkedId (text) {
return entities.decode(text)
.toLowerCase()
.trim()
.replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~_]/g, '')
.replace(/\s/g, '-')
} | javascript | function getMarkedId (text) {
return entities.decode(text)
.toLowerCase()
.trim()
.replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~_]/g, '')
.replace(/\s/g, '-')
} | [
"function",
"getMarkedId",
"(",
"text",
")",
"{",
"return",
"entities",
".",
"decode",
"(",
"text",
")",
".",
"toLowerCase",
"(",
")",
".",
"trim",
"(",
")",
".",
"replace",
"(",
"/",
"[\\u2000-\\u206F\\u2E00-\\u2E7F\\\\'!\"#$%&()*+,./:;<=>?@[\\]^`{|}~_]",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"/",
"\\s",
"/",
"g",
",",
"'-'",
")",
"}"
] | getMarkedId - anchors used in `npm i marked`
@private
@see: https://github.com/markedjs/marked/blob/master/lib/marked.js#L1306 | [
"getMarkedId",
"-",
"anchors",
"used",
"in",
"npm",
"i",
"marked"
] | f72db5aa2c1b858a9d5403c6103f24227d74c611 | https://github.com/commenthol/markedpp/blob/f72db5aa2c1b858a9d5403c6103f24227d74c611/src/anchorSlugger.js#L127-L133 | train |
commenthol/markedpp | src/anchorSlugger.js | getMarkDownItAnchorId | function getMarkDownItAnchorId (text) {
text = text
.replace(/^[<]|[>]$/g, '') // correct markdown format bold/url
text = entities.decode(text)
.toLowerCase()
.trim()
.replace(/\s+/g, '-')
return encodeURIComponent(text)
} | javascript | function getMarkDownItAnchorId (text) {
text = text
.replace(/^[<]|[>]$/g, '') // correct markdown format bold/url
text = entities.decode(text)
.toLowerCase()
.trim()
.replace(/\s+/g, '-')
return encodeURIComponent(text)
} | [
"function",
"getMarkDownItAnchorId",
"(",
"text",
")",
"{",
"text",
"=",
"text",
".",
"replace",
"(",
"/",
"^[<]|[>]$",
"/",
"g",
",",
"''",
")",
"text",
"=",
"entities",
".",
"decode",
"(",
"text",
")",
".",
"toLowerCase",
"(",
")",
".",
"trim",
"(",
")",
".",
"replace",
"(",
"/",
"\\s+",
"/",
"g",
",",
"'-'",
")",
"return",
"encodeURIComponent",
"(",
"text",
")",
"}"
] | getMarkDownItAnchorId - anchors used with `npm i markdown-it-anchor`
@private
@see: https://github.com/valeriangalliat/markdown-it-anchor/blob/master/index.js#L1
If no repetition, or if the repetition is 0 then ignore. Otherwise append '_' and the number.
numbering starts at 2! | [
"getMarkDownItAnchorId",
"-",
"anchors",
"used",
"with",
"npm",
"i",
"markdown",
"-",
"it",
"-",
"anchor"
] | f72db5aa2c1b858a9d5403c6103f24227d74c611 | https://github.com/commenthol/markedpp/blob/f72db5aa2c1b858a9d5403c6103f24227d74c611/src/anchorSlugger.js#L142-L150 | train |
commenthol/markedpp | src/anchorSlugger.js | slugger | function slugger (header, mode) {
mode = mode || 'marked'
let replace
switch (mode) {
case MODE.MARKED:
replace = getMarkedId
break
case MODE.MARKDOWNIT:
return getMarkDownItAnchorId(header)
case MODE.GITHUB:
replace = getGithubId
break
case MODE.GITLAB:
replace = getGitlabId
break
case MODE.PANDOC:
replace = getPandocId
break
case MODE.BITBUCKET:
replace = getBitbucketId
break
case MODE.GHOST:
replace = getGhostId
break
default:
throw new Error('Unknown mode: ' + mode)
}
const href = replace(asciiOnlyToLowerCase(header.trim()))
return encodeURI(href)
} | javascript | function slugger (header, mode) {
mode = mode || 'marked'
let replace
switch (mode) {
case MODE.MARKED:
replace = getMarkedId
break
case MODE.MARKDOWNIT:
return getMarkDownItAnchorId(header)
case MODE.GITHUB:
replace = getGithubId
break
case MODE.GITLAB:
replace = getGitlabId
break
case MODE.PANDOC:
replace = getPandocId
break
case MODE.BITBUCKET:
replace = getBitbucketId
break
case MODE.GHOST:
replace = getGhostId
break
default:
throw new Error('Unknown mode: ' + mode)
}
const href = replace(asciiOnlyToLowerCase(header.trim()))
return encodeURI(href)
} | [
"function",
"slugger",
"(",
"header",
",",
"mode",
")",
"{",
"mode",
"=",
"mode",
"||",
"'marked'",
"let",
"replace",
"switch",
"(",
"mode",
")",
"{",
"case",
"MODE",
".",
"MARKED",
":",
"replace",
"=",
"getMarkedId",
"break",
"case",
"MODE",
".",
"MARKDOWNIT",
":",
"return",
"getMarkDownItAnchorId",
"(",
"header",
")",
"case",
"MODE",
".",
"GITHUB",
":",
"replace",
"=",
"getGithubId",
"break",
"case",
"MODE",
".",
"GITLAB",
":",
"replace",
"=",
"getGitlabId",
"break",
"case",
"MODE",
".",
"PANDOC",
":",
"replace",
"=",
"getPandocId",
"break",
"case",
"MODE",
".",
"BITBUCKET",
":",
"replace",
"=",
"getBitbucketId",
"break",
"case",
"MODE",
".",
"GHOST",
":",
"replace",
"=",
"getGhostId",
"break",
"default",
":",
"throw",
"new",
"Error",
"(",
"'Unknown mode: '",
"+",
"mode",
")",
"}",
"const",
"href",
"=",
"replace",
"(",
"asciiOnlyToLowerCase",
"(",
"header",
".",
"trim",
"(",
")",
")",
")",
"return",
"encodeURI",
"(",
"href",
")",
"}"
] | Generates an anchor for the given header and mode.
@param header {String} The header to be anchored.
@param mode {String} The anchor mode (github.com|nodejs.org|bitbucket.org|ghost.org|gitlab.com).
@return {String} The header anchor that is compatible with the given mode. | [
"Generates",
"an",
"anchor",
"for",
"the",
"given",
"header",
"and",
"mode",
"."
] | f72db5aa2c1b858a9d5403c6103f24227d74c611 | https://github.com/commenthol/markedpp/blob/f72db5aa2c1b858a9d5403c6103f24227d74c611/src/anchorSlugger.js#L174-L206 | train |
Skellington-Closet/skellington | lib/help.js | registerHelpListener | function registerHelpListener (controller, helpInfo) {
controller.hears('^help ' + helpInfo.command + '$', 'direct_mention,direct_message', (bot, message) => {
let replyText = helpInfo.text
if (typeof helpInfo.text === 'function') {
let helpOpts = _.merge({botName: bot.identity.name}, _.pick(message, ['team', 'channel', 'user']))
replyText = helpInfo.text(helpOpts)
}
bot.reply(message, replyText)
})
} | javascript | function registerHelpListener (controller, helpInfo) {
controller.hears('^help ' + helpInfo.command + '$', 'direct_mention,direct_message', (bot, message) => {
let replyText = helpInfo.text
if (typeof helpInfo.text === 'function') {
let helpOpts = _.merge({botName: bot.identity.name}, _.pick(message, ['team', 'channel', 'user']))
replyText = helpInfo.text(helpOpts)
}
bot.reply(message, replyText)
})
} | [
"function",
"registerHelpListener",
"(",
"controller",
",",
"helpInfo",
")",
"{",
"controller",
".",
"hears",
"(",
"'^help '",
"+",
"helpInfo",
".",
"command",
"+",
"'$'",
",",
"'direct_mention,direct_message'",
",",
"(",
"bot",
",",
"message",
")",
"=>",
"{",
"let",
"replyText",
"=",
"helpInfo",
".",
"text",
"if",
"(",
"typeof",
"helpInfo",
".",
"text",
"===",
"'function'",
")",
"{",
"let",
"helpOpts",
"=",
"_",
".",
"merge",
"(",
"{",
"botName",
":",
"bot",
".",
"identity",
".",
"name",
"}",
",",
"_",
".",
"pick",
"(",
"message",
",",
"[",
"'team'",
",",
"'channel'",
",",
"'user'",
"]",
")",
")",
"replyText",
"=",
"helpInfo",
".",
"text",
"(",
"helpOpts",
")",
"}",
"bot",
".",
"reply",
"(",
"message",
",",
"replyText",
")",
"}",
")",
"}"
] | Adds a single help listener for a plugin
@param controller
@param helpInfo | [
"Adds",
"a",
"single",
"help",
"listener",
"for",
"a",
"plugin"
] | fa660c0864ab13188c0b663cd57ccbcc979683f1 | https://github.com/Skellington-Closet/skellington/blob/fa660c0864ab13188c0b663cd57ccbcc979683f1/lib/help.js#L40-L52 | train |
LivePersonInc/chronosjs | src/courier/PostMessageMapper.js | toEvent | function toEvent(message) {
if (message) {
if (message.error) {
PostMessageUtilities.log("Error on message: " + message.error, "ERROR", "PostMessageMapper");
return function() {
return message;
};
}
else {
return _getMappedMethod.call(this, message);
}
}
} | javascript | function toEvent(message) {
if (message) {
if (message.error) {
PostMessageUtilities.log("Error on message: " + message.error, "ERROR", "PostMessageMapper");
return function() {
return message;
};
}
else {
return _getMappedMethod.call(this, message);
}
}
} | [
"function",
"toEvent",
"(",
"message",
")",
"{",
"if",
"(",
"message",
")",
"{",
"if",
"(",
"message",
".",
"error",
")",
"{",
"PostMessageUtilities",
".",
"log",
"(",
"\"Error on message: \"",
"+",
"message",
".",
"error",
",",
"\"ERROR\"",
",",
"\"PostMessageMapper\"",
")",
";",
"return",
"function",
"(",
")",
"{",
"return",
"message",
";",
"}",
";",
"}",
"else",
"{",
"return",
"_getMappedMethod",
".",
"call",
"(",
"this",
",",
"message",
")",
";",
"}",
"}",
"}"
] | Method mapping the message to the correct event on the event channel and invoking it
@param {Object} message - the message to be mapped
@returns {Function} the handler function to invoke on the event channel | [
"Method",
"mapping",
"the",
"message",
"to",
"the",
"correct",
"event",
"on",
"the",
"event",
"channel",
"and",
"invoking",
"it"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageMapper.js#L61-L73 | train |
LivePersonInc/chronosjs | src/courier/PostMessageMapper.js | toMessage | function toMessage(id, name) {
return {
method: {
id: id,
name: name,
args: Array.prototype.slice.call(arguments, 2)
}
};
} | javascript | function toMessage(id, name) {
return {
method: {
id: id,
name: name,
args: Array.prototype.slice.call(arguments, 2)
}
};
} | [
"function",
"toMessage",
"(",
"id",
",",
"name",
")",
"{",
"return",
"{",
"method",
":",
"{",
"id",
":",
"id",
",",
"name",
":",
"name",
",",
"args",
":",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"2",
")",
"}",
"}",
";",
"}"
] | Method mapping the method call on the event aggregator to a message which can be posted
@param {String} id - the id for the call
@param {String} name - the name of the method
optional additional method arguments
@returns {Object} the mapped method | [
"Method",
"mapping",
"the",
"method",
"call",
"on",
"the",
"event",
"aggregator",
"to",
"a",
"message",
"which",
"can",
"be",
"posted"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageMapper.js#L82-L90 | train |
LivePersonInc/chronosjs | src/courier/PostMessageMapper.js | _getMappedMethod | function _getMappedMethod(message) {
var method = message && message.method;
var name = method && method.name;
var args = method && method.args;
var eventChannel = this.eventChannel;
return function() {
if (eventChannel && eventChannel[name]) {
return eventChannel[name].apply(eventChannel, args);
}
else {
/* istanbul ignore next */
PostMessageUtilities.log("No channel exists", "ERROR", "PostMessageMapper");
}
};
} | javascript | function _getMappedMethod(message) {
var method = message && message.method;
var name = method && method.name;
var args = method && method.args;
var eventChannel = this.eventChannel;
return function() {
if (eventChannel && eventChannel[name]) {
return eventChannel[name].apply(eventChannel, args);
}
else {
/* istanbul ignore next */
PostMessageUtilities.log("No channel exists", "ERROR", "PostMessageMapper");
}
};
} | [
"function",
"_getMappedMethod",
"(",
"message",
")",
"{",
"var",
"method",
"=",
"message",
"&&",
"message",
".",
"method",
";",
"var",
"name",
"=",
"method",
"&&",
"method",
".",
"name",
";",
"var",
"args",
"=",
"method",
"&&",
"method",
".",
"args",
";",
"var",
"eventChannel",
"=",
"this",
".",
"eventChannel",
";",
"return",
"function",
"(",
")",
"{",
"if",
"(",
"eventChannel",
"&&",
"eventChannel",
"[",
"name",
"]",
")",
"{",
"return",
"eventChannel",
"[",
"name",
"]",
".",
"apply",
"(",
"eventChannel",
",",
"args",
")",
";",
"}",
"else",
"{",
"PostMessageUtilities",
".",
"log",
"(",
"\"No channel exists\"",
",",
"\"ERROR\"",
",",
"\"PostMessageMapper\"",
")",
";",
"}",
"}",
";",
"}"
] | Method getting the mapped method on the event channel after which it can be invoked
@param {Object} message - the message to be mapped
optional additional method arguments
@return {Function} the function to invoke on the event channel
@private | [
"Method",
"getting",
"the",
"mapped",
"method",
"on",
"the",
"event",
"channel",
"after",
"which",
"it",
"can",
"be",
"invoked"
] | 05631bf9323ce3eda368c1c3e9308b23e91f4d13 | https://github.com/LivePersonInc/chronosjs/blob/05631bf9323ce3eda368c1c3e9308b23e91f4d13/src/courier/PostMessageMapper.js#L99-L114 | train |
desirepath41/visualCaptcha-npm | visualCaptcha.js | function( numberOfOptions ) {
var visualCaptchaSession = this.session[ this.namespace ],
imageValues = [];
// Avoid the next IF failing if a string with a number is sent
numberOfOptions = parseInt( numberOfOptions, 10 );
// If it's not a valid number, default to 5
if ( ! numberOfOptions || ! _.isNumber(numberOfOptions) || isNaN(numberOfOptions) ) {
numberOfOptions = 5;
}
// Set the minimum numberOfOptions to four
if ( numberOfOptions < 4 ) {
numberOfOptions = 4;
}
// Shuffle all imageOptions
this.imageOptions = _.shuffle( this.imageOptions );
// Get a random sample of X images
visualCaptchaSession.images = _.sample( this.imageOptions, numberOfOptions );
// Set a random value for each of the images, to be used in the frontend
visualCaptchaSession.images.forEach( function( image, index ) {
var randomValue = crypto.randomBytes( 20 ).toString( 'hex' );
imageValues.push( randomValue );
visualCaptchaSession.images[ index ].value = randomValue;
});
// Select a random image option, pluck current valid image option
visualCaptchaSession.validImageOption = _.sample(
_.without( visualCaptchaSession.images, visualCaptchaSession.validImageOption )
);
// Select a random audio option, pluck current valid audio option
visualCaptchaSession.validAudioOption = _.sample(
_.without( this.audioOptions, visualCaptchaSession.validAudioOption )
);
// Set random hashes for audio and image field names, and add it in the frontend data object
visualCaptchaSession.frontendData = {
values: imageValues,
imageName: this.getValidImageOption().name,
imageFieldName: crypto.randomBytes( 20 ).toString( 'hex' ),
audioFieldName: crypto.randomBytes( 20 ).toString( 'hex' )
};
} | javascript | function( numberOfOptions ) {
var visualCaptchaSession = this.session[ this.namespace ],
imageValues = [];
// Avoid the next IF failing if a string with a number is sent
numberOfOptions = parseInt( numberOfOptions, 10 );
// If it's not a valid number, default to 5
if ( ! numberOfOptions || ! _.isNumber(numberOfOptions) || isNaN(numberOfOptions) ) {
numberOfOptions = 5;
}
// Set the minimum numberOfOptions to four
if ( numberOfOptions < 4 ) {
numberOfOptions = 4;
}
// Shuffle all imageOptions
this.imageOptions = _.shuffle( this.imageOptions );
// Get a random sample of X images
visualCaptchaSession.images = _.sample( this.imageOptions, numberOfOptions );
// Set a random value for each of the images, to be used in the frontend
visualCaptchaSession.images.forEach( function( image, index ) {
var randomValue = crypto.randomBytes( 20 ).toString( 'hex' );
imageValues.push( randomValue );
visualCaptchaSession.images[ index ].value = randomValue;
});
// Select a random image option, pluck current valid image option
visualCaptchaSession.validImageOption = _.sample(
_.without( visualCaptchaSession.images, visualCaptchaSession.validImageOption )
);
// Select a random audio option, pluck current valid audio option
visualCaptchaSession.validAudioOption = _.sample(
_.without( this.audioOptions, visualCaptchaSession.validAudioOption )
);
// Set random hashes for audio and image field names, and add it in the frontend data object
visualCaptchaSession.frontendData = {
values: imageValues,
imageName: this.getValidImageOption().name,
imageFieldName: crypto.randomBytes( 20 ).toString( 'hex' ),
audioFieldName: crypto.randomBytes( 20 ).toString( 'hex' )
};
} | [
"function",
"(",
"numberOfOptions",
")",
"{",
"var",
"visualCaptchaSession",
"=",
"this",
".",
"session",
"[",
"this",
".",
"namespace",
"]",
",",
"imageValues",
"=",
"[",
"]",
";",
"numberOfOptions",
"=",
"parseInt",
"(",
"numberOfOptions",
",",
"10",
")",
";",
"if",
"(",
"!",
"numberOfOptions",
"||",
"!",
"_",
".",
"isNumber",
"(",
"numberOfOptions",
")",
"||",
"isNaN",
"(",
"numberOfOptions",
")",
")",
"{",
"numberOfOptions",
"=",
"5",
";",
"}",
"if",
"(",
"numberOfOptions",
"<",
"4",
")",
"{",
"numberOfOptions",
"=",
"4",
";",
"}",
"this",
".",
"imageOptions",
"=",
"_",
".",
"shuffle",
"(",
"this",
".",
"imageOptions",
")",
";",
"visualCaptchaSession",
".",
"images",
"=",
"_",
".",
"sample",
"(",
"this",
".",
"imageOptions",
",",
"numberOfOptions",
")",
";",
"visualCaptchaSession",
".",
"images",
".",
"forEach",
"(",
"function",
"(",
"image",
",",
"index",
")",
"{",
"var",
"randomValue",
"=",
"crypto",
".",
"randomBytes",
"(",
"20",
")",
".",
"toString",
"(",
"'hex'",
")",
";",
"imageValues",
".",
"push",
"(",
"randomValue",
")",
";",
"visualCaptchaSession",
".",
"images",
"[",
"index",
"]",
".",
"value",
"=",
"randomValue",
";",
"}",
")",
";",
"visualCaptchaSession",
".",
"validImageOption",
"=",
"_",
".",
"sample",
"(",
"_",
".",
"without",
"(",
"visualCaptchaSession",
".",
"images",
",",
"visualCaptchaSession",
".",
"validImageOption",
")",
")",
";",
"visualCaptchaSession",
".",
"validAudioOption",
"=",
"_",
".",
"sample",
"(",
"_",
".",
"without",
"(",
"this",
".",
"audioOptions",
",",
"visualCaptchaSession",
".",
"validAudioOption",
")",
")",
";",
"visualCaptchaSession",
".",
"frontendData",
"=",
"{",
"values",
":",
"imageValues",
",",
"imageName",
":",
"this",
".",
"getValidImageOption",
"(",
")",
".",
"name",
",",
"imageFieldName",
":",
"crypto",
".",
"randomBytes",
"(",
"20",
")",
".",
"toString",
"(",
"'hex'",
")",
",",
"audioFieldName",
":",
"crypto",
".",
"randomBytes",
"(",
"20",
")",
".",
"toString",
"(",
"'hex'",
")",
"}",
";",
"}"
] | Generate a new valid option @param numberOfOptions is optional. Defaults to 5 | [
"Generate",
"a",
"new",
"valid",
"option"
] | f1fe570d0a9d2e56c78fea8f77fef32cd5a7471d | https://github.com/desirepath41/visualCaptcha-npm/blob/f1fe570d0a9d2e56c78fea8f77fef32cd5a7471d/visualCaptcha.js#L28-L76 | train |
|
desirepath41/visualCaptcha-npm | visualCaptcha.js | function( response, fileType ) {
var fs = require( 'fs' ),
mime = require( 'mime' ),
audioOption = this.getValidAudioOption(),
audioFileName = audioOption ? audioOption.path : '',// If there's no audioOption, we set the file name as empty
audioFilePath = __dirname + '/audios/' + audioFileName,
mimeType,
stream;
// If the file name is empty, we skip any work and return a 404 response
if ( audioFileName ) {
// We need to replace '.mp3' with '.ogg' if the fileType === 'ogg'
if ( fileType === 'ogg' ) {
audioFileName = audioFileName.replace( /\.mp3/gi, '.ogg' );
audioFilePath = audioFilePath.replace( /\.mp3/gi, '.ogg' );
} else {
fileType = 'mp3';// This isn't doing anything, really, but I feel better with it
}
fs.exists( audioFilePath, function( exists ) {
if ( exists ) {
mimeType = mime.getType( audioFilePath );
// Set the appropriate mime type
response.set( 'content-type', mimeType );
// Make sure this is not cached
response.set( 'cache-control', 'no-cache, no-store, must-revalidate' );
response.set( 'pragma', 'no-cache' );
response.set( 'expires', 0 );
stream = fs.createReadStream( audioFilePath );
var responseData = [];
if ( stream ) {
stream.on( 'data', function( chunk ) {
responseData.push( chunk );
});
stream.on( 'end', function() {
if ( ! response.headerSent ) {
var finalData = Buffer.concat( responseData );
response.write( finalData );
// Add some noise randomly, so audio files can't be saved and matched easily by filesize or checksum
var noiseData = crypto.randomBytes(Math.round((Math.random() * 1999)) + 501).toString('hex');
response.write( noiseData );
response.end();
}
});
} else {
response.status( 404 ).send( 'Not Found' );
}
} else {
response.status( 404 ).send( 'Not Found' );
}
});
} else {
response.status( 404 ).send( 'Not Found' );
}
} | javascript | function( response, fileType ) {
var fs = require( 'fs' ),
mime = require( 'mime' ),
audioOption = this.getValidAudioOption(),
audioFileName = audioOption ? audioOption.path : '',// If there's no audioOption, we set the file name as empty
audioFilePath = __dirname + '/audios/' + audioFileName,
mimeType,
stream;
// If the file name is empty, we skip any work and return a 404 response
if ( audioFileName ) {
// We need to replace '.mp3' with '.ogg' if the fileType === 'ogg'
if ( fileType === 'ogg' ) {
audioFileName = audioFileName.replace( /\.mp3/gi, '.ogg' );
audioFilePath = audioFilePath.replace( /\.mp3/gi, '.ogg' );
} else {
fileType = 'mp3';// This isn't doing anything, really, but I feel better with it
}
fs.exists( audioFilePath, function( exists ) {
if ( exists ) {
mimeType = mime.getType( audioFilePath );
// Set the appropriate mime type
response.set( 'content-type', mimeType );
// Make sure this is not cached
response.set( 'cache-control', 'no-cache, no-store, must-revalidate' );
response.set( 'pragma', 'no-cache' );
response.set( 'expires', 0 );
stream = fs.createReadStream( audioFilePath );
var responseData = [];
if ( stream ) {
stream.on( 'data', function( chunk ) {
responseData.push( chunk );
});
stream.on( 'end', function() {
if ( ! response.headerSent ) {
var finalData = Buffer.concat( responseData );
response.write( finalData );
// Add some noise randomly, so audio files can't be saved and matched easily by filesize or checksum
var noiseData = crypto.randomBytes(Math.round((Math.random() * 1999)) + 501).toString('hex');
response.write( noiseData );
response.end();
}
});
} else {
response.status( 404 ).send( 'Not Found' );
}
} else {
response.status( 404 ).send( 'Not Found' );
}
});
} else {
response.status( 404 ).send( 'Not Found' );
}
} | [
"function",
"(",
"response",
",",
"fileType",
")",
"{",
"var",
"fs",
"=",
"require",
"(",
"'fs'",
")",
",",
"mime",
"=",
"require",
"(",
"'mime'",
")",
",",
"audioOption",
"=",
"this",
".",
"getValidAudioOption",
"(",
")",
",",
"audioFileName",
"=",
"audioOption",
"?",
"audioOption",
".",
"path",
":",
"''",
",",
"audioFilePath",
"=",
"__dirname",
"+",
"'/audios/'",
"+",
"audioFileName",
",",
"mimeType",
",",
"stream",
";",
"if",
"(",
"audioFileName",
")",
"{",
"if",
"(",
"fileType",
"===",
"'ogg'",
")",
"{",
"audioFileName",
"=",
"audioFileName",
".",
"replace",
"(",
"/",
"\\.mp3",
"/",
"gi",
",",
"'.ogg'",
")",
";",
"audioFilePath",
"=",
"audioFilePath",
".",
"replace",
"(",
"/",
"\\.mp3",
"/",
"gi",
",",
"'.ogg'",
")",
";",
"}",
"else",
"{",
"fileType",
"=",
"'mp3'",
";",
"}",
"fs",
".",
"exists",
"(",
"audioFilePath",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"exists",
")",
"{",
"mimeType",
"=",
"mime",
".",
"getType",
"(",
"audioFilePath",
")",
";",
"response",
".",
"set",
"(",
"'content-type'",
",",
"mimeType",
")",
";",
"response",
".",
"set",
"(",
"'cache-control'",
",",
"'no-cache, no-store, must-revalidate'",
")",
";",
"response",
".",
"set",
"(",
"'pragma'",
",",
"'no-cache'",
")",
";",
"response",
".",
"set",
"(",
"'expires'",
",",
"0",
")",
";",
"stream",
"=",
"fs",
".",
"createReadStream",
"(",
"audioFilePath",
")",
";",
"var",
"responseData",
"=",
"[",
"]",
";",
"if",
"(",
"stream",
")",
"{",
"stream",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"chunk",
")",
"{",
"responseData",
".",
"push",
"(",
"chunk",
")",
";",
"}",
")",
";",
"stream",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"response",
".",
"headerSent",
")",
"{",
"var",
"finalData",
"=",
"Buffer",
".",
"concat",
"(",
"responseData",
")",
";",
"response",
".",
"write",
"(",
"finalData",
")",
";",
"var",
"noiseData",
"=",
"crypto",
".",
"randomBytes",
"(",
"Math",
".",
"round",
"(",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"1999",
")",
")",
"+",
"501",
")",
".",
"toString",
"(",
"'hex'",
")",
";",
"response",
".",
"write",
"(",
"noiseData",
")",
";",
"response",
".",
"end",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"response",
".",
"status",
"(",
"404",
")",
".",
"send",
"(",
"'Not Found'",
")",
";",
"}",
"}",
"else",
"{",
"response",
".",
"status",
"(",
"404",
")",
".",
"send",
"(",
"'Not Found'",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"response",
".",
"status",
"(",
"404",
")",
".",
"send",
"(",
"'Not Found'",
")",
";",
"}",
"}"
] | Stream audio file @param response Node's response object @param fileType defaults to 'mp3', can also be 'ogg' | [
"Stream",
"audio",
"file"
] | f1fe570d0a9d2e56c78fea8f77fef32cd5a7471d | https://github.com/desirepath41/visualCaptcha-npm/blob/f1fe570d0a9d2e56c78fea8f77fef32cd5a7471d/visualCaptcha.js#L143-L204 | train |
|
desirepath41/visualCaptcha-npm | visualCaptcha.js | function( index, response, isRetina ) {
var fs = require( 'fs' ),
imageOption = this.getImageOptionAtIndex( index ),
imageFileName = imageOption ? imageOption.path : '',// If there's no imageOption, we set the file name as empty
imageFilePath = __dirname + '/images/' + imageFileName,
mime = require( 'mime' ),
mimeType,
stream;
// Force boolean for isRetina
if ( ! isRetina ) {
isRetina = false;
} else {
isRetina = true;
}
// If retina is requested, change the file name
if ( isRetina ) {
imageFileName = imageFileName.replace( /\.png/gi, '@2x.png' );
imageFilePath = imageFilePath.replace( /\.png/gi, '@2x.png' );
}
// If the index is non-existent, the file name will be empty, same as if the options weren't generated
if ( imageFileName ) {
fs.exists( imageFilePath, function( exists ) {
if ( exists ) {
mimeType = mime.getType( imageFilePath );
// Set the appropriate mime type
response.set( 'content-type', mimeType );
// Make sure this is not cached
response.set( 'cache-control', 'no-cache, no-store, must-revalidate' );
response.set( 'pragma', 'no-cache' );
response.set( 'expires', 0 );
stream = fs.createReadStream( imageFilePath );
var responseData = [];
if ( stream ) {
stream.on( 'data', function( chunk ) {
responseData.push( chunk );
});
stream.on( 'end', function() {
if ( ! response.headerSent ) {
var finalData = Buffer.concat( responseData );
response.write( finalData );
// Add some noise randomly, so images can't be saved and matched easily by filesize or checksum
var noiseData = crypto.randomBytes(Math.round((Math.random() * 1999)) + 501).toString('hex');
response.write( noiseData );
response.end();
}
});
} else {
response.status( 404 ).send( 'Not Found' );
}
} else {
response.status( 404 ).send( 'Not Found' );
}
});
} else {
response.status( 404 ).send( 'Not Found' );
}
} | javascript | function( index, response, isRetina ) {
var fs = require( 'fs' ),
imageOption = this.getImageOptionAtIndex( index ),
imageFileName = imageOption ? imageOption.path : '',// If there's no imageOption, we set the file name as empty
imageFilePath = __dirname + '/images/' + imageFileName,
mime = require( 'mime' ),
mimeType,
stream;
// Force boolean for isRetina
if ( ! isRetina ) {
isRetina = false;
} else {
isRetina = true;
}
// If retina is requested, change the file name
if ( isRetina ) {
imageFileName = imageFileName.replace( /\.png/gi, '@2x.png' );
imageFilePath = imageFilePath.replace( /\.png/gi, '@2x.png' );
}
// If the index is non-existent, the file name will be empty, same as if the options weren't generated
if ( imageFileName ) {
fs.exists( imageFilePath, function( exists ) {
if ( exists ) {
mimeType = mime.getType( imageFilePath );
// Set the appropriate mime type
response.set( 'content-type', mimeType );
// Make sure this is not cached
response.set( 'cache-control', 'no-cache, no-store, must-revalidate' );
response.set( 'pragma', 'no-cache' );
response.set( 'expires', 0 );
stream = fs.createReadStream( imageFilePath );
var responseData = [];
if ( stream ) {
stream.on( 'data', function( chunk ) {
responseData.push( chunk );
});
stream.on( 'end', function() {
if ( ! response.headerSent ) {
var finalData = Buffer.concat( responseData );
response.write( finalData );
// Add some noise randomly, so images can't be saved and matched easily by filesize or checksum
var noiseData = crypto.randomBytes(Math.round((Math.random() * 1999)) + 501).toString('hex');
response.write( noiseData );
response.end();
}
});
} else {
response.status( 404 ).send( 'Not Found' );
}
} else {
response.status( 404 ).send( 'Not Found' );
}
});
} else {
response.status( 404 ).send( 'Not Found' );
}
} | [
"function",
"(",
"index",
",",
"response",
",",
"isRetina",
")",
"{",
"var",
"fs",
"=",
"require",
"(",
"'fs'",
")",
",",
"imageOption",
"=",
"this",
".",
"getImageOptionAtIndex",
"(",
"index",
")",
",",
"imageFileName",
"=",
"imageOption",
"?",
"imageOption",
".",
"path",
":",
"''",
",",
"imageFilePath",
"=",
"__dirname",
"+",
"'/images/'",
"+",
"imageFileName",
",",
"mime",
"=",
"require",
"(",
"'mime'",
")",
",",
"mimeType",
",",
"stream",
";",
"if",
"(",
"!",
"isRetina",
")",
"{",
"isRetina",
"=",
"false",
";",
"}",
"else",
"{",
"isRetina",
"=",
"true",
";",
"}",
"if",
"(",
"isRetina",
")",
"{",
"imageFileName",
"=",
"imageFileName",
".",
"replace",
"(",
"/",
"\\.png",
"/",
"gi",
",",
"'@2x.png'",
")",
";",
"imageFilePath",
"=",
"imageFilePath",
".",
"replace",
"(",
"/",
"\\.png",
"/",
"gi",
",",
"'@2x.png'",
")",
";",
"}",
"if",
"(",
"imageFileName",
")",
"{",
"fs",
".",
"exists",
"(",
"imageFilePath",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"exists",
")",
"{",
"mimeType",
"=",
"mime",
".",
"getType",
"(",
"imageFilePath",
")",
";",
"response",
".",
"set",
"(",
"'content-type'",
",",
"mimeType",
")",
";",
"response",
".",
"set",
"(",
"'cache-control'",
",",
"'no-cache, no-store, must-revalidate'",
")",
";",
"response",
".",
"set",
"(",
"'pragma'",
",",
"'no-cache'",
")",
";",
"response",
".",
"set",
"(",
"'expires'",
",",
"0",
")",
";",
"stream",
"=",
"fs",
".",
"createReadStream",
"(",
"imageFilePath",
")",
";",
"var",
"responseData",
"=",
"[",
"]",
";",
"if",
"(",
"stream",
")",
"{",
"stream",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"chunk",
")",
"{",
"responseData",
".",
"push",
"(",
"chunk",
")",
";",
"}",
")",
";",
"stream",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"response",
".",
"headerSent",
")",
"{",
"var",
"finalData",
"=",
"Buffer",
".",
"concat",
"(",
"responseData",
")",
";",
"response",
".",
"write",
"(",
"finalData",
")",
";",
"var",
"noiseData",
"=",
"crypto",
".",
"randomBytes",
"(",
"Math",
".",
"round",
"(",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"1999",
")",
")",
"+",
"501",
")",
".",
"toString",
"(",
"'hex'",
")",
";",
"response",
".",
"write",
"(",
"noiseData",
")",
";",
"response",
".",
"end",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"response",
".",
"status",
"(",
"404",
")",
".",
"send",
"(",
"'Not Found'",
")",
";",
"}",
"}",
"else",
"{",
"response",
".",
"status",
"(",
"404",
")",
".",
"send",
"(",
"'Not Found'",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"response",
".",
"status",
"(",
"404",
")",
".",
"send",
"(",
"'Not Found'",
")",
";",
"}",
"}"
] | Stream image file given an index in the session visualCaptcha images array @param index of the image in the session images array to send @param response Node's response object @paran isRetina boolean. Defaults to false | [
"Stream",
"image",
"file",
"given",
"an",
"index",
"in",
"the",
"session",
"visualCaptcha",
"images",
"array"
] | f1fe570d0a9d2e56c78fea8f77fef32cd5a7471d | https://github.com/desirepath41/visualCaptcha-npm/blob/f1fe570d0a9d2e56c78fea8f77fef32cd5a7471d/visualCaptcha.js#L210-L278 | train |
|
NebulousLabs/Nodejs-Sia | src/sia.js | connect | async function connect(address) {
const running = await isRunning(address)
if (!running) {
throw errCouldNotConnect
}
return siadWrapper(address)
} | javascript | async function connect(address) {
const running = await isRunning(address)
if (!running) {
throw errCouldNotConnect
}
return siadWrapper(address)
} | [
"async",
"function",
"connect",
"(",
"address",
")",
"{",
"const",
"running",
"=",
"await",
"isRunning",
"(",
"address",
")",
"if",
"(",
"!",
"running",
")",
"{",
"throw",
"errCouldNotConnect",
"}",
"return",
"siadWrapper",
"(",
"address",
")",
"}"
] | connect connects to a running Siad at `address` and returns a siadWrapper object. | [
"connect",
"connects",
"to",
"a",
"running",
"Siad",
"at",
"address",
"and",
"returns",
"a",
"siadWrapper",
"object",
"."
] | 147b48b97312ab69a4cd0fc207e6bb849124a3af | https://github.com/NebulousLabs/Nodejs-Sia/blob/147b48b97312ab69a4cd0fc207e6bb849124a3af/src/sia.js#L123-L129 | train |
strues/boldr | packages/core/src/client/configBrowser.js | walk | function walk(obj, path, initializeMissing = false) {
let newObj = obj;
if (path) {
const ar = path.split('.');
while (ar.length) {
const k = ar.shift();
if (initializeMissing && obj[k] == null) {
newObj[k] = {};
newObj = newObj[k];
} else if (k in newObj) {
newObj = newObj[k];
} else {
throw new Error(`cannot find configuration param '${path}'`);
}
}
}
return newObj;
} | javascript | function walk(obj, path, initializeMissing = false) {
let newObj = obj;
if (path) {
const ar = path.split('.');
while (ar.length) {
const k = ar.shift();
if (initializeMissing && obj[k] == null) {
newObj[k] = {};
newObj = newObj[k];
} else if (k in newObj) {
newObj = newObj[k];
} else {
throw new Error(`cannot find configuration param '${path}'`);
}
}
}
return newObj;
} | [
"function",
"walk",
"(",
"obj",
",",
"path",
",",
"initializeMissing",
"=",
"false",
")",
"{",
"let",
"newObj",
"=",
"obj",
";",
"if",
"(",
"path",
")",
"{",
"const",
"ar",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
";",
"while",
"(",
"ar",
".",
"length",
")",
"{",
"const",
"k",
"=",
"ar",
".",
"shift",
"(",
")",
";",
"if",
"(",
"initializeMissing",
"&&",
"obj",
"[",
"k",
"]",
"==",
"null",
")",
"{",
"newObj",
"[",
"k",
"]",
"=",
"{",
"}",
";",
"newObj",
"=",
"newObj",
"[",
"k",
"]",
";",
"}",
"else",
"if",
"(",
"k",
"in",
"newObj",
")",
"{",
"newObj",
"=",
"newObj",
"[",
"k",
"]",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"path",
"}",
"`",
")",
";",
"}",
"}",
"}",
"return",
"newObj",
";",
"}"
] | Taken from convict source code. | [
"Taken",
"from",
"convict",
"source",
"code",
"."
] | 21f1ed9a5ed754e01c50827249e89087b788e660 | https://github.com/strues/boldr/blob/21f1ed9a5ed754e01c50827249e89087b788e660/packages/core/src/client/configBrowser.js#L2-L21 | train |
Skellington-Closet/skellington | index.js | getSlackbotConfig | function getSlackbotConfig (config) {
return _.defaults(config.botkit, {debug: !!config.debug}, botkitDefaults)
} | javascript | function getSlackbotConfig (config) {
return _.defaults(config.botkit, {debug: !!config.debug}, botkitDefaults)
} | [
"function",
"getSlackbotConfig",
"(",
"config",
")",
"{",
"return",
"_",
".",
"defaults",
"(",
"config",
".",
"botkit",
",",
"{",
"debug",
":",
"!",
"!",
"config",
".",
"debug",
"}",
",",
"botkitDefaults",
")",
"}"
] | Gets the config object for Botkit.slackbot
@param config | [
"Gets",
"the",
"config",
"object",
"for",
"Botkit",
".",
"slackbot"
] | fa660c0864ab13188c0b663cd57ccbcc979683f1 | https://github.com/Skellington-Closet/skellington/blob/fa660c0864ab13188c0b663cd57ccbcc979683f1/index.js#L54-L56 | train |
Skellington-Closet/skellington | index.js | formatConfig | function formatConfig (config) {
_.defaults(config, {debug: false, plugins: []})
config.debugOptions = config.debugOptions || {}
config.connectedTeams = new Set()
if (!Array.isArray(config.plugins)) {
config.plugins = [config.plugins]
}
config.scopes = _.chain(config.plugins)
.map('scopes')
.flatten()
.concat(_.isArray(config.scopes) ? config.scopes : [])
.uniq()
.remove(_.isString.bind(_))
.value()
config.isSlackApp = !config.slackToken
if (!config.slackToken && !(config.clientId && config.clientSecret && config.port)) {
logger.error(`Missing configuration. Config must include either slackToken AND/OR clientId, clientSecret, and port`)
process.exit(1)
}
} | javascript | function formatConfig (config) {
_.defaults(config, {debug: false, plugins: []})
config.debugOptions = config.debugOptions || {}
config.connectedTeams = new Set()
if (!Array.isArray(config.plugins)) {
config.plugins = [config.plugins]
}
config.scopes = _.chain(config.plugins)
.map('scopes')
.flatten()
.concat(_.isArray(config.scopes) ? config.scopes : [])
.uniq()
.remove(_.isString.bind(_))
.value()
config.isSlackApp = !config.slackToken
if (!config.slackToken && !(config.clientId && config.clientSecret && config.port)) {
logger.error(`Missing configuration. Config must include either slackToken AND/OR clientId, clientSecret, and port`)
process.exit(1)
}
} | [
"function",
"formatConfig",
"(",
"config",
")",
"{",
"_",
".",
"defaults",
"(",
"config",
",",
"{",
"debug",
":",
"false",
",",
"plugins",
":",
"[",
"]",
"}",
")",
"config",
".",
"debugOptions",
"=",
"config",
".",
"debugOptions",
"||",
"{",
"}",
"config",
".",
"connectedTeams",
"=",
"new",
"Set",
"(",
")",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"config",
".",
"plugins",
")",
")",
"{",
"config",
".",
"plugins",
"=",
"[",
"config",
".",
"plugins",
"]",
"}",
"config",
".",
"scopes",
"=",
"_",
".",
"chain",
"(",
"config",
".",
"plugins",
")",
".",
"map",
"(",
"'scopes'",
")",
".",
"flatten",
"(",
")",
".",
"concat",
"(",
"_",
".",
"isArray",
"(",
"config",
".",
"scopes",
")",
"?",
"config",
".",
"scopes",
":",
"[",
"]",
")",
".",
"uniq",
"(",
")",
".",
"remove",
"(",
"_",
".",
"isString",
".",
"bind",
"(",
"_",
")",
")",
".",
"value",
"(",
")",
"config",
".",
"isSlackApp",
"=",
"!",
"config",
".",
"slackToken",
"if",
"(",
"!",
"config",
".",
"slackToken",
"&&",
"!",
"(",
"config",
".",
"clientId",
"&&",
"config",
".",
"clientSecret",
"&&",
"config",
".",
"port",
")",
")",
"{",
"logger",
".",
"error",
"(",
"`",
"`",
")",
"process",
".",
"exit",
"(",
"1",
")",
"}",
"}"
] | Formats config values so they are normalized, will exit the process with an error if required config is missing
@param config | [
"Formats",
"config",
"values",
"so",
"they",
"are",
"normalized",
"will",
"exit",
"the",
"process",
"with",
"an",
"error",
"if",
"required",
"config",
"is",
"missing"
] | fa660c0864ab13188c0b663cd57ccbcc979683f1 | https://github.com/Skellington-Closet/skellington/blob/fa660c0864ab13188c0b663cd57ccbcc979683f1/index.js#L63-L87 | train |
mikolalysenko/split-polygon | clip-poly.js | lerpW | function lerpW(a, wa, b, wb) {
var d = wb - wa
var t = -wa / d
if(t < 0.0) {
t = 0.0
} else if(t > 1.0) {
t = 1.0
}
var ti = 1.0 - t
var n = a.length
var r = new Array(n)
for(var i=0; i<n; ++i) {
r[i] = t * a[i] + ti * b[i]
}
return r
} | javascript | function lerpW(a, wa, b, wb) {
var d = wb - wa
var t = -wa / d
if(t < 0.0) {
t = 0.0
} else if(t > 1.0) {
t = 1.0
}
var ti = 1.0 - t
var n = a.length
var r = new Array(n)
for(var i=0; i<n; ++i) {
r[i] = t * a[i] + ti * b[i]
}
return r
} | [
"function",
"lerpW",
"(",
"a",
",",
"wa",
",",
"b",
",",
"wb",
")",
"{",
"var",
"d",
"=",
"wb",
"-",
"wa",
"var",
"t",
"=",
"-",
"wa",
"/",
"d",
"if",
"(",
"t",
"<",
"0.0",
")",
"{",
"t",
"=",
"0.0",
"}",
"else",
"if",
"(",
"t",
">",
"1.0",
")",
"{",
"t",
"=",
"1.0",
"}",
"var",
"ti",
"=",
"1.0",
"-",
"t",
"var",
"n",
"=",
"a",
".",
"length",
"var",
"r",
"=",
"new",
"Array",
"(",
"n",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"r",
"[",
"i",
"]",
"=",
"t",
"*",
"a",
"[",
"i",
"]",
"+",
"ti",
"*",
"b",
"[",
"i",
"]",
"}",
"return",
"r",
"}"
] | Can't do this exactly and emit a floating point result | [
"Can",
"t",
"do",
"this",
"exactly",
"and",
"emit",
"a",
"floating",
"point",
"result"
] | 7b7a567329bde91a700553fd3889f66acd69ef5b | https://github.com/mikolalysenko/split-polygon/blob/7b7a567329bde91a700553fd3889f66acd69ef5b/clip-poly.js#L17-L32 | train |
matteodelabre/midijs | lib/connect.js | connect | function connect() {
return new Promise(function (resolve, reject) {
navigator.requestMIDIAccess().then(function (access) {
resolve(new Driver(access));
}).catch(function () {
reject(new Error('MIDI access denied'));
});
});
} | javascript | function connect() {
return new Promise(function (resolve, reject) {
navigator.requestMIDIAccess().then(function (access) {
resolve(new Driver(access));
}).catch(function () {
reject(new Error('MIDI access denied'));
});
});
} | [
"function",
"connect",
"(",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"navigator",
".",
"requestMIDIAccess",
"(",
")",
".",
"then",
"(",
"function",
"(",
"access",
")",
"{",
"resolve",
"(",
"new",
"Driver",
"(",
"access",
")",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'MIDI access denied'",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Establish a connection to the MIDI driver
@return {Promise} A connection promise | [
"Establish",
"a",
"connection",
"to",
"the",
"MIDI",
"driver"
] | c11d2f938125336624f5c6ef4c8c1f6cfac07d93 | https://github.com/matteodelabre/midijs/blob/c11d2f938125336624f5c6ef4c8c1f6cfac07d93/lib/connect.js#L13-L21 | train |
glennjones/elsewhere-profiles | lib/page.js | function(callback){
var options = this.options,
cache = this.options.cache,
logger = this.options.logger;
if(this.url){
logger.log('fetch page: ' + this.url);
// if there is a cache and it holds the url
if(cache &&cache.has(this.url)){
// http status - content located elsewhere, retrieve from there
this.statusCode = 305;
this.requestTime = 0;
this.html = cache.get(this.url);
logger.log('fetched html from cache: ' + this.url);
this.parse(function(){
callback(this);
})
// if not get the html from the url
}else{
this.startedRequest = new Date();
var self = this;
var requestObj = {
uri: this.url,
headers: options.httpHeaders
}
request(requestObj, function(requestErrors, response, body){
if(!requestErrors && response.statusCode === 200){
self.endedRequest = new Date();
self.requestTime = self.endedRequest.getTime() - self.startedRequest.getTime();
logger.log('fetched html from page: '
+ self.requestTime + 'ms - ' + self.url);
self.statusCode = response.statusCode;
self.html = body;
if(cache){
cache.set(self.url, body);
}
self.parse(function(){
self.status = "fetched";
callback(self);
})
}else{
logger.warn('error requesting page: ' + self.url);
self.error = 'error requesting page: ' + self.url;
self.status = "errored";
callback();
}
});
}
}else{
logger.warn('no url given');
this.error = 'no url given';
this.status = "errored";
callback();
}
} | javascript | function(callback){
var options = this.options,
cache = this.options.cache,
logger = this.options.logger;
if(this.url){
logger.log('fetch page: ' + this.url);
// if there is a cache and it holds the url
if(cache &&cache.has(this.url)){
// http status - content located elsewhere, retrieve from there
this.statusCode = 305;
this.requestTime = 0;
this.html = cache.get(this.url);
logger.log('fetched html from cache: ' + this.url);
this.parse(function(){
callback(this);
})
// if not get the html from the url
}else{
this.startedRequest = new Date();
var self = this;
var requestObj = {
uri: this.url,
headers: options.httpHeaders
}
request(requestObj, function(requestErrors, response, body){
if(!requestErrors && response.statusCode === 200){
self.endedRequest = new Date();
self.requestTime = self.endedRequest.getTime() - self.startedRequest.getTime();
logger.log('fetched html from page: '
+ self.requestTime + 'ms - ' + self.url);
self.statusCode = response.statusCode;
self.html = body;
if(cache){
cache.set(self.url, body);
}
self.parse(function(){
self.status = "fetched";
callback(self);
})
}else{
logger.warn('error requesting page: ' + self.url);
self.error = 'error requesting page: ' + self.url;
self.status = "errored";
callback();
}
});
}
}else{
logger.warn('no url given');
this.error = 'no url given';
this.status = "errored";
callback();
}
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"options",
"=",
"this",
".",
"options",
",",
"cache",
"=",
"this",
".",
"options",
".",
"cache",
",",
"logger",
"=",
"this",
".",
"options",
".",
"logger",
";",
"if",
"(",
"this",
".",
"url",
")",
"{",
"logger",
".",
"log",
"(",
"'fetch page: '",
"+",
"this",
".",
"url",
")",
";",
"if",
"(",
"cache",
"&&",
"cache",
".",
"has",
"(",
"this",
".",
"url",
")",
")",
"{",
"this",
".",
"statusCode",
"=",
"305",
";",
"this",
".",
"requestTime",
"=",
"0",
";",
"this",
".",
"html",
"=",
"cache",
".",
"get",
"(",
"this",
".",
"url",
")",
";",
"logger",
".",
"log",
"(",
"'fetched html from cache: '",
"+",
"this",
".",
"url",
")",
";",
"this",
".",
"parse",
"(",
"function",
"(",
")",
"{",
"callback",
"(",
"this",
")",
";",
"}",
")",
"}",
"else",
"{",
"this",
".",
"startedRequest",
"=",
"new",
"Date",
"(",
")",
";",
"var",
"self",
"=",
"this",
";",
"var",
"requestObj",
"=",
"{",
"uri",
":",
"this",
".",
"url",
",",
"headers",
":",
"options",
".",
"httpHeaders",
"}",
"request",
"(",
"requestObj",
",",
"function",
"(",
"requestErrors",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"!",
"requestErrors",
"&&",
"response",
".",
"statusCode",
"===",
"200",
")",
"{",
"self",
".",
"endedRequest",
"=",
"new",
"Date",
"(",
")",
";",
"self",
".",
"requestTime",
"=",
"self",
".",
"endedRequest",
".",
"getTime",
"(",
")",
"-",
"self",
".",
"startedRequest",
".",
"getTime",
"(",
")",
";",
"logger",
".",
"log",
"(",
"'fetched html from page: '",
"+",
"self",
".",
"requestTime",
"+",
"'ms - '",
"+",
"self",
".",
"url",
")",
";",
"self",
".",
"statusCode",
"=",
"response",
".",
"statusCode",
";",
"self",
".",
"html",
"=",
"body",
";",
"if",
"(",
"cache",
")",
"{",
"cache",
".",
"set",
"(",
"self",
".",
"url",
",",
"body",
")",
";",
"}",
"self",
".",
"parse",
"(",
"function",
"(",
")",
"{",
"self",
".",
"status",
"=",
"\"fetched\"",
";",
"callback",
"(",
"self",
")",
";",
"}",
")",
"}",
"else",
"{",
"logger",
".",
"warn",
"(",
"'error requesting page: '",
"+",
"self",
".",
"url",
")",
";",
"self",
".",
"error",
"=",
"'error requesting page: '",
"+",
"self",
".",
"url",
";",
"self",
".",
"status",
"=",
"\"errored\"",
";",
"callback",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
"else",
"{",
"logger",
".",
"warn",
"(",
"'no url given'",
")",
";",
"this",
".",
"error",
"=",
"'no url given'",
";",
"this",
".",
"status",
"=",
"\"errored\"",
";",
"callback",
"(",
")",
";",
"}",
"}"
] | fetches page and loads html into object before call parse | [
"fetches",
"page",
"and",
"loads",
"html",
"into",
"object",
"before",
"call",
"parse"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/page.js#L62-L130 | train |
|
glennjones/elsewhere-profiles | lib/page.js | function(callback){
var options = {},// utils.clone( this.options ),
self = this;
options.baseUrl = self.url;
self.startedUFParse = new Date();
//console.log(self.url)
try
{
parser.parseHtml (self.html, options, function(err, data){
//console.log( JSON.stringify(data) );
if(data){
self.profile.hCards = self.getArrayOfContentType(data, 'h-card' );
self.profile.hResumes = self.getArrayOfContentType(data, 'hresume' );
self.profile.xfn = self.getArrayOfContentType(data, 'xfn' );
}
if(callback){
callback();
}
});
}
catch(err)
{
self.options.logger.warn('error parsing microformats in page: ' + self.url);
self.error = err;
callback();
}
self.endedUFParse = new Date();
self.parseTime = self.endedUFParse.getTime() - self.startedUFParse.getTime();
self.options.logger.log('time to parse microformats in page: ' + self.parseTime + 'ms - ' + self.url);
} | javascript | function(callback){
var options = {},// utils.clone( this.options ),
self = this;
options.baseUrl = self.url;
self.startedUFParse = new Date();
//console.log(self.url)
try
{
parser.parseHtml (self.html, options, function(err, data){
//console.log( JSON.stringify(data) );
if(data){
self.profile.hCards = self.getArrayOfContentType(data, 'h-card' );
self.profile.hResumes = self.getArrayOfContentType(data, 'hresume' );
self.profile.xfn = self.getArrayOfContentType(data, 'xfn' );
}
if(callback){
callback();
}
});
}
catch(err)
{
self.options.logger.warn('error parsing microformats in page: ' + self.url);
self.error = err;
callback();
}
self.endedUFParse = new Date();
self.parseTime = self.endedUFParse.getTime() - self.startedUFParse.getTime();
self.options.logger.log('time to parse microformats in page: ' + self.parseTime + 'ms - ' + self.url);
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"options",
"=",
"{",
"}",
",",
"self",
"=",
"this",
";",
"options",
".",
"baseUrl",
"=",
"self",
".",
"url",
";",
"self",
".",
"startedUFParse",
"=",
"new",
"Date",
"(",
")",
";",
"try",
"{",
"parser",
".",
"parseHtml",
"(",
"self",
".",
"html",
",",
"options",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"data",
")",
"{",
"self",
".",
"profile",
".",
"hCards",
"=",
"self",
".",
"getArrayOfContentType",
"(",
"data",
",",
"'h-card'",
")",
";",
"self",
".",
"profile",
".",
"hResumes",
"=",
"self",
".",
"getArrayOfContentType",
"(",
"data",
",",
"'hresume'",
")",
";",
"self",
".",
"profile",
".",
"xfn",
"=",
"self",
".",
"getArrayOfContentType",
"(",
"data",
",",
"'xfn'",
")",
";",
"}",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"self",
".",
"options",
".",
"logger",
".",
"warn",
"(",
"'error parsing microformats in page: '",
"+",
"self",
".",
"url",
")",
";",
"self",
".",
"error",
"=",
"err",
";",
"callback",
"(",
")",
";",
"}",
"self",
".",
"endedUFParse",
"=",
"new",
"Date",
"(",
")",
";",
"self",
".",
"parseTime",
"=",
"self",
".",
"endedUFParse",
".",
"getTime",
"(",
")",
"-",
"self",
".",
"startedUFParse",
".",
"getTime",
"(",
")",
";",
"self",
".",
"options",
".",
"logger",
".",
"log",
"(",
"'time to parse microformats in page: '",
"+",
"self",
".",
"parseTime",
"+",
"'ms - '",
"+",
"self",
".",
"url",
")",
";",
"}"
] | parses microformats from html | [
"parses",
"microformats",
"from",
"html"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/page.js#L134-L170 | train |
|
glennjones/elsewhere-profiles | lib/page.js | function(callback){
var options = this.options,
cache = this.options.cache,
logger = this.options.logger;
if(this.apiInterface){
logger.info('fetch data from api: ' + this.apiInterface.name);
var sgn = this.profile.identity.sgn || '',
self = this;
try
{
this.apiInterface.getProfile(this.url, sgn, options, function(hCard){
if(hCard){
self.profile.hCards = [hCard];
}
self.status = "fetched";
callback();
});
}
catch(err)
{
logger.warn('error getting api data with plugin for: ' + self.domain + ' - ' + err);
self.error = err;
self.status = "errored";
callback();
}
}
} | javascript | function(callback){
var options = this.options,
cache = this.options.cache,
logger = this.options.logger;
if(this.apiInterface){
logger.info('fetch data from api: ' + this.apiInterface.name);
var sgn = this.profile.identity.sgn || '',
self = this;
try
{
this.apiInterface.getProfile(this.url, sgn, options, function(hCard){
if(hCard){
self.profile.hCards = [hCard];
}
self.status = "fetched";
callback();
});
}
catch(err)
{
logger.warn('error getting api data with plugin for: ' + self.domain + ' - ' + err);
self.error = err;
self.status = "errored";
callback();
}
}
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"options",
"=",
"this",
".",
"options",
",",
"cache",
"=",
"this",
".",
"options",
".",
"cache",
",",
"logger",
"=",
"this",
".",
"options",
".",
"logger",
";",
"if",
"(",
"this",
".",
"apiInterface",
")",
"{",
"logger",
".",
"info",
"(",
"'fetch data from api: '",
"+",
"this",
".",
"apiInterface",
".",
"name",
")",
";",
"var",
"sgn",
"=",
"this",
".",
"profile",
".",
"identity",
".",
"sgn",
"||",
"''",
",",
"self",
"=",
"this",
";",
"try",
"{",
"this",
".",
"apiInterface",
".",
"getProfile",
"(",
"this",
".",
"url",
",",
"sgn",
",",
"options",
",",
"function",
"(",
"hCard",
")",
"{",
"if",
"(",
"hCard",
")",
"{",
"self",
".",
"profile",
".",
"hCards",
"=",
"[",
"hCard",
"]",
";",
"}",
"self",
".",
"status",
"=",
"\"fetched\"",
";",
"callback",
"(",
")",
";",
"}",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"logger",
".",
"warn",
"(",
"'error getting api data with plugin for: '",
"+",
"self",
".",
"domain",
"+",
"' - '",
"+",
"err",
")",
";",
"self",
".",
"error",
"=",
"err",
";",
"self",
".",
"status",
"=",
"\"errored\"",
";",
"callback",
"(",
")",
";",
"}",
"}",
"}"
] | uses plug-in interface to get profile from an api | [
"uses",
"plug",
"-",
"in",
"interface",
"to",
"get",
"profile",
"from",
"an",
"api"
] | f86a5d040d540d4f8ed4f86518b75a0e6c8855ba | https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/page.js#L188-L219 | train |
|
claudio-silva/grunt-angular-builder | tasks/middleware/includeRequiredScripts.js | IncludeRequiredScriptsMiddleware | function IncludeRequiredScriptsMiddleware (context)
{
var path = require ('path');
/**
* Paths of the required scripts.
* @type {string[]}
*/
var paths = [];
/**
* File content of the required scripts.
* @type {string[]}
*/
var sources = [];
/**
* Map of required script paths, as they are being resolved.
* Prevents infinite recursion and redundant scans.
* Note: paths will be registered here *before* being added to `paths`.
* @type {Object.<string,boolean>}
*/
var references = {};
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
// Do nothing
};
this.trace = function (module)
{
util.info ("Scanning <cyan>%</cyan> for non-angular script dependencies...", module.name);
scan (module.head, module.headPath);
module.bodies.forEach (function (path, i)
{
scan (path, module.bodyPaths[i]);
});
};
this.build = function (targetScript)
{
/* jshint unused: vars */
var scripts = paths.map (function (path, i)
{
return {
path: path,
content: sources[i]
};
});
util.arrayAppend (context.standaloneScripts, scripts);
if (context.standaloneScripts.length) {
var list = context.standaloneScripts.map (
function (e, i) { return ' ' + (i + 1) + '. ' + e.path; }
).join (util.NL);
util.info ("Required non-angular scripts:%<cyan>%</cyan>", util.NL, list);
}
};
//--------------------------------------------------------------------------------------------------------------------
// PRIVATE
//--------------------------------------------------------------------------------------------------------------------
/**
* Extracts file paths from embedded comment references to scripts and appends them to `paths`.
* @param {string} sourceCode
* @param {string} filePath
*/
function scan (sourceCode, filePath)
{
/* jshint -W083 */
var match
, r = new RegExp (MATCH_DIRECTIVE);
while ((match = r.exec (sourceCode))) {
match[1].split (/\s*,\s*/).forEach (function (s)
{
var m = s.match (/(["'])(.*?)\1/);
if (!m)
util.warn ('syntax error on #script directive on argument ...<cyan> % </cyan>...%At <cyan>%</cyan>\t',
s, util.NL, filePath);
else {
var url = m[2];
var requiredPath = path.normalize (path.dirname (filePath) + '/' + url);
// Check if this script was not already referenced.
if (!references[requiredPath]) {
references[requiredPath] = true;
var source = context.grunt.file.read (requiredPath);
// First, see if the required script has its own 'requires'.
// If so, they must be required *before* the current script.
scan (source, requiredPath);
// Let's register the dependency now.
paths.push (requiredPath);
sources.push (source);
}
}
});
}
}
} | javascript | function IncludeRequiredScriptsMiddleware (context)
{
var path = require ('path');
/**
* Paths of the required scripts.
* @type {string[]}
*/
var paths = [];
/**
* File content of the required scripts.
* @type {string[]}
*/
var sources = [];
/**
* Map of required script paths, as they are being resolved.
* Prevents infinite recursion and redundant scans.
* Note: paths will be registered here *before* being added to `paths`.
* @type {Object.<string,boolean>}
*/
var references = {};
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
// Do nothing
};
this.trace = function (module)
{
util.info ("Scanning <cyan>%</cyan> for non-angular script dependencies...", module.name);
scan (module.head, module.headPath);
module.bodies.forEach (function (path, i)
{
scan (path, module.bodyPaths[i]);
});
};
this.build = function (targetScript)
{
/* jshint unused: vars */
var scripts = paths.map (function (path, i)
{
return {
path: path,
content: sources[i]
};
});
util.arrayAppend (context.standaloneScripts, scripts);
if (context.standaloneScripts.length) {
var list = context.standaloneScripts.map (
function (e, i) { return ' ' + (i + 1) + '. ' + e.path; }
).join (util.NL);
util.info ("Required non-angular scripts:%<cyan>%</cyan>", util.NL, list);
}
};
//--------------------------------------------------------------------------------------------------------------------
// PRIVATE
//--------------------------------------------------------------------------------------------------------------------
/**
* Extracts file paths from embedded comment references to scripts and appends them to `paths`.
* @param {string} sourceCode
* @param {string} filePath
*/
function scan (sourceCode, filePath)
{
/* jshint -W083 */
var match
, r = new RegExp (MATCH_DIRECTIVE);
while ((match = r.exec (sourceCode))) {
match[1].split (/\s*,\s*/).forEach (function (s)
{
var m = s.match (/(["'])(.*?)\1/);
if (!m)
util.warn ('syntax error on #script directive on argument ...<cyan> % </cyan>...%At <cyan>%</cyan>\t',
s, util.NL, filePath);
else {
var url = m[2];
var requiredPath = path.normalize (path.dirname (filePath) + '/' + url);
// Check if this script was not already referenced.
if (!references[requiredPath]) {
references[requiredPath] = true;
var source = context.grunt.file.read (requiredPath);
// First, see if the required script has its own 'requires'.
// If so, they must be required *before* the current script.
scan (source, requiredPath);
// Let's register the dependency now.
paths.push (requiredPath);
sources.push (source);
}
}
});
}
}
} | [
"function",
"IncludeRequiredScriptsMiddleware",
"(",
"context",
")",
"{",
"var",
"path",
"=",
"require",
"(",
"'path'",
")",
";",
"var",
"paths",
"=",
"[",
"]",
";",
"var",
"sources",
"=",
"[",
"]",
";",
"var",
"references",
"=",
"{",
"}",
";",
"this",
".",
"analyze",
"=",
"function",
"(",
"filesArray",
")",
"{",
"}",
";",
"this",
".",
"trace",
"=",
"function",
"(",
"module",
")",
"{",
"util",
".",
"info",
"(",
"\"Scanning <cyan>%</cyan> for non-angular script dependencies...\"",
",",
"module",
".",
"name",
")",
";",
"scan",
"(",
"module",
".",
"head",
",",
"module",
".",
"headPath",
")",
";",
"module",
".",
"bodies",
".",
"forEach",
"(",
"function",
"(",
"path",
",",
"i",
")",
"{",
"scan",
"(",
"path",
",",
"module",
".",
"bodyPaths",
"[",
"i",
"]",
")",
";",
"}",
")",
";",
"}",
";",
"this",
".",
"build",
"=",
"function",
"(",
"targetScript",
")",
"{",
"var",
"scripts",
"=",
"paths",
".",
"map",
"(",
"function",
"(",
"path",
",",
"i",
")",
"{",
"return",
"{",
"path",
":",
"path",
",",
"content",
":",
"sources",
"[",
"i",
"]",
"}",
";",
"}",
")",
";",
"util",
".",
"arrayAppend",
"(",
"context",
".",
"standaloneScripts",
",",
"scripts",
")",
";",
"if",
"(",
"context",
".",
"standaloneScripts",
".",
"length",
")",
"{",
"var",
"list",
"=",
"context",
".",
"standaloneScripts",
".",
"map",
"(",
"function",
"(",
"e",
",",
"i",
")",
"{",
"return",
"' '",
"+",
"(",
"i",
"+",
"1",
")",
"+",
"'. '",
"+",
"e",
".",
"path",
";",
"}",
")",
".",
"join",
"(",
"util",
".",
"NL",
")",
";",
"util",
".",
"info",
"(",
"\"Required non-angular scripts:%<cyan>%</cyan>\"",
",",
"util",
".",
"NL",
",",
"list",
")",
";",
"}",
"}",
";",
"function",
"scan",
"(",
"sourceCode",
",",
"filePath",
")",
"{",
"var",
"match",
",",
"r",
"=",
"new",
"RegExp",
"(",
"MATCH_DIRECTIVE",
")",
";",
"while",
"(",
"(",
"match",
"=",
"r",
".",
"exec",
"(",
"sourceCode",
")",
")",
")",
"{",
"match",
"[",
"1",
"]",
".",
"split",
"(",
"/",
"\\s*,\\s*",
"/",
")",
".",
"forEach",
"(",
"function",
"(",
"s",
")",
"{",
"var",
"m",
"=",
"s",
".",
"match",
"(",
"/",
"([\"'])(.*?)\\1",
"/",
")",
";",
"if",
"(",
"!",
"m",
")",
"util",
".",
"warn",
"(",
"'syntax error on #script directive on argument ...<cyan> % </cyan>...%At <cyan>%</cyan>\\t'",
",",
"\\t",
",",
"s",
",",
"util",
".",
"NL",
")",
";",
"else",
"filePath",
"}",
")",
";",
"}",
"}",
"}"
] | Exports to the context the paths of all extra scripts required explicitly by build-directives,
in the order defined by the modules' dependency graph.
@constructor
@implements {MiddlewareInterface}
@param {Context} context The execution context for the middleware stack. | [
"Exports",
"to",
"the",
"context",
"the",
"paths",
"of",
"all",
"extra",
"scripts",
"required",
"explicitly",
"by",
"build",
"-",
"directives",
"in",
"the",
"order",
"defined",
"by",
"the",
"modules",
"dependency",
"graph",
"."
] | 0aa4232257e4ae95d0aa9258ff0a91395383d8b7 | https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/includeRequiredScripts.js#L26-L131 | train |
commenthol/markedpp | src/Parser.js | prep | function prep (id) {
id = id.replace(/(?:%20|\+)/g, ' ')
id = self.headingAutoId({ text: id })
return id
} | javascript | function prep (id) {
id = id.replace(/(?:%20|\+)/g, ' ')
id = self.headingAutoId({ text: id })
return id
} | [
"function",
"prep",
"(",
"id",
")",
"{",
"id",
"=",
"id",
".",
"replace",
"(",
"/",
"(?:%20|\\+)",
"/",
"g",
",",
"' '",
")",
"id",
"=",
"self",
".",
"headingAutoId",
"(",
"{",
"text",
":",
"id",
"}",
")",
"return",
"id",
"}"
] | sanitize the id before lookup | [
"sanitize",
"the",
"id",
"before",
"lookup"
] | f72db5aa2c1b858a9d5403c6103f24227d74c611 | https://github.com/commenthol/markedpp/blob/f72db5aa2c1b858a9d5403c6103f24227d74c611/src/Parser.js#L167-L171 | train |
strapi/strapi-generate-upload | files/api/upload/controllers/Upload.js | function (fieldname, file, filename) {
const acceptedExtensions = strapi.api.upload.config.acceptedExtensions || [];
if (acceptedExtensions[0] !== '*' && !_.contains(acceptedExtensions, path.extname(filename))) {
this.status = 400;
this.body = {
message: 'Invalid file format ' + filename ? 'for this file' + filename : ''
};
}
} | javascript | function (fieldname, file, filename) {
const acceptedExtensions = strapi.api.upload.config.acceptedExtensions || [];
if (acceptedExtensions[0] !== '*' && !_.contains(acceptedExtensions, path.extname(filename))) {
this.status = 400;
this.body = {
message: 'Invalid file format ' + filename ? 'for this file' + filename : ''
};
}
} | [
"function",
"(",
"fieldname",
",",
"file",
",",
"filename",
")",
"{",
"const",
"acceptedExtensions",
"=",
"strapi",
".",
"api",
".",
"upload",
".",
"config",
".",
"acceptedExtensions",
"||",
"[",
"]",
";",
"if",
"(",
"acceptedExtensions",
"[",
"0",
"]",
"!==",
"'*'",
"&&",
"!",
"_",
".",
"contains",
"(",
"acceptedExtensions",
",",
"path",
".",
"extname",
"(",
"filename",
")",
")",
")",
"{",
"this",
".",
"status",
"=",
"400",
";",
"this",
".",
"body",
"=",
"{",
"message",
":",
"'Invalid file format '",
"+",
"filename",
"?",
"'for this file'",
"+",
"filename",
":",
"''",
"}",
";",
"}",
"}"
] | Validation used by `co-busboy`. | [
"Validation",
"used",
"by",
"co",
"-",
"busboy",
"."
] | 52d2202743e3f1b6390b4db5dcb9484f44d2bb85 | https://github.com/strapi/strapi-generate-upload/blob/52d2202743e3f1b6390b4db5dcb9484f44d2bb85/files/api/upload/controllers/Upload.js#L32-L40 | train |
|
koa-modules/methodoverride | index.js | createHeaderGetter | function createHeaderGetter(str) {
var header = str.toLowerCase()
return headerGetter
function headerGetter(req, res) {
// set appropriate Vary header
res.vary(str)
// multiple headers get joined with comma by node.js core
return (req.headers[header] || '').split(/ *, */)
}
} | javascript | function createHeaderGetter(str) {
var header = str.toLowerCase()
return headerGetter
function headerGetter(req, res) {
// set appropriate Vary header
res.vary(str)
// multiple headers get joined with comma by node.js core
return (req.headers[header] || '').split(/ *, */)
}
} | [
"function",
"createHeaderGetter",
"(",
"str",
")",
"{",
"var",
"header",
"=",
"str",
".",
"toLowerCase",
"(",
")",
"return",
"headerGetter",
"function",
"headerGetter",
"(",
"req",
",",
"res",
")",
"{",
"res",
".",
"vary",
"(",
"str",
")",
"return",
"(",
"req",
".",
"headers",
"[",
"header",
"]",
"||",
"''",
")",
".",
"split",
"(",
"/",
" *, *",
"/",
")",
"}",
"}"
] | Create a getter for the given header name. | [
"Create",
"a",
"getter",
"for",
"the",
"given",
"header",
"name",
"."
] | b1ca34955b6243655dd979c106544d15051d3093 | https://github.com/koa-modules/methodoverride/blob/b1ca34955b6243655dd979c106544d15051d3093/index.js#L114-L126 | train |
danielstjules/pattern-emitter | lib/patternEmitter.js | PatternEmitter | function PatternEmitter() {
EventEmitter.call(this);
this.event = '';
this._regexesCount = 0;
this._events = this._events || {};
this._patternEvents = this._patternEvents || {};
this._regexes = this._regexes || {};
} | javascript | function PatternEmitter() {
EventEmitter.call(this);
this.event = '';
this._regexesCount = 0;
this._events = this._events || {};
this._patternEvents = this._patternEvents || {};
this._regexes = this._regexes || {};
} | [
"function",
"PatternEmitter",
"(",
")",
"{",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"event",
"=",
"''",
";",
"this",
".",
"_regexesCount",
"=",
"0",
";",
"this",
".",
"_events",
"=",
"this",
".",
"_events",
"||",
"{",
"}",
";",
"this",
".",
"_patternEvents",
"=",
"this",
".",
"_patternEvents",
"||",
"{",
"}",
";",
"this",
".",
"_regexes",
"=",
"this",
".",
"_regexes",
"||",
"{",
"}",
";",
"}"
] | Creates a new PatternEmitter, which extends EventEmitter. In addition to
EventEmitter's prototype, it allows listeners to register to events matching
a RegExp.
@constructor
@extends EventEmitter
@property {*} event The type of the last emitted event | [
"Creates",
"a",
"new",
"PatternEmitter",
"which",
"extends",
"EventEmitter",
".",
"In",
"addition",
"to",
"EventEmitter",
"s",
"prototype",
"it",
"allows",
"listeners",
"to",
"register",
"to",
"events",
"matching",
"a",
"RegExp",
"."
] | 93f76146b414a16864ce340e40ad9f18505ecebf | https://github.com/danielstjules/pattern-emitter/blob/93f76146b414a16864ce340e40ad9f18505ecebf/lib/patternEmitter.js#L16-L25 | train |
bmeck/understudy | index.js | iterate | function iterate(self, interceptors, args, after) {
if (!interceptors || !interceptors.length) {
after.apply(self, args);
return;
}
var i = 0;
var len = interceptors.length;
if (!len) {
after.apply(self, args);
return;
}
function nextInterceptor() {
if (i === len) {
i++;
after.apply(self, arguments);
}
else if (i < len) {
var used = false;
var interceptor = interceptors[i++];
interceptor.apply(self, Array.prototype.slice.call(arguments, 1).concat(function next(err) {
//
// Do not allow multiple continuations
//
if (used) { return; }
used = true;
if (!err || !callback) {
nextInterceptor.apply(null, waterfall ? arguments : args);
} else {
after.call(self, err);
}
}));
}
}
nextInterceptor.apply(null, args);
} | javascript | function iterate(self, interceptors, args, after) {
if (!interceptors || !interceptors.length) {
after.apply(self, args);
return;
}
var i = 0;
var len = interceptors.length;
if (!len) {
after.apply(self, args);
return;
}
function nextInterceptor() {
if (i === len) {
i++;
after.apply(self, arguments);
}
else if (i < len) {
var used = false;
var interceptor = interceptors[i++];
interceptor.apply(self, Array.prototype.slice.call(arguments, 1).concat(function next(err) {
//
// Do not allow multiple continuations
//
if (used) { return; }
used = true;
if (!err || !callback) {
nextInterceptor.apply(null, waterfall ? arguments : args);
} else {
after.call(self, err);
}
}));
}
}
nextInterceptor.apply(null, args);
} | [
"function",
"iterate",
"(",
"self",
",",
"interceptors",
",",
"args",
",",
"after",
")",
"{",
"if",
"(",
"!",
"interceptors",
"||",
"!",
"interceptors",
".",
"length",
")",
"{",
"after",
".",
"apply",
"(",
"self",
",",
"args",
")",
";",
"return",
";",
"}",
"var",
"i",
"=",
"0",
";",
"var",
"len",
"=",
"interceptors",
".",
"length",
";",
"if",
"(",
"!",
"len",
")",
"{",
"after",
".",
"apply",
"(",
"self",
",",
"args",
")",
";",
"return",
";",
"}",
"function",
"nextInterceptor",
"(",
")",
"{",
"if",
"(",
"i",
"===",
"len",
")",
"{",
"i",
"++",
";",
"after",
".",
"apply",
"(",
"self",
",",
"arguments",
")",
";",
"}",
"else",
"if",
"(",
"i",
"<",
"len",
")",
"{",
"var",
"used",
"=",
"false",
";",
"var",
"interceptor",
"=",
"interceptors",
"[",
"i",
"++",
"]",
";",
"interceptor",
".",
"apply",
"(",
"self",
",",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
".",
"concat",
"(",
"function",
"next",
"(",
"err",
")",
"{",
"if",
"(",
"used",
")",
"{",
"return",
";",
"}",
"used",
"=",
"true",
";",
"if",
"(",
"!",
"err",
"||",
"!",
"callback",
")",
"{",
"nextInterceptor",
".",
"apply",
"(",
"null",
",",
"waterfall",
"?",
"arguments",
":",
"args",
")",
";",
"}",
"else",
"{",
"after",
".",
"call",
"(",
"self",
",",
"err",
")",
";",
"}",
"}",
")",
")",
";",
"}",
"}",
"nextInterceptor",
".",
"apply",
"(",
"null",
",",
"args",
")",
";",
"}"
] | This is called in multiple temporal localities, put into a function instead of inline minor speed loss for more maintainability | [
"This",
"is",
"called",
"in",
"multiple",
"temporal",
"localities",
"put",
"into",
"a",
"function",
"instead",
"of",
"inline",
"minor",
"speed",
"loss",
"for",
"more",
"maintainability"
] | 1f77aca180f7ce9736d7c75cad5594df86f921d7 | https://github.com/bmeck/understudy/blob/1f77aca180f7ce9736d7c75cad5594df86f921d7/index.js#L71-L108 | train |
flux-capacitor/flux-capacitor | packages/flux-capacitor-sequelize/lib/createTransaction.js | createTransaction | function createTransaction (database, sequelizeTransaction) {
const transaction = Object.assign(sequelizeTransaction, {
getImplementation () {
return sequelizeTransaction
},
perform (changeset) {
return database.applyChangeset(changeset, { transaction })
}
})
return transaction
} | javascript | function createTransaction (database, sequelizeTransaction) {
const transaction = Object.assign(sequelizeTransaction, {
getImplementation () {
return sequelizeTransaction
},
perform (changeset) {
return database.applyChangeset(changeset, { transaction })
}
})
return transaction
} | [
"function",
"createTransaction",
"(",
"database",
",",
"sequelizeTransaction",
")",
"{",
"const",
"transaction",
"=",
"Object",
".",
"assign",
"(",
"sequelizeTransaction",
",",
"{",
"getImplementation",
"(",
")",
"{",
"return",
"sequelizeTransaction",
"}",
",",
"perform",
"(",
"changeset",
")",
"{",
"return",
"database",
".",
"applyChangeset",
"(",
"changeset",
",",
"{",
"transaction",
"}",
")",
"}",
"}",
")",
"return",
"transaction",
"}"
] | Extends sequelize transaction.
@param {Database} database
@param {Sequelize.Transaction} sequelizeTransaction
@return {Transaction} | [
"Extends",
"sequelize",
"transaction",
"."
] | 66393138ecdff9c1ba81d88b53144220e593584f | https://github.com/flux-capacitor/flux-capacitor/blob/66393138ecdff9c1ba81d88b53144220e593584f/packages/flux-capacitor-sequelize/lib/createTransaction.js#L10-L21 | train |
NetEase/pomelo-loader | lib/loader.js | function(fn, suffix) {
if(suffix.charAt(0) !== '.') {
suffix = '.' + suffix;
}
if(fn.length <= suffix.length) {
return false;
}
var str = fn.substring(fn.length - suffix.length).toLowerCase();
suffix = suffix.toLowerCase();
return str === suffix;
} | javascript | function(fn, suffix) {
if(suffix.charAt(0) !== '.') {
suffix = '.' + suffix;
}
if(fn.length <= suffix.length) {
return false;
}
var str = fn.substring(fn.length - suffix.length).toLowerCase();
suffix = suffix.toLowerCase();
return str === suffix;
} | [
"function",
"(",
"fn",
",",
"suffix",
")",
"{",
"if",
"(",
"suffix",
".",
"charAt",
"(",
"0",
")",
"!==",
"'.'",
")",
"{",
"suffix",
"=",
"'.'",
"+",
"suffix",
";",
"}",
"if",
"(",
"fn",
".",
"length",
"<=",
"suffix",
".",
"length",
")",
"{",
"return",
"false",
";",
"}",
"var",
"str",
"=",
"fn",
".",
"substring",
"(",
"fn",
".",
"length",
"-",
"suffix",
".",
"length",
")",
".",
"toLowerCase",
"(",
")",
";",
"suffix",
"=",
"suffix",
".",
"toLowerCase",
"(",
")",
";",
"return",
"str",
"===",
"suffix",
";",
"}"
] | Check file suffix
@param fn {String} file name
@param suffix {String} suffix string, such as .js, etc. | [
"Check",
"file",
"suffix"
] | 3036711de323f6a5350c2bf634b0a69b110de458 | https://github.com/NetEase/pomelo-loader/blob/3036711de323f6a5350c2bf634b0a69b110de458/lib/loader.js#L98-L110 | train |
|
flux-capacitor/flux-capacitor | packages/flux-capacitor/lib/combineReducers.js | combineReducers | function combineReducers (reducers) {
const databaseReducers = Object.keys(reducers)
.map((collectionName) => {
const reducer = reducers[ collectionName ]
return createDatabaseReducer(reducer, collectionName)
})
return (database, event) => {
const changesets = databaseReducers.map((reducer) => reducer(database, event))
return combineChangesets(changesets)
}
} | javascript | function combineReducers (reducers) {
const databaseReducers = Object.keys(reducers)
.map((collectionName) => {
const reducer = reducers[ collectionName ]
return createDatabaseReducer(reducer, collectionName)
})
return (database, event) => {
const changesets = databaseReducers.map((reducer) => reducer(database, event))
return combineChangesets(changesets)
}
} | [
"function",
"combineReducers",
"(",
"reducers",
")",
"{",
"const",
"databaseReducers",
"=",
"Object",
".",
"keys",
"(",
"reducers",
")",
".",
"map",
"(",
"(",
"collectionName",
")",
"=>",
"{",
"const",
"reducer",
"=",
"reducers",
"[",
"collectionName",
"]",
"return",
"createDatabaseReducer",
"(",
"reducer",
",",
"collectionName",
")",
"}",
")",
"return",
"(",
"database",
",",
"event",
")",
"=>",
"{",
"const",
"changesets",
"=",
"databaseReducers",
".",
"map",
"(",
"(",
"reducer",
")",
"=>",
"reducer",
"(",
"database",
",",
"event",
")",
")",
"return",
"combineChangesets",
"(",
"changesets",
")",
"}",
"}"
] | Will combine multiple collection reducers to one database reducer.
Takes an object whose keys are collection names and whose values are
reducer functions.
The input reducers have the signature `(Collection, Event) => Changeset`,
the resulting combined reducer is `(Database, Event) => Changeset`.
@param {object} reducers { [collectionName: string]: Function }
@return {Function} | [
"Will",
"combine",
"multiple",
"collection",
"reducers",
"to",
"one",
"database",
"reducer",
".",
"Takes",
"an",
"object",
"whose",
"keys",
"are",
"collection",
"names",
"and",
"whose",
"values",
"are",
"reducer",
"functions",
"."
] | 66393138ecdff9c1ba81d88b53144220e593584f | https://github.com/flux-capacitor/flux-capacitor/blob/66393138ecdff9c1ba81d88b53144220e593584f/packages/flux-capacitor/lib/combineReducers.js#L18-L29 | train |
flux-capacitor/flux-capacitor | packages/flux-capacitor/lib/combineReducers.js | createDatabaseReducer | function createDatabaseReducer (collectionReducer, collectionName) {
return (database, event) => {
const collection = database.collections[ collectionName ]
if (!collection) {
throw new Error(`Collection '${collectionName}' not known by database instance.`)
}
return collectionReducer(collection, event)
}
} | javascript | function createDatabaseReducer (collectionReducer, collectionName) {
return (database, event) => {
const collection = database.collections[ collectionName ]
if (!collection) {
throw new Error(`Collection '${collectionName}' not known by database instance.`)
}
return collectionReducer(collection, event)
}
} | [
"function",
"createDatabaseReducer",
"(",
"collectionReducer",
",",
"collectionName",
")",
"{",
"return",
"(",
"database",
",",
"event",
")",
"=>",
"{",
"const",
"collection",
"=",
"database",
".",
"collections",
"[",
"collectionName",
"]",
"if",
"(",
"!",
"collection",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"collectionName",
"}",
"`",
")",
"}",
"return",
"collectionReducer",
"(",
"collection",
",",
"event",
")",
"}",
"}"
] | Takes a collection reducer and turns it into a database reducer by binding it
to one of the database's collections.
@param {Function} collectionReducer (Collection, Event) => Changeset
@param {string} collectionName
@return {Function} (Database, Event) => Changeset | [
"Takes",
"a",
"collection",
"reducer",
"and",
"turns",
"it",
"into",
"a",
"database",
"reducer",
"by",
"binding",
"it",
"to",
"one",
"of",
"the",
"database",
"s",
"collections",
"."
] | 66393138ecdff9c1ba81d88b53144220e593584f | https://github.com/flux-capacitor/flux-capacitor/blob/66393138ecdff9c1ba81d88b53144220e593584f/packages/flux-capacitor/lib/combineReducers.js#L39-L49 | train |
igorski/zCanvas | dist/es5/Loader.js | isReady | function isReady(aImage) {
// first check : load status
if (typeof aImage.complete === "boolean" && !aImage.complete) return false;
// second check : validity of source (can be 0 until bitmap has been fully parsed by browser)
return !(typeof aImage.naturalWidth !== "undefined" && aImage.naturalWidth === 0);
} | javascript | function isReady(aImage) {
// first check : load status
if (typeof aImage.complete === "boolean" && !aImage.complete) return false;
// second check : validity of source (can be 0 until bitmap has been fully parsed by browser)
return !(typeof aImage.naturalWidth !== "undefined" && aImage.naturalWidth === 0);
} | [
"function",
"isReady",
"(",
"aImage",
")",
"{",
"if",
"(",
"typeof",
"aImage",
".",
"complete",
"===",
"\"boolean\"",
"&&",
"!",
"aImage",
".",
"complete",
")",
"return",
"false",
";",
"return",
"!",
"(",
"typeof",
"aImage",
".",
"naturalWidth",
"!==",
"\"undefined\"",
"&&",
"aImage",
".",
"naturalWidth",
"===",
"0",
")",
";",
"}"
] | a quick query to check whether the Image is ready for rendering
@public
@param {Image} aImage
@return {boolean} | [
"a",
"quick",
"query",
"to",
"check",
"whether",
"the",
"Image",
"is",
"ready",
"for",
"rendering"
] | 8b5cd8e195178a80a9bc4ace7ea0b94dfe6b3f82 | https://github.com/igorski/zCanvas/blob/8b5cd8e195178a80a9bc4ace7ea0b94dfe6b3f82/dist/es5/Loader.js#L123-L130 | train |
igorski/zCanvas | dist/es5/Loader.js | onReady | function onReady(aImage, aCallback, aErrorCallback) {
// if this didn't resolve in a full second, we presume the Image is corrupt
var MAX_ITERATIONS = 60;
var iterations = 0;
function readyCheck() {
if (Loader.isReady(aImage)) {
aCallback();
} else if (++iterations === MAX_ITERATIONS) {
if (typeof aErrorCallback === "function") aErrorCallback();
console.warn("Image could not be resolved. This shouldn't occur.");
} else {
// requestAnimationFrame preferred over a timeout as
// browsers will fire this when the DOM is actually ready (e.g. Image is rendered)
window.requestAnimationFrame(readyCheck);
}
}
readyCheck();
} | javascript | function onReady(aImage, aCallback, aErrorCallback) {
// if this didn't resolve in a full second, we presume the Image is corrupt
var MAX_ITERATIONS = 60;
var iterations = 0;
function readyCheck() {
if (Loader.isReady(aImage)) {
aCallback();
} else if (++iterations === MAX_ITERATIONS) {
if (typeof aErrorCallback === "function") aErrorCallback();
console.warn("Image could not be resolved. This shouldn't occur.");
} else {
// requestAnimationFrame preferred over a timeout as
// browsers will fire this when the DOM is actually ready (e.g. Image is rendered)
window.requestAnimationFrame(readyCheck);
}
}
readyCheck();
} | [
"function",
"onReady",
"(",
"aImage",
",",
"aCallback",
",",
"aErrorCallback",
")",
"{",
"var",
"MAX_ITERATIONS",
"=",
"60",
";",
"var",
"iterations",
"=",
"0",
";",
"function",
"readyCheck",
"(",
")",
"{",
"if",
"(",
"Loader",
".",
"isReady",
"(",
"aImage",
")",
")",
"{",
"aCallback",
"(",
")",
";",
"}",
"else",
"if",
"(",
"++",
"iterations",
"===",
"MAX_ITERATIONS",
")",
"{",
"if",
"(",
"typeof",
"aErrorCallback",
"===",
"\"function\"",
")",
"aErrorCallback",
"(",
")",
";",
"console",
".",
"warn",
"(",
"\"Image could not be resolved. This shouldn't occur.\"",
")",
";",
"}",
"else",
"{",
"window",
".",
"requestAnimationFrame",
"(",
"readyCheck",
")",
";",
"}",
"}",
"readyCheck",
"(",
")",
";",
"}"
] | Executes given callback when given Image is actually ready for rendering
If the image was ready when this function was called, execution is synchronous
if not it will be made asynchronous via RAF delegation
@public
@param {Image} aImage
@param {!Function} aCallback
@param {!Function=} aErrorCallback optional callback to fire if Image is never ready | [
"Executes",
"given",
"callback",
"when",
"given",
"Image",
"is",
"actually",
"ready",
"for",
"rendering",
"If",
"the",
"image",
"was",
"ready",
"when",
"this",
"function",
"was",
"called",
"execution",
"is",
"synchronous",
"if",
"not",
"it",
"will",
"be",
"made",
"asynchronous",
"via",
"RAF",
"delegation"
] | 8b5cd8e195178a80a9bc4ace7ea0b94dfe6b3f82 | https://github.com/igorski/zCanvas/blob/8b5cd8e195178a80a9bc4ace7ea0b94dfe6b3f82/dist/es5/Loader.js#L143-L166 | train |
scienceai/crossref | source.js | listRequest | function listRequest (path, options = {}, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
}
// serialise options
let opts = [];
for (let k in options) {
// The whole URL *minus* the scheme and "://" (for whatever benighted reason) has to be at most
// 4096 characters long. Taking the extra bloat that `encodeURIComponent()` adds we truncate the
// query to 2000 chars. We could be more precise and regenerate the URL until we reach as close
// as possible to 4096, but frankly if you're searching for a string longer than 2000 characters
// you're probably doing something wrong.
if (k === 'query') {
if (options.query.length > 2000) options.query = options.query.substr(0, 2000);
opts.push(`query=${encodeURIComponent(options.query)}`);
}
else if (k === 'filter') {
let filts = [];
for (let f in options.filter) {
if (Array.isArray(options.filter[f])) {
options.filter[f].forEach(val => {
filts.push(`${f}:${val}`);
});
}
else {
filts.push(`${f}:${options.filter[f]}`);
}
}
opts.push(`filter=${filts.join(',')}`);
}
else if (k === 'facet' && options.facet) opts.push('facet=t');
else opts.push(`${k}=${options[k]}`);
}
if (opts.length) path += `?${opts.join('&')}`;
return GET(path, (err, msg) => {
if (err) return cb(err);
let objects = msg.items;
delete msg.items;
let nextOffset = 0
, isDone = false
, nextOptions
;
// /types is a list but it does not behave like the other lists
// Once again the science.ai League of JStice saves the day papering over inconsistency!
if (msg['items-per-page'] && msg.query) {
nextOffset = msg.query['start-index'] + msg['items-per-page'];
if (nextOffset > msg['total-results']) isDone = true;
nextOptions = assign({}, options, { offset: nextOffset });
}
else {
isDone = true;
nextOptions = assign({}, options);
}
cb(null, objects, nextOptions, isDone, msg);
});
} | javascript | function listRequest (path, options = {}, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
}
// serialise options
let opts = [];
for (let k in options) {
// The whole URL *minus* the scheme and "://" (for whatever benighted reason) has to be at most
// 4096 characters long. Taking the extra bloat that `encodeURIComponent()` adds we truncate the
// query to 2000 chars. We could be more precise and regenerate the URL until we reach as close
// as possible to 4096, but frankly if you're searching for a string longer than 2000 characters
// you're probably doing something wrong.
if (k === 'query') {
if (options.query.length > 2000) options.query = options.query.substr(0, 2000);
opts.push(`query=${encodeURIComponent(options.query)}`);
}
else if (k === 'filter') {
let filts = [];
for (let f in options.filter) {
if (Array.isArray(options.filter[f])) {
options.filter[f].forEach(val => {
filts.push(`${f}:${val}`);
});
}
else {
filts.push(`${f}:${options.filter[f]}`);
}
}
opts.push(`filter=${filts.join(',')}`);
}
else if (k === 'facet' && options.facet) opts.push('facet=t');
else opts.push(`${k}=${options[k]}`);
}
if (opts.length) path += `?${opts.join('&')}`;
return GET(path, (err, msg) => {
if (err) return cb(err);
let objects = msg.items;
delete msg.items;
let nextOffset = 0
, isDone = false
, nextOptions
;
// /types is a list but it does not behave like the other lists
// Once again the science.ai League of JStice saves the day papering over inconsistency!
if (msg['items-per-page'] && msg.query) {
nextOffset = msg.query['start-index'] + msg['items-per-page'];
if (nextOffset > msg['total-results']) isDone = true;
nextOptions = assign({}, options, { offset: nextOffset });
}
else {
isDone = true;
nextOptions = assign({}, options);
}
cb(null, objects, nextOptions, isDone, msg);
});
} | [
"function",
"listRequest",
"(",
"path",
",",
"options",
"=",
"{",
"}",
",",
"cb",
")",
"{",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"cb",
"=",
"options",
";",
"options",
"=",
"{",
"}",
";",
"}",
"let",
"opts",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"k",
"in",
"options",
")",
"{",
"if",
"(",
"k",
"===",
"'query'",
")",
"{",
"if",
"(",
"options",
".",
"query",
".",
"length",
">",
"2000",
")",
"options",
".",
"query",
"=",
"options",
".",
"query",
".",
"substr",
"(",
"0",
",",
"2000",
")",
";",
"opts",
".",
"push",
"(",
"`",
"${",
"encodeURIComponent",
"(",
"options",
".",
"query",
")",
"}",
"`",
")",
";",
"}",
"else",
"if",
"(",
"k",
"===",
"'filter'",
")",
"{",
"let",
"filts",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"f",
"in",
"options",
".",
"filter",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"options",
".",
"filter",
"[",
"f",
"]",
")",
")",
"{",
"options",
".",
"filter",
"[",
"f",
"]",
".",
"forEach",
"(",
"val",
"=>",
"{",
"filts",
".",
"push",
"(",
"`",
"${",
"f",
"}",
"${",
"val",
"}",
"`",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"filts",
".",
"push",
"(",
"`",
"${",
"f",
"}",
"${",
"options",
".",
"filter",
"[",
"f",
"]",
"}",
"`",
")",
";",
"}",
"}",
"opts",
".",
"push",
"(",
"`",
"${",
"filts",
".",
"join",
"(",
"','",
")",
"}",
"`",
")",
";",
"}",
"else",
"if",
"(",
"k",
"===",
"'facet'",
"&&",
"options",
".",
"facet",
")",
"opts",
".",
"push",
"(",
"'facet=t'",
")",
";",
"else",
"opts",
".",
"push",
"(",
"`",
"${",
"k",
"}",
"${",
"options",
"[",
"k",
"]",
"}",
"`",
")",
";",
"}",
"if",
"(",
"opts",
".",
"length",
")",
"path",
"+=",
"`",
"${",
"opts",
".",
"join",
"(",
"'&'",
")",
"}",
"`",
";",
"return",
"GET",
"(",
"path",
",",
"(",
"err",
",",
"msg",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"let",
"objects",
"=",
"msg",
".",
"items",
";",
"delete",
"msg",
".",
"items",
";",
"let",
"nextOffset",
"=",
"0",
",",
"isDone",
"=",
"false",
",",
"nextOptions",
";",
"if",
"(",
"msg",
"[",
"'items-per-page'",
"]",
"&&",
"msg",
".",
"query",
")",
"{",
"nextOffset",
"=",
"msg",
".",
"query",
"[",
"'start-index'",
"]",
"+",
"msg",
"[",
"'items-per-page'",
"]",
";",
"if",
"(",
"nextOffset",
">",
"msg",
"[",
"'total-results'",
"]",
")",
"isDone",
"=",
"true",
";",
"nextOptions",
"=",
"assign",
"(",
"{",
"}",
",",
"options",
",",
"{",
"offset",
":",
"nextOffset",
"}",
")",
";",
"}",
"else",
"{",
"isDone",
"=",
"true",
";",
"nextOptions",
"=",
"assign",
"(",
"{",
"}",
",",
"options",
")",
";",
"}",
"cb",
"(",
"null",
",",
"objects",
",",
"nextOptions",
",",
"isDone",
",",
"msg",
")",
";",
"}",
")",
";",
"}"
] | backend for list requests | [
"backend",
"for",
"list",
"requests"
] | cfda7f2a705663e9bc595a6599329e094f3e3725 | https://github.com/scienceai/crossref/blob/cfda7f2a705663e9bc595a6599329e094f3e3725/source.js#L41-L97 | train |
crysalead-js/string-placeholder | index.js | template | function template(str, data, options) {
var data = data || {};
var options = options || {};
var keys = Array.isArray(data) ? Array.apply(null, { length: data.length }).map(Number.call, Number) : Object.keys(data);
var len = keys.length;
if (!len) {
return str;
}
var before = options.before !== undefined ? options.before : '${';
var after = options.after !== undefined ? options.after : '}';
var escape = options.escape !== undefined ? options.escape : '\\';
var clean = options.clean !== undefined ? options.clean : false;
cache[escape] = cache[escape] || escapeRegExp(escape);
cache[before] = cache[before] || escapeRegExp(before);
cache[after] = cache[after] || escapeRegExp(after);
var begin = escape ? '(' + cache[escape] + ')?' + cache[before] : cache[before];
var end = cache[after];
for (var i = 0; i < len; i++) {
str = str.replace(new RegExp(begin + String(keys[i]) + end, 'g'), function(match, behind) {
return behind ? match : String(data[keys[i]])
});
}
if (escape) {
str = str.replace(new RegExp(escapeRegExp(escape) + escapeRegExp(before), 'g'), before);
}
return clean ? template.clean(str, options) : str;
} | javascript | function template(str, data, options) {
var data = data || {};
var options = options || {};
var keys = Array.isArray(data) ? Array.apply(null, { length: data.length }).map(Number.call, Number) : Object.keys(data);
var len = keys.length;
if (!len) {
return str;
}
var before = options.before !== undefined ? options.before : '${';
var after = options.after !== undefined ? options.after : '}';
var escape = options.escape !== undefined ? options.escape : '\\';
var clean = options.clean !== undefined ? options.clean : false;
cache[escape] = cache[escape] || escapeRegExp(escape);
cache[before] = cache[before] || escapeRegExp(before);
cache[after] = cache[after] || escapeRegExp(after);
var begin = escape ? '(' + cache[escape] + ')?' + cache[before] : cache[before];
var end = cache[after];
for (var i = 0; i < len; i++) {
str = str.replace(new RegExp(begin + String(keys[i]) + end, 'g'), function(match, behind) {
return behind ? match : String(data[keys[i]])
});
}
if (escape) {
str = str.replace(new RegExp(escapeRegExp(escape) + escapeRegExp(before), 'g'), before);
}
return clean ? template.clean(str, options) : str;
} | [
"function",
"template",
"(",
"str",
",",
"data",
",",
"options",
")",
"{",
"var",
"data",
"=",
"data",
"||",
"{",
"}",
";",
"var",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"keys",
"=",
"Array",
".",
"isArray",
"(",
"data",
")",
"?",
"Array",
".",
"apply",
"(",
"null",
",",
"{",
"length",
":",
"data",
".",
"length",
"}",
")",
".",
"map",
"(",
"Number",
".",
"call",
",",
"Number",
")",
":",
"Object",
".",
"keys",
"(",
"data",
")",
";",
"var",
"len",
"=",
"keys",
".",
"length",
";",
"if",
"(",
"!",
"len",
")",
"{",
"return",
"str",
";",
"}",
"var",
"before",
"=",
"options",
".",
"before",
"!==",
"undefined",
"?",
"options",
".",
"before",
":",
"'${'",
";",
"var",
"after",
"=",
"options",
".",
"after",
"!==",
"undefined",
"?",
"options",
".",
"after",
":",
"'}'",
";",
"var",
"escape",
"=",
"options",
".",
"escape",
"!==",
"undefined",
"?",
"options",
".",
"escape",
":",
"'\\\\'",
";",
"\\\\",
"var",
"clean",
"=",
"options",
".",
"clean",
"!==",
"undefined",
"?",
"options",
".",
"clean",
":",
"false",
";",
"cache",
"[",
"escape",
"]",
"=",
"cache",
"[",
"escape",
"]",
"||",
"escapeRegExp",
"(",
"escape",
")",
";",
"cache",
"[",
"before",
"]",
"=",
"cache",
"[",
"before",
"]",
"||",
"escapeRegExp",
"(",
"before",
")",
";",
"cache",
"[",
"after",
"]",
"=",
"cache",
"[",
"after",
"]",
"||",
"escapeRegExp",
"(",
"after",
")",
";",
"var",
"begin",
"=",
"escape",
"?",
"'('",
"+",
"cache",
"[",
"escape",
"]",
"+",
"')?'",
"+",
"cache",
"[",
"before",
"]",
":",
"cache",
"[",
"before",
"]",
";",
"var",
"end",
"=",
"cache",
"[",
"after",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"str",
"=",
"str",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"begin",
"+",
"String",
"(",
"keys",
"[",
"i",
"]",
")",
"+",
"end",
",",
"'g'",
")",
",",
"function",
"(",
"match",
",",
"behind",
")",
"{",
"return",
"behind",
"?",
"match",
":",
"String",
"(",
"data",
"[",
"keys",
"[",
"i",
"]",
"]",
")",
"}",
")",
";",
"}",
"if",
"(",
"escape",
")",
"{",
"str",
"=",
"str",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"escapeRegExp",
"(",
"escape",
")",
"+",
"escapeRegExp",
"(",
"before",
")",
",",
"'g'",
")",
",",
"before",
")",
";",
"}",
"}"
] | Replaces variable placeholders inside a string with any given data. Each key
in `data` corresponds to a variable placeholder name in `str`.
Usage:
{{{
template('My name is ${name} and I am ${age} years old.', { name: 'Bob', age: '65' });
}}}
@param String str A string containing variable place-holders.
@param Object data A key, value array where each key stands for a place-holder variable
name to be replaced with value.
@param Object options Available options are:
- `'before'`: The character or string in front of the name of the variable
place-holder (defaults to `'${'`).
- `'after'`: The character or string after the name of the variable
place-holder (defaults to `}`).
- `'escape'`: The character or string used to escape the before character or string
(defaults to `'\\'`).
- `'clean'`: A boolean or array with instructions for cleaning.
@return String | [
"Replaces",
"variable",
"placeholders",
"inside",
"a",
"string",
"with",
"any",
"given",
"data",
".",
"Each",
"key",
"in",
"data",
"corresponds",
"to",
"a",
"variable",
"placeholder",
"name",
"in",
"str",
"."
] | 73e399bd8ef35ac74118139aa606c00874682e1d | https://github.com/crysalead-js/string-placeholder/blob/73e399bd8ef35ac74118139aa606c00874682e1d/index.js#L28-L61 | train |
flux-capacitor/flux-capacitor | packages/flux-capacitor-boot/src/express/bootstrap.js | bootstrap | function bootstrap (bootstrappers) {
const bootstrapPromise = bootstrappers.reduce(
(metaPromise, bootstrapper) => metaPromise.then((prevMeta) =>
Promise.resolve(bootstrapper(prevMeta)).then((newMeta) => Object.assign({}, prevMeta, newMeta))
),
Promise.resolve({})
).then((meta) => checkIfReadyToBoot(meta))
/**
* @param {int} [port]
* @param {string} [hostname]
* @return {Promise<Http.Server>}
* @see https://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback
*/
bootstrapPromise.listen = function listen (port, hostname) {
return bootstrapPromise.then((meta) => promisifiedListen(meta.app, port, hostname))
}
return bootstrapPromise
} | javascript | function bootstrap (bootstrappers) {
const bootstrapPromise = bootstrappers.reduce(
(metaPromise, bootstrapper) => metaPromise.then((prevMeta) =>
Promise.resolve(bootstrapper(prevMeta)).then((newMeta) => Object.assign({}, prevMeta, newMeta))
),
Promise.resolve({})
).then((meta) => checkIfReadyToBoot(meta))
/**
* @param {int} [port]
* @param {string} [hostname]
* @return {Promise<Http.Server>}
* @see https://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback
*/
bootstrapPromise.listen = function listen (port, hostname) {
return bootstrapPromise.then((meta) => promisifiedListen(meta.app, port, hostname))
}
return bootstrapPromise
} | [
"function",
"bootstrap",
"(",
"bootstrappers",
")",
"{",
"const",
"bootstrapPromise",
"=",
"bootstrappers",
".",
"reduce",
"(",
"(",
"metaPromise",
",",
"bootstrapper",
")",
"=>",
"metaPromise",
".",
"then",
"(",
"(",
"prevMeta",
")",
"=>",
"Promise",
".",
"resolve",
"(",
"bootstrapper",
"(",
"prevMeta",
")",
")",
".",
"then",
"(",
"(",
"newMeta",
")",
"=>",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"prevMeta",
",",
"newMeta",
")",
")",
")",
",",
"Promise",
".",
"resolve",
"(",
"{",
"}",
")",
")",
".",
"then",
"(",
"(",
"meta",
")",
"=>",
"checkIfReadyToBoot",
"(",
"meta",
")",
")",
"bootstrapPromise",
".",
"listen",
"=",
"function",
"listen",
"(",
"port",
",",
"hostname",
")",
"{",
"return",
"bootstrapPromise",
".",
"then",
"(",
"(",
"meta",
")",
"=>",
"promisifiedListen",
"(",
"meta",
".",
"app",
",",
"port",
",",
"hostname",
")",
")",
"}",
"return",
"bootstrapPromise",
"}"
] | Takes an array of bootstrapping functions and returns a Promise extended by a
`listen` method.
@param {Function[]} bootstrappers
@return {FluxCapAppPromise} { listen: ([port: int][, hostname: string]) => Promise<Http.Server>, catch: (Error) => Promise, then: (Function) => Promise } | [
"Takes",
"an",
"array",
"of",
"bootstrapping",
"functions",
"and",
"returns",
"a",
"Promise",
"extended",
"by",
"a",
"listen",
"method",
"."
] | 66393138ecdff9c1ba81d88b53144220e593584f | https://github.com/flux-capacitor/flux-capacitor/blob/66393138ecdff9c1ba81d88b53144220e593584f/packages/flux-capacitor-boot/src/express/bootstrap.js#L10-L29 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.