id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
|---|---|---|---|---|---|---|---|---|---|---|---|
17,000
|
hflabs/suggestions-jquery
|
src/includes/suggestions.js
|
function () {
var that = this,
parentInstance = that.getParentInstance(),
parentValue = parentInstance && parentInstance.extendedCurrentValue(),
currentValue = $.trim(that.el.val());
return utils.compact([parentValue, currentValue]).join(' ');
}
|
javascript
|
function () {
var that = this,
parentInstance = that.getParentInstance(),
parentValue = parentInstance && parentInstance.extendedCurrentValue(),
currentValue = $.trim(that.el.val());
return utils.compact([parentValue, currentValue]).join(' ');
}
|
[
"function",
"(",
")",
"{",
"var",
"that",
"=",
"this",
",",
"parentInstance",
"=",
"that",
".",
"getParentInstance",
"(",
")",
",",
"parentValue",
"=",
"parentInstance",
"&&",
"parentInstance",
".",
"extendedCurrentValue",
"(",
")",
",",
"currentValue",
"=",
"$",
".",
"trim",
"(",
"that",
".",
"el",
".",
"val",
"(",
")",
")",
";",
"return",
"utils",
".",
"compact",
"(",
"[",
"parentValue",
",",
"currentValue",
"]",
")",
".",
"join",
"(",
"' '",
")",
";",
"}"
] |
Querying related methods
Looks up parent instances
@returns {String} current value prepended by parents' values
|
[
"Querying",
"related",
"methods",
"Looks",
"up",
"parent",
"instances"
] |
17e3ac383790069ad4d3dd92185d9fb9e30382a7
|
https://github.com/hflabs/suggestions-jquery/blob/17e3ac383790069ad4d3dd92185d9fb9e30382a7/src/includes/suggestions.js#L471-L478
|
|
17,001
|
hflabs/suggestions-jquery
|
src/includes/suggestions.js
|
function (query, customParams, requestOptions) {
var response,
that = this,
options = that.options,
noCallbacks = requestOptions && requestOptions.noCallbacks,
useEnrichmentCache = requestOptions && requestOptions.useEnrichmentCache,
method = requestOptions && requestOptions.method || that.requestMode.method,
params = that.constructRequestParams(query, customParams),
cacheKey = $.param(params || {}),
resolver = $.Deferred();
response = that.cachedResponse[cacheKey];
if (response && $.isArray(response.suggestions)) {
resolver.resolve(response.suggestions);
} else {
if (that.isBadQuery(query)) {
resolver.reject();
} else {
if (!noCallbacks && options.onSearchStart.call(that.element, params) === false) {
resolver.reject();
} else {
that.doGetSuggestions(params, method)
.done(function (response) {
// if response is correct and current value has not been changed
if (that.processResponse(response) && query == that.currentValue) {
// Cache results if cache is not disabled:
if (!options.noCache) {
if (useEnrichmentCache) {
that.enrichmentCache[query] = response.suggestions[0];
} else {
that.enrichResponse(response, query);
that.cachedResponse[cacheKey] = response;
if (options.preventBadQueries && response.suggestions.length === 0) {
that.badQueries.push(query);
}
}
}
resolver.resolve(response.suggestions);
} else {
resolver.reject();
}
if (!noCallbacks) {
options.onSearchComplete.call(that.element, query, response.suggestions);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
resolver.reject();
if (!noCallbacks && textStatus !== 'abort') {
options.onSearchError.call(that.element, query, jqXHR, textStatus, errorThrown);
}
});
}
}
}
return resolver;
}
|
javascript
|
function (query, customParams, requestOptions) {
var response,
that = this,
options = that.options,
noCallbacks = requestOptions && requestOptions.noCallbacks,
useEnrichmentCache = requestOptions && requestOptions.useEnrichmentCache,
method = requestOptions && requestOptions.method || that.requestMode.method,
params = that.constructRequestParams(query, customParams),
cacheKey = $.param(params || {}),
resolver = $.Deferred();
response = that.cachedResponse[cacheKey];
if (response && $.isArray(response.suggestions)) {
resolver.resolve(response.suggestions);
} else {
if (that.isBadQuery(query)) {
resolver.reject();
} else {
if (!noCallbacks && options.onSearchStart.call(that.element, params) === false) {
resolver.reject();
} else {
that.doGetSuggestions(params, method)
.done(function (response) {
// if response is correct and current value has not been changed
if (that.processResponse(response) && query == that.currentValue) {
// Cache results if cache is not disabled:
if (!options.noCache) {
if (useEnrichmentCache) {
that.enrichmentCache[query] = response.suggestions[0];
} else {
that.enrichResponse(response, query);
that.cachedResponse[cacheKey] = response;
if (options.preventBadQueries && response.suggestions.length === 0) {
that.badQueries.push(query);
}
}
}
resolver.resolve(response.suggestions);
} else {
resolver.reject();
}
if (!noCallbacks) {
options.onSearchComplete.call(that.element, query, response.suggestions);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
resolver.reject();
if (!noCallbacks && textStatus !== 'abort') {
options.onSearchError.call(that.element, query, jqXHR, textStatus, errorThrown);
}
});
}
}
}
return resolver;
}
|
[
"function",
"(",
"query",
",",
"customParams",
",",
"requestOptions",
")",
"{",
"var",
"response",
",",
"that",
"=",
"this",
",",
"options",
"=",
"that",
".",
"options",
",",
"noCallbacks",
"=",
"requestOptions",
"&&",
"requestOptions",
".",
"noCallbacks",
",",
"useEnrichmentCache",
"=",
"requestOptions",
"&&",
"requestOptions",
".",
"useEnrichmentCache",
",",
"method",
"=",
"requestOptions",
"&&",
"requestOptions",
".",
"method",
"||",
"that",
".",
"requestMode",
".",
"method",
",",
"params",
"=",
"that",
".",
"constructRequestParams",
"(",
"query",
",",
"customParams",
")",
",",
"cacheKey",
"=",
"$",
".",
"param",
"(",
"params",
"||",
"{",
"}",
")",
",",
"resolver",
"=",
"$",
".",
"Deferred",
"(",
")",
";",
"response",
"=",
"that",
".",
"cachedResponse",
"[",
"cacheKey",
"]",
";",
"if",
"(",
"response",
"&&",
"$",
".",
"isArray",
"(",
"response",
".",
"suggestions",
")",
")",
"{",
"resolver",
".",
"resolve",
"(",
"response",
".",
"suggestions",
")",
";",
"}",
"else",
"{",
"if",
"(",
"that",
".",
"isBadQuery",
"(",
"query",
")",
")",
"{",
"resolver",
".",
"reject",
"(",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"noCallbacks",
"&&",
"options",
".",
"onSearchStart",
".",
"call",
"(",
"that",
".",
"element",
",",
"params",
")",
"===",
"false",
")",
"{",
"resolver",
".",
"reject",
"(",
")",
";",
"}",
"else",
"{",
"that",
".",
"doGetSuggestions",
"(",
"params",
",",
"method",
")",
".",
"done",
"(",
"function",
"(",
"response",
")",
"{",
"// if response is correct and current value has not been changed",
"if",
"(",
"that",
".",
"processResponse",
"(",
"response",
")",
"&&",
"query",
"==",
"that",
".",
"currentValue",
")",
"{",
"// Cache results if cache is not disabled:",
"if",
"(",
"!",
"options",
".",
"noCache",
")",
"{",
"if",
"(",
"useEnrichmentCache",
")",
"{",
"that",
".",
"enrichmentCache",
"[",
"query",
"]",
"=",
"response",
".",
"suggestions",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"that",
".",
"enrichResponse",
"(",
"response",
",",
"query",
")",
";",
"that",
".",
"cachedResponse",
"[",
"cacheKey",
"]",
"=",
"response",
";",
"if",
"(",
"options",
".",
"preventBadQueries",
"&&",
"response",
".",
"suggestions",
".",
"length",
"===",
"0",
")",
"{",
"that",
".",
"badQueries",
".",
"push",
"(",
"query",
")",
";",
"}",
"}",
"}",
"resolver",
".",
"resolve",
"(",
"response",
".",
"suggestions",
")",
";",
"}",
"else",
"{",
"resolver",
".",
"reject",
"(",
")",
";",
"}",
"if",
"(",
"!",
"noCallbacks",
")",
"{",
"options",
".",
"onSearchComplete",
".",
"call",
"(",
"that",
".",
"element",
",",
"query",
",",
"response",
".",
"suggestions",
")",
";",
"}",
"}",
")",
".",
"fail",
"(",
"function",
"(",
"jqXHR",
",",
"textStatus",
",",
"errorThrown",
")",
"{",
"resolver",
".",
"reject",
"(",
")",
";",
"if",
"(",
"!",
"noCallbacks",
"&&",
"textStatus",
"!==",
"'abort'",
")",
"{",
"options",
".",
"onSearchError",
".",
"call",
"(",
"that",
".",
"element",
",",
"query",
",",
"jqXHR",
",",
"textStatus",
",",
"errorThrown",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
"}",
"return",
"resolver",
";",
"}"
] |
Get suggestions from cache or from server
@param {String} query
@param {Object} customParams parameters specified here will be passed to request body
@param {Object} requestOptions
@param {Boolean} [requestOptions.noCallbacks] flag, request competence callbacks will not be invoked
@param {Boolean} [requestOptions.useEnrichmentCache]
@return {$.Deferred} waiter which is to be resolved with suggestions as argument
|
[
"Get",
"suggestions",
"from",
"cache",
"or",
"from",
"server"
] |
17e3ac383790069ad4d3dd92185d9fb9e30382a7
|
https://github.com/hflabs/suggestions-jquery/blob/17e3ac383790069ad4d3dd92185d9fb9e30382a7/src/includes/suggestions.js#L595-L651
|
|
17,002
|
hflabs/suggestions-jquery
|
src/includes/suggestions.js
|
function (params, method) {
var that = this,
request = $.ajax(
that.getAjaxParams(method, { data: utils.serialize(params) })
);
that.abortRequest();
that.currentRequest = request;
that.notify('request');
request.always(function () {
that.currentRequest = null;
that.notify('request');
});
return request;
}
|
javascript
|
function (params, method) {
var that = this,
request = $.ajax(
that.getAjaxParams(method, { data: utils.serialize(params) })
);
that.abortRequest();
that.currentRequest = request;
that.notify('request');
request.always(function () {
that.currentRequest = null;
that.notify('request');
});
return request;
}
|
[
"function",
"(",
"params",
",",
"method",
")",
"{",
"var",
"that",
"=",
"this",
",",
"request",
"=",
"$",
".",
"ajax",
"(",
"that",
".",
"getAjaxParams",
"(",
"method",
",",
"{",
"data",
":",
"utils",
".",
"serialize",
"(",
"params",
")",
"}",
")",
")",
";",
"that",
".",
"abortRequest",
"(",
")",
";",
"that",
".",
"currentRequest",
"=",
"request",
";",
"that",
".",
"notify",
"(",
"'request'",
")",
";",
"request",
".",
"always",
"(",
"function",
"(",
")",
"{",
"that",
".",
"currentRequest",
"=",
"null",
";",
"that",
".",
"notify",
"(",
"'request'",
")",
";",
"}",
")",
";",
"return",
"request",
";",
"}"
] |
Sends an AJAX request to server suggest method.
@param {Object} params request params
@returns {$.Deferred} response promise
|
[
"Sends",
"an",
"AJAX",
"request",
"to",
"server",
"suggest",
"method",
"."
] |
17e3ac383790069ad4d3dd92185d9fb9e30382a7
|
https://github.com/hflabs/suggestions-jquery/blob/17e3ac383790069ad4d3dd92185d9fb9e30382a7/src/includes/suggestions.js#L658-L674
|
|
17,003
|
hflabs/suggestions-jquery
|
src/includes/suggestions.js
|
function (response) {
var that = this,
suggestions;
if (!response || !$.isArray(response.suggestions)) {
return false;
}
that.verifySuggestionsFormat(response.suggestions);
that.setUnrestrictedValues(response.suggestions);
if ($.isFunction(that.options.onSuggestionsFetch)) {
suggestions = that.options.onSuggestionsFetch.call(that.element, response.suggestions);
if ($.isArray(suggestions)) {
response.suggestions = suggestions;
}
}
return true;
}
|
javascript
|
function (response) {
var that = this,
suggestions;
if (!response || !$.isArray(response.suggestions)) {
return false;
}
that.verifySuggestionsFormat(response.suggestions);
that.setUnrestrictedValues(response.suggestions);
if ($.isFunction(that.options.onSuggestionsFetch)) {
suggestions = that.options.onSuggestionsFetch.call(that.element, response.suggestions);
if ($.isArray(suggestions)) {
response.suggestions = suggestions;
}
}
return true;
}
|
[
"function",
"(",
"response",
")",
"{",
"var",
"that",
"=",
"this",
",",
"suggestions",
";",
"if",
"(",
"!",
"response",
"||",
"!",
"$",
".",
"isArray",
"(",
"response",
".",
"suggestions",
")",
")",
"{",
"return",
"false",
";",
"}",
"that",
".",
"verifySuggestionsFormat",
"(",
"response",
".",
"suggestions",
")",
";",
"that",
".",
"setUnrestrictedValues",
"(",
"response",
".",
"suggestions",
")",
";",
"if",
"(",
"$",
".",
"isFunction",
"(",
"that",
".",
"options",
".",
"onSuggestionsFetch",
")",
")",
"{",
"suggestions",
"=",
"that",
".",
"options",
".",
"onSuggestionsFetch",
".",
"call",
"(",
"that",
".",
"element",
",",
"response",
".",
"suggestions",
")",
";",
"if",
"(",
"$",
".",
"isArray",
"(",
"suggestions",
")",
")",
"{",
"response",
".",
"suggestions",
"=",
"suggestions",
";",
"}",
"}",
"return",
"true",
";",
"}"
] |
Checks response format and data
@return {Boolean} response contains acceptable data
|
[
"Checks",
"response",
"format",
"and",
"data"
] |
17e3ac383790069ad4d3dd92185d9fb9e30382a7
|
https://github.com/hflabs/suggestions-jquery/blob/17e3ac383790069ad4d3dd92185d9fb9e30382a7/src/includes/suggestions.js#L700-L719
|
|
17,004
|
hflabs/suggestions-jquery
|
src/includes/suggestions.js
|
function (suggestion, selectionOptions) {
var that = this,
formatSelected = that.options.formatSelected || that.type.formatSelected,
hasSameValues = selectionOptions && selectionOptions.hasSameValues,
hasBeenEnriched = selectionOptions && selectionOptions.hasBeenEnriched,
formattedValue,
typeFormattedValue = null;
if ($.isFunction(formatSelected)) {
formattedValue = formatSelected.call(that, suggestion);
}
if (typeof formattedValue !== 'string') {
formattedValue = suggestion.value;
if (that.type.getSuggestionValue) {
typeFormattedValue = that.type.getSuggestionValue(that, {
suggestion: suggestion,
hasSameValues: hasSameValues,
hasBeenEnriched: hasBeenEnriched,
});
if (typeFormattedValue !== null) {
formattedValue = typeFormattedValue;
}
}
}
return formattedValue;
}
|
javascript
|
function (suggestion, selectionOptions) {
var that = this,
formatSelected = that.options.formatSelected || that.type.formatSelected,
hasSameValues = selectionOptions && selectionOptions.hasSameValues,
hasBeenEnriched = selectionOptions && selectionOptions.hasBeenEnriched,
formattedValue,
typeFormattedValue = null;
if ($.isFunction(formatSelected)) {
formattedValue = formatSelected.call(that, suggestion);
}
if (typeof formattedValue !== 'string') {
formattedValue = suggestion.value;
if (that.type.getSuggestionValue) {
typeFormattedValue = that.type.getSuggestionValue(that, {
suggestion: suggestion,
hasSameValues: hasSameValues,
hasBeenEnriched: hasBeenEnriched,
});
if (typeFormattedValue !== null) {
formattedValue = typeFormattedValue;
}
}
}
return formattedValue;
}
|
[
"function",
"(",
"suggestion",
",",
"selectionOptions",
")",
"{",
"var",
"that",
"=",
"this",
",",
"formatSelected",
"=",
"that",
".",
"options",
".",
"formatSelected",
"||",
"that",
".",
"type",
".",
"formatSelected",
",",
"hasSameValues",
"=",
"selectionOptions",
"&&",
"selectionOptions",
".",
"hasSameValues",
",",
"hasBeenEnriched",
"=",
"selectionOptions",
"&&",
"selectionOptions",
".",
"hasBeenEnriched",
",",
"formattedValue",
",",
"typeFormattedValue",
"=",
"null",
";",
"if",
"(",
"$",
".",
"isFunction",
"(",
"formatSelected",
")",
")",
"{",
"formattedValue",
"=",
"formatSelected",
".",
"call",
"(",
"that",
",",
"suggestion",
")",
";",
"}",
"if",
"(",
"typeof",
"formattedValue",
"!==",
"'string'",
")",
"{",
"formattedValue",
"=",
"suggestion",
".",
"value",
";",
"if",
"(",
"that",
".",
"type",
".",
"getSuggestionValue",
")",
"{",
"typeFormattedValue",
"=",
"that",
".",
"type",
".",
"getSuggestionValue",
"(",
"that",
",",
"{",
"suggestion",
":",
"suggestion",
",",
"hasSameValues",
":",
"hasSameValues",
",",
"hasBeenEnriched",
":",
"hasBeenEnriched",
",",
"}",
")",
";",
"if",
"(",
"typeFormattedValue",
"!==",
"null",
")",
"{",
"formattedValue",
"=",
"typeFormattedValue",
";",
"}",
"}",
"}",
"return",
"formattedValue",
";",
"}"
] |
Gets string to set as input value
@param suggestion
@param {Object} [selectionOptions]
@param {boolean} selectionOptions.hasBeenEnriched
@param {boolean} selectionOptions.hasSameValues
@return {string}
|
[
"Gets",
"string",
"to",
"set",
"as",
"input",
"value"
] |
17e3ac383790069ad4d3dd92185d9fb9e30382a7
|
https://github.com/hflabs/suggestions-jquery/blob/17e3ac383790069ad4d3dd92185d9fb9e30382a7/src/includes/suggestions.js#L738-L768
|
|
17,005
|
hflabs/suggestions-jquery
|
src/includes/suggestions.js
|
function (suggestions) {
var that = this,
shouldRestrict = that.shouldRestrictValues(),
label = that.getFirstConstraintLabel();
$.each(suggestions, function (i, suggestion) {
if (!suggestion.unrestricted_value) {
suggestion.unrestricted_value = shouldRestrict ? label + ', ' + suggestion.value : suggestion.value;
}
});
}
|
javascript
|
function (suggestions) {
var that = this,
shouldRestrict = that.shouldRestrictValues(),
label = that.getFirstConstraintLabel();
$.each(suggestions, function (i, suggestion) {
if (!suggestion.unrestricted_value) {
suggestion.unrestricted_value = shouldRestrict ? label + ', ' + suggestion.value : suggestion.value;
}
});
}
|
[
"function",
"(",
"suggestions",
")",
"{",
"var",
"that",
"=",
"this",
",",
"shouldRestrict",
"=",
"that",
".",
"shouldRestrictValues",
"(",
")",
",",
"label",
"=",
"that",
".",
"getFirstConstraintLabel",
"(",
")",
";",
"$",
".",
"each",
"(",
"suggestions",
",",
"function",
"(",
"i",
",",
"suggestion",
")",
"{",
"if",
"(",
"!",
"suggestion",
".",
"unrestricted_value",
")",
"{",
"suggestion",
".",
"unrestricted_value",
"=",
"shouldRestrict",
"?",
"label",
"+",
"', '",
"+",
"suggestion",
".",
"value",
":",
"suggestion",
".",
"value",
";",
"}",
"}",
")",
";",
"}"
] |
Fills suggestion.unrestricted_value property
|
[
"Fills",
"suggestion",
".",
"unrestricted_value",
"property"
] |
17e3ac383790069ad4d3dd92185d9fb9e30382a7
|
https://github.com/hflabs/suggestions-jquery/blob/17e3ac383790069ad4d3dd92185d9fb9e30382a7/src/includes/suggestions.js#L801-L811
|
|
17,006
|
hflabs/suggestions-jquery
|
src/includes/matchers.js
|
sameParentChecker
|
function sameParentChecker (preprocessFn) {
return function (suggestions) {
if (suggestions.length === 0) {
return false;
}
if (suggestions.length === 1) {
return true;
}
var parentValue = preprocessFn(suggestions[0].value),
aliens = suggestions.filter(function (suggestion) {
return preprocessFn(suggestion.value).indexOf(parentValue) !== 0;
});
return aliens.length === 0;
}
}
|
javascript
|
function sameParentChecker (preprocessFn) {
return function (suggestions) {
if (suggestions.length === 0) {
return false;
}
if (suggestions.length === 1) {
return true;
}
var parentValue = preprocessFn(suggestions[0].value),
aliens = suggestions.filter(function (suggestion) {
return preprocessFn(suggestion.value).indexOf(parentValue) !== 0;
});
return aliens.length === 0;
}
}
|
[
"function",
"sameParentChecker",
"(",
"preprocessFn",
")",
"{",
"return",
"function",
"(",
"suggestions",
")",
"{",
"if",
"(",
"suggestions",
".",
"length",
"===",
"0",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"suggestions",
".",
"length",
"===",
"1",
")",
"{",
"return",
"true",
";",
"}",
"var",
"parentValue",
"=",
"preprocessFn",
"(",
"suggestions",
"[",
"0",
"]",
".",
"value",
")",
",",
"aliens",
"=",
"suggestions",
".",
"filter",
"(",
"function",
"(",
"suggestion",
")",
"{",
"return",
"preprocessFn",
"(",
"suggestion",
".",
"value",
")",
".",
"indexOf",
"(",
"parentValue",
")",
"!==",
"0",
";",
"}",
")",
";",
"return",
"aliens",
".",
"length",
"===",
"0",
";",
"}",
"}"
] |
Factory to create same parent checker function
@param preprocessFn called on each value before comparison
@returns {Function} same parent checker function
|
[
"Factory",
"to",
"create",
"same",
"parent",
"checker",
"function"
] |
17e3ac383790069ad4d3dd92185d9fb9e30382a7
|
https://github.com/hflabs/suggestions-jquery/blob/17e3ac383790069ad4d3dd92185d9fb9e30382a7/src/includes/matchers.js#L10-L26
|
17,007
|
hflabs/suggestions-jquery
|
src/includes/constraints.js
|
belongsToArea
|
function belongsToArea(suggestion, instance){
var parentSuggestion = instance.selection,
result = parentSuggestion && parentSuggestion.data && instance.bounds;
if (result) {
collection_util.each(instance.bounds.all, function (bound, i) {
return (result = parentSuggestion.data[bound] === suggestion.data[bound]);
});
}
return result;
}
|
javascript
|
function belongsToArea(suggestion, instance){
var parentSuggestion = instance.selection,
result = parentSuggestion && parentSuggestion.data && instance.bounds;
if (result) {
collection_util.each(instance.bounds.all, function (bound, i) {
return (result = parentSuggestion.data[bound] === suggestion.data[bound]);
});
}
return result;
}
|
[
"function",
"belongsToArea",
"(",
"suggestion",
",",
"instance",
")",
"{",
"var",
"parentSuggestion",
"=",
"instance",
".",
"selection",
",",
"result",
"=",
"parentSuggestion",
"&&",
"parentSuggestion",
".",
"data",
"&&",
"instance",
".",
"bounds",
";",
"if",
"(",
"result",
")",
"{",
"collection_util",
".",
"each",
"(",
"instance",
".",
"bounds",
".",
"all",
",",
"function",
"(",
"bound",
",",
"i",
")",
"{",
"return",
"(",
"result",
"=",
"parentSuggestion",
".",
"data",
"[",
"bound",
"]",
"===",
"suggestion",
".",
"data",
"[",
"bound",
"]",
")",
";",
"}",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Compares two suggestion objects
@param suggestion
@param instance other Suggestions instance
|
[
"Compares",
"two",
"suggestion",
"objects"
] |
17e3ac383790069ad4d3dd92185d9fb9e30382a7
|
https://github.com/hflabs/suggestions-jquery/blob/17e3ac383790069ad4d3dd92185d9fb9e30382a7/src/includes/constraints.js#L34-L44
|
17,008
|
hflabs/suggestions-jquery
|
src/includes/constraints.js
|
function (data) {
var that = this,
restrictedKeys = [],
unrestrictedData = {},
maxSpecificity = -1;
// Find most specific location that could restrict current data
collection_util.each(that.constraints, function (constraint, id) {
collection_util.each(constraint.locations, function (location, i) {
if (location.containsData(data) && location.specificity > maxSpecificity) {
maxSpecificity = location.specificity;
}
});
});
if (maxSpecificity >= 0) {
// Для городов-регионов нужно также отсечь и город
if (data.region_kladr_id && data.region_kladr_id === data.city_kladr_id) {
restrictedKeys.push.apply(restrictedKeys, that.type.dataComponentsById['city'].fields);
}
// Collect all fieldnames from all restricted components
collection_util.each(that.type.dataComponents.slice(0, maxSpecificity + 1), function (component, i) {
restrictedKeys.push.apply(restrictedKeys, component.fields);
});
// Copy skipping restricted fields
collection_util.each(data, function (value, key) {
if (restrictedKeys.indexOf(key) === -1) {
unrestrictedData[key] = value;
}
});
} else {
unrestrictedData = data;
}
return unrestrictedData;
}
|
javascript
|
function (data) {
var that = this,
restrictedKeys = [],
unrestrictedData = {},
maxSpecificity = -1;
// Find most specific location that could restrict current data
collection_util.each(that.constraints, function (constraint, id) {
collection_util.each(constraint.locations, function (location, i) {
if (location.containsData(data) && location.specificity > maxSpecificity) {
maxSpecificity = location.specificity;
}
});
});
if (maxSpecificity >= 0) {
// Для городов-регионов нужно также отсечь и город
if (data.region_kladr_id && data.region_kladr_id === data.city_kladr_id) {
restrictedKeys.push.apply(restrictedKeys, that.type.dataComponentsById['city'].fields);
}
// Collect all fieldnames from all restricted components
collection_util.each(that.type.dataComponents.slice(0, maxSpecificity + 1), function (component, i) {
restrictedKeys.push.apply(restrictedKeys, component.fields);
});
// Copy skipping restricted fields
collection_util.each(data, function (value, key) {
if (restrictedKeys.indexOf(key) === -1) {
unrestrictedData[key] = value;
}
});
} else {
unrestrictedData = data;
}
return unrestrictedData;
}
|
[
"function",
"(",
"data",
")",
"{",
"var",
"that",
"=",
"this",
",",
"restrictedKeys",
"=",
"[",
"]",
",",
"unrestrictedData",
"=",
"{",
"}",
",",
"maxSpecificity",
"=",
"-",
"1",
";",
"// Find most specific location that could restrict current data",
"collection_util",
".",
"each",
"(",
"that",
".",
"constraints",
",",
"function",
"(",
"constraint",
",",
"id",
")",
"{",
"collection_util",
".",
"each",
"(",
"constraint",
".",
"locations",
",",
"function",
"(",
"location",
",",
"i",
")",
"{",
"if",
"(",
"location",
".",
"containsData",
"(",
"data",
")",
"&&",
"location",
".",
"specificity",
">",
"maxSpecificity",
")",
"{",
"maxSpecificity",
"=",
"location",
".",
"specificity",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"if",
"(",
"maxSpecificity",
">=",
"0",
")",
"{",
"// Для городов-регионов нужно также отсечь и город",
"if",
"(",
"data",
".",
"region_kladr_id",
"&&",
"data",
".",
"region_kladr_id",
"===",
"data",
".",
"city_kladr_id",
")",
"{",
"restrictedKeys",
".",
"push",
".",
"apply",
"(",
"restrictedKeys",
",",
"that",
".",
"type",
".",
"dataComponentsById",
"[",
"'city'",
"]",
".",
"fields",
")",
";",
"}",
"// Collect all fieldnames from all restricted components",
"collection_util",
".",
"each",
"(",
"that",
".",
"type",
".",
"dataComponents",
".",
"slice",
"(",
"0",
",",
"maxSpecificity",
"+",
"1",
")",
",",
"function",
"(",
"component",
",",
"i",
")",
"{",
"restrictedKeys",
".",
"push",
".",
"apply",
"(",
"restrictedKeys",
",",
"component",
".",
"fields",
")",
";",
"}",
")",
";",
"// Copy skipping restricted fields",
"collection_util",
".",
"each",
"(",
"data",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"if",
"(",
"restrictedKeys",
".",
"indexOf",
"(",
"key",
")",
"===",
"-",
"1",
")",
"{",
"unrestrictedData",
"[",
"key",
"]",
"=",
"value",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"unrestrictedData",
"=",
"data",
";",
"}",
"return",
"unrestrictedData",
";",
"}"
] |
Pick only fields that absent in restriction
|
[
"Pick",
"only",
"fields",
"that",
"absent",
"in",
"restriction"
] |
17e3ac383790069ad4d3dd92185d9fb9e30382a7
|
https://github.com/hflabs/suggestions-jquery/blob/17e3ac383790069ad4d3dd92185d9fb9e30382a7/src/includes/constraints.js#L467-L505
|
|
17,009
|
marcoslin/angularAMD
|
dist/angularAMD.js
|
setAlternateAngular
|
function setAlternateAngular() {
// This method cannot be called more than once
if (alt_angular) {
throw new Error('setAlternateAngular can only be called once.');
} else {
alt_angular = {};
}
// Make sure that bootstrap has been called
checkBootstrapped();
// Create a a copy of orig_angular with on demand loading capability
orig_angular.extend(alt_angular, orig_angular);
// Custom version of angular.module used as cache
alt_angular.module = function (name, requires) {
if (typeof requires === 'undefined') {
// Return module from alternate_modules if it was created using the alt_angular
if (alternate_modules_tracker.hasOwnProperty(name)) {
return alternate_modules[name];
} else {
return orig_angular.module(name);
}
} else {
var orig_mod = orig_angular.module.apply(null, arguments),
item = { name: name, module: orig_mod};
alternate_queue.push(item);
orig_angular.extend(orig_mod, onDemandLoader);
/*
Use `alternate_modules_tracker` to track which module has been created by alt_angular
but use `alternate_modules` to cache the module created. This is to simplify the
removal of cached modules after .processQueue.
*/
alternate_modules_tracker[name] = true;
alternate_modules[name] = orig_mod;
// Return created module
return orig_mod;
}
};
window.angular = alt_angular;
if (require.defined('angular')) {
require.undef('angular');
define('angular', [], alt_angular);
}
}
|
javascript
|
function setAlternateAngular() {
// This method cannot be called more than once
if (alt_angular) {
throw new Error('setAlternateAngular can only be called once.');
} else {
alt_angular = {};
}
// Make sure that bootstrap has been called
checkBootstrapped();
// Create a a copy of orig_angular with on demand loading capability
orig_angular.extend(alt_angular, orig_angular);
// Custom version of angular.module used as cache
alt_angular.module = function (name, requires) {
if (typeof requires === 'undefined') {
// Return module from alternate_modules if it was created using the alt_angular
if (alternate_modules_tracker.hasOwnProperty(name)) {
return alternate_modules[name];
} else {
return orig_angular.module(name);
}
} else {
var orig_mod = orig_angular.module.apply(null, arguments),
item = { name: name, module: orig_mod};
alternate_queue.push(item);
orig_angular.extend(orig_mod, onDemandLoader);
/*
Use `alternate_modules_tracker` to track which module has been created by alt_angular
but use `alternate_modules` to cache the module created. This is to simplify the
removal of cached modules after .processQueue.
*/
alternate_modules_tracker[name] = true;
alternate_modules[name] = orig_mod;
// Return created module
return orig_mod;
}
};
window.angular = alt_angular;
if (require.defined('angular')) {
require.undef('angular');
define('angular', [], alt_angular);
}
}
|
[
"function",
"setAlternateAngular",
"(",
")",
"{",
"// This method cannot be called more than once",
"if",
"(",
"alt_angular",
")",
"{",
"throw",
"new",
"Error",
"(",
"'setAlternateAngular can only be called once.'",
")",
";",
"}",
"else",
"{",
"alt_angular",
"=",
"{",
"}",
";",
"}",
"// Make sure that bootstrap has been called",
"checkBootstrapped",
"(",
")",
";",
"// Create a a copy of orig_angular with on demand loading capability",
"orig_angular",
".",
"extend",
"(",
"alt_angular",
",",
"orig_angular",
")",
";",
"// Custom version of angular.module used as cache",
"alt_angular",
".",
"module",
"=",
"function",
"(",
"name",
",",
"requires",
")",
"{",
"if",
"(",
"typeof",
"requires",
"===",
"'undefined'",
")",
"{",
"// Return module from alternate_modules if it was created using the alt_angular",
"if",
"(",
"alternate_modules_tracker",
".",
"hasOwnProperty",
"(",
"name",
")",
")",
"{",
"return",
"alternate_modules",
"[",
"name",
"]",
";",
"}",
"else",
"{",
"return",
"orig_angular",
".",
"module",
"(",
"name",
")",
";",
"}",
"}",
"else",
"{",
"var",
"orig_mod",
"=",
"orig_angular",
".",
"module",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
",",
"item",
"=",
"{",
"name",
":",
"name",
",",
"module",
":",
"orig_mod",
"}",
";",
"alternate_queue",
".",
"push",
"(",
"item",
")",
";",
"orig_angular",
".",
"extend",
"(",
"orig_mod",
",",
"onDemandLoader",
")",
";",
"/*\n Use `alternate_modules_tracker` to track which module has been created by alt_angular\n but use `alternate_modules` to cache the module created. This is to simplify the\n removal of cached modules after .processQueue.\n */",
"alternate_modules_tracker",
"[",
"name",
"]",
"=",
"true",
";",
"alternate_modules",
"[",
"name",
"]",
"=",
"orig_mod",
";",
"// Return created module",
"return",
"orig_mod",
";",
"}",
"}",
";",
"window",
".",
"angular",
"=",
"alt_angular",
";",
"if",
"(",
"require",
".",
"defined",
"(",
"'angular'",
")",
")",
"{",
"require",
".",
"undef",
"(",
"'angular'",
")",
";",
"define",
"(",
"'angular'",
",",
"[",
"]",
",",
"alt_angular",
")",
";",
"}",
"}"
] |
Create an alternate angular so that subsequent call to angular.module will queue up
the module created for later processing via the .processQueue method.
This delaying processing is needed as angular does not recognize any newly created
module after angular.bootstrap has ran. The only way to add new objects to angular
post bootstrap is using cached provider.
Once the modules has been queued, processQueue would then use each module's _invokeQueue
and _runBlock to recreate object using cached $provider. In essence, creating a duplicate
object into the current ng-app. As result, if there are subsequent call to retrieve the
module post processQueue, it would retrieve a module that is not integrated into the ng-app.
Therefore, any subsequent to call to angular.module after processQueue should return undefined
to prevent obtaining a duplicated object. However, it is critical that angular.module return
appropriate object *during* processQueue.
|
[
"Create",
"an",
"alternate",
"angular",
"so",
"that",
"subsequent",
"call",
"to",
"angular",
".",
"module",
"will",
"queue",
"up",
"the",
"module",
"created",
"for",
"later",
"processing",
"via",
"the",
".",
"processQueue",
"method",
"."
] |
f379eb66a9e4d2ab5e49b2455ee48e624ccde047
|
https://github.com/marcoslin/angularAMD/blob/f379eb66a9e4d2ab5e49b2455ee48e624ccde047/dist/angularAMD.js#L56-L104
|
17,010
|
MathieuLoutre/mock-aws-s3
|
lib/mock.js
|
applyBasePath
|
function applyBasePath(search) {
if (_.isUndefined(config.basePath)) {
return search;
}
var modifyKeys = ['Bucket', 'CopySource'];
var ret = _.mapObject(search, function (value, key) {
if (_.indexOf(modifyKeys, key) === -1) {
return value;
}
else {
return config.basePath + '/' + value;
}
})
return ret;
}
|
javascript
|
function applyBasePath(search) {
if (_.isUndefined(config.basePath)) {
return search;
}
var modifyKeys = ['Bucket', 'CopySource'];
var ret = _.mapObject(search, function (value, key) {
if (_.indexOf(modifyKeys, key) === -1) {
return value;
}
else {
return config.basePath + '/' + value;
}
})
return ret;
}
|
[
"function",
"applyBasePath",
"(",
"search",
")",
"{",
"if",
"(",
"_",
".",
"isUndefined",
"(",
"config",
".",
"basePath",
")",
")",
"{",
"return",
"search",
";",
"}",
"var",
"modifyKeys",
"=",
"[",
"'Bucket'",
",",
"'CopySource'",
"]",
";",
"var",
"ret",
"=",
"_",
".",
"mapObject",
"(",
"search",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"if",
"(",
"_",
".",
"indexOf",
"(",
"modifyKeys",
",",
"key",
")",
"===",
"-",
"1",
")",
"{",
"return",
"value",
";",
"}",
"else",
"{",
"return",
"config",
".",
"basePath",
"+",
"'/'",
"+",
"value",
";",
"}",
"}",
")",
"return",
"ret",
";",
"}"
] |
Add basePath to selected keys
|
[
"Add",
"basePath",
"to",
"selected",
"keys"
] |
ee822c5659c9e1bb6b359ef5def5abb781ff5de2
|
https://github.com/MathieuLoutre/mock-aws-s3/blob/ee822c5659c9e1bb6b359ef5def5abb781ff5de2/lib/mock.js#L43-L61
|
17,011
|
MathieuLoutre/mock-aws-s3
|
lib/mock.js
|
S3Mock
|
function S3Mock(options) {
if (!_.isUndefined(options) && !_.isUndefined(options.params)) {
this.defaultOptions = _.extend({}, applyBasePath(options.params));
}
this.config = {
update: function() {}
};
}
|
javascript
|
function S3Mock(options) {
if (!_.isUndefined(options) && !_.isUndefined(options.params)) {
this.defaultOptions = _.extend({}, applyBasePath(options.params));
}
this.config = {
update: function() {}
};
}
|
[
"function",
"S3Mock",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isUndefined",
"(",
"options",
")",
"&&",
"!",
"_",
".",
"isUndefined",
"(",
"options",
".",
"params",
")",
")",
"{",
"this",
".",
"defaultOptions",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"applyBasePath",
"(",
"options",
".",
"params",
")",
")",
";",
"}",
"this",
".",
"config",
"=",
"{",
"update",
":",
"function",
"(",
")",
"{",
"}",
"}",
";",
"}"
] |
Mocks key pieces of the amazon s3 sdk
|
[
"Mocks",
"key",
"pieces",
"of",
"the",
"amazon",
"s3",
"sdk"
] |
ee822c5659c9e1bb6b359ef5def5abb781ff5de2
|
https://github.com/MathieuLoutre/mock-aws-s3/blob/ee822c5659c9e1bb6b359ef5def5abb781ff5de2/lib/mock.js#L104-L112
|
17,012
|
MathieuLoutre/mock-aws-s3
|
lib/mock.js
|
function(params, callback) {
var err = null;
if (typeof(params) === "object" && params !== null)
{
if(typeof(params.Bucket) !== "string" || params.Bucket.length <= 0)
{
err = new Error("Mock-AWS-S3: Argument 'params' must contain a 'Bucket' (String) property");
}
}
else {
err = new Error("Mock-AWS-S3: Argument 'params' must be an Object");
}
var opts = _.extend({}, this.defaultOptions, applyBasePath(params));
if (err !== null) {
callback(err);
}
var bucketPath = opts.basePath || "";
bucketPath += opts.Bucket;
fs.remove(bucketPath, function(err) {
return callback(err);
});
}
|
javascript
|
function(params, callback) {
var err = null;
if (typeof(params) === "object" && params !== null)
{
if(typeof(params.Bucket) !== "string" || params.Bucket.length <= 0)
{
err = new Error("Mock-AWS-S3: Argument 'params' must contain a 'Bucket' (String) property");
}
}
else {
err = new Error("Mock-AWS-S3: Argument 'params' must be an Object");
}
var opts = _.extend({}, this.defaultOptions, applyBasePath(params));
if (err !== null) {
callback(err);
}
var bucketPath = opts.basePath || "";
bucketPath += opts.Bucket;
fs.remove(bucketPath, function(err) {
return callback(err);
});
}
|
[
"function",
"(",
"params",
",",
"callback",
")",
"{",
"var",
"err",
"=",
"null",
";",
"if",
"(",
"typeof",
"(",
"params",
")",
"===",
"\"object\"",
"&&",
"params",
"!==",
"null",
")",
"{",
"if",
"(",
"typeof",
"(",
"params",
".",
"Bucket",
")",
"!==",
"\"string\"",
"||",
"params",
".",
"Bucket",
".",
"length",
"<=",
"0",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"\"Mock-AWS-S3: Argument 'params' must contain a 'Bucket' (String) property\"",
")",
";",
"}",
"}",
"else",
"{",
"err",
"=",
"new",
"Error",
"(",
"\"Mock-AWS-S3: Argument 'params' must be an Object\"",
")",
";",
"}",
"var",
"opts",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"this",
".",
"defaultOptions",
",",
"applyBasePath",
"(",
"params",
")",
")",
";",
"if",
"(",
"err",
"!==",
"null",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"var",
"bucketPath",
"=",
"opts",
".",
"basePath",
"||",
"\"\"",
";",
"bucketPath",
"+=",
"opts",
".",
"Bucket",
";",
"fs",
".",
"remove",
"(",
"bucketPath",
",",
"function",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
] |
Deletes a bucket. Behaviour as createBucket
@param params {Bucket: bucketName}. Name of bucket to delete
@param callback
@returns void
|
[
"Deletes",
"a",
"bucket",
".",
"Behaviour",
"as",
"createBucket"
] |
ee822c5659c9e1bb6b359ef5def5abb781ff5de2
|
https://github.com/MathieuLoutre/mock-aws-s3/blob/ee822c5659c9e1bb6b359ef5def5abb781ff5de2/lib/mock.js#L390-L416
|
|
17,013
|
publiclab/webjack
|
examples/crc8/crc8.js
|
CRC8
|
function CRC8(polynomial) { // constructor takes an optional polynomial type from CRC8.POLY
if (polynomial == null) polynomial = CRC8.POLY.CRC8_CCITT
//if (polynomial == null) polynomial = CRC8.POLY.CRC8_DALLAS_MAXIM
this.table = CRC8.generateTable(polynomial);
}
|
javascript
|
function CRC8(polynomial) { // constructor takes an optional polynomial type from CRC8.POLY
if (polynomial == null) polynomial = CRC8.POLY.CRC8_CCITT
//if (polynomial == null) polynomial = CRC8.POLY.CRC8_DALLAS_MAXIM
this.table = CRC8.generateTable(polynomial);
}
|
[
"function",
"CRC8",
"(",
"polynomial",
")",
"{",
"// constructor takes an optional polynomial type from CRC8.POLY",
"if",
"(",
"polynomial",
"==",
"null",
")",
"polynomial",
"=",
"CRC8",
".",
"POLY",
".",
"CRC8_CCITT",
"//if (polynomial == null) polynomial = CRC8.POLY.CRC8_DALLAS_MAXIM",
"this",
".",
"table",
"=",
"CRC8",
".",
"generateTable",
"(",
"polynomial",
")",
";",
"}"
] |
"Class" for calculating CRC8 checksums...
|
[
"Class",
"for",
"calculating",
"CRC8",
"checksums",
"..."
] |
0976e0da7ff6bbb536637e8d12398ca1d20ce7ca
|
https://github.com/publiclab/webjack/blob/0976e0da7ff6bbb536637e8d12398ca1d20ce7ca/examples/crc8/crc8.js#L3-L8
|
17,014
|
alecsgone/jsx-render
|
src/dom.js
|
createElements
|
function createElements(tagName, attrs, children) {
const element = isSVG(tagName)
? document.createElementNS('http://www.w3.org/2000/svg', tagName)
: document.createElement(tagName)
// one or multiple will be evaluated to append as string or HTMLElement
const fragment = createFragmentFrom(children)
element.appendChild(fragment)
Object.keys(attrs || {}).forEach(prop => {
if (prop === 'style') {
// e.g. origin: <element style={{ prop: value }} />
Object.assign(element.style, attrs[prop])
} else if (prop === 'ref' && typeof attrs.ref === 'function') {
attrs.ref(element, attrs)
} else if (prop === 'className') {
element.setAttribute('class', attrs[prop])
} else if (prop === 'xlinkHref') {
element.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', attrs[prop])
} else if (prop === 'dangerouslySetInnerHTML') {
// eslint-disable-next-line no-underscore-dangle
element.innerHTML = attrs[prop].__html
} else {
// any other prop will be set as attribute
element.setAttribute(prop, attrs[prop])
}
})
return element
}
|
javascript
|
function createElements(tagName, attrs, children) {
const element = isSVG(tagName)
? document.createElementNS('http://www.w3.org/2000/svg', tagName)
: document.createElement(tagName)
// one or multiple will be evaluated to append as string or HTMLElement
const fragment = createFragmentFrom(children)
element.appendChild(fragment)
Object.keys(attrs || {}).forEach(prop => {
if (prop === 'style') {
// e.g. origin: <element style={{ prop: value }} />
Object.assign(element.style, attrs[prop])
} else if (prop === 'ref' && typeof attrs.ref === 'function') {
attrs.ref(element, attrs)
} else if (prop === 'className') {
element.setAttribute('class', attrs[prop])
} else if (prop === 'xlinkHref') {
element.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', attrs[prop])
} else if (prop === 'dangerouslySetInnerHTML') {
// eslint-disable-next-line no-underscore-dangle
element.innerHTML = attrs[prop].__html
} else {
// any other prop will be set as attribute
element.setAttribute(prop, attrs[prop])
}
})
return element
}
|
[
"function",
"createElements",
"(",
"tagName",
",",
"attrs",
",",
"children",
")",
"{",
"const",
"element",
"=",
"isSVG",
"(",
"tagName",
")",
"?",
"document",
".",
"createElementNS",
"(",
"'http://www.w3.org/2000/svg'",
",",
"tagName",
")",
":",
"document",
".",
"createElement",
"(",
"tagName",
")",
"// one or multiple will be evaluated to append as string or HTMLElement",
"const",
"fragment",
"=",
"createFragmentFrom",
"(",
"children",
")",
"element",
".",
"appendChild",
"(",
"fragment",
")",
"Object",
".",
"keys",
"(",
"attrs",
"||",
"{",
"}",
")",
".",
"forEach",
"(",
"prop",
"=>",
"{",
"if",
"(",
"prop",
"===",
"'style'",
")",
"{",
"// e.g. origin: <element style={{ prop: value }} />",
"Object",
".",
"assign",
"(",
"element",
".",
"style",
",",
"attrs",
"[",
"prop",
"]",
")",
"}",
"else",
"if",
"(",
"prop",
"===",
"'ref'",
"&&",
"typeof",
"attrs",
".",
"ref",
"===",
"'function'",
")",
"{",
"attrs",
".",
"ref",
"(",
"element",
",",
"attrs",
")",
"}",
"else",
"if",
"(",
"prop",
"===",
"'className'",
")",
"{",
"element",
".",
"setAttribute",
"(",
"'class'",
",",
"attrs",
"[",
"prop",
"]",
")",
"}",
"else",
"if",
"(",
"prop",
"===",
"'xlinkHref'",
")",
"{",
"element",
".",
"setAttributeNS",
"(",
"'http://www.w3.org/1999/xlink'",
",",
"'xlink:href'",
",",
"attrs",
"[",
"prop",
"]",
")",
"}",
"else",
"if",
"(",
"prop",
"===",
"'dangerouslySetInnerHTML'",
")",
"{",
"// eslint-disable-next-line no-underscore-dangle",
"element",
".",
"innerHTML",
"=",
"attrs",
"[",
"prop",
"]",
".",
"__html",
"}",
"else",
"{",
"// any other prop will be set as attribute",
"element",
".",
"setAttribute",
"(",
"prop",
",",
"attrs",
"[",
"prop",
"]",
")",
"}",
"}",
")",
"return",
"element",
"}"
] |
The tag name and create an html together with the attributes
@param {String} tagName name as string, e.g. 'div', 'span', 'svg'
@param {Object} attrs html attributes e.g. data-, width, src
@param {Array} children html nodes from inside de elements
@return {HTMLElement} html node with attrs
|
[
"The",
"tag",
"name",
"and",
"create",
"an",
"html",
"together",
"with",
"the",
"attributes"
] |
e7b261c7e4b4e516eaca40cc2c3d219a123af989
|
https://github.com/alecsgone/jsx-render/blob/e7b261c7e4b4e516eaca40cc2c3d219a123af989/src/dom.js#L11-L40
|
17,015
|
alecsgone/jsx-render
|
src/dom.js
|
composeToFunction
|
function composeToFunction(JSXTag, elementProps, children) {
const props = Object.assign({}, JSXTag.defaultProps || {}, elementProps, { children })
const bridge = JSXTag.prototype.render ? new JSXTag(props).render : JSXTag
const result = bridge(props)
switch (result) {
case 'FRAGMENT':
return createFragmentFrom(children)
// Portals are useful to render modals
// allow render on a different element than the parent of the chain
// and leave a comment instead
case 'PORTAL':
bridge.target.appendChild(createFragmentFrom(children))
return document.createComment('Portal Used')
default:
return result
}
}
|
javascript
|
function composeToFunction(JSXTag, elementProps, children) {
const props = Object.assign({}, JSXTag.defaultProps || {}, elementProps, { children })
const bridge = JSXTag.prototype.render ? new JSXTag(props).render : JSXTag
const result = bridge(props)
switch (result) {
case 'FRAGMENT':
return createFragmentFrom(children)
// Portals are useful to render modals
// allow render on a different element than the parent of the chain
// and leave a comment instead
case 'PORTAL':
bridge.target.appendChild(createFragmentFrom(children))
return document.createComment('Portal Used')
default:
return result
}
}
|
[
"function",
"composeToFunction",
"(",
"JSXTag",
",",
"elementProps",
",",
"children",
")",
"{",
"const",
"props",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"JSXTag",
".",
"defaultProps",
"||",
"{",
"}",
",",
"elementProps",
",",
"{",
"children",
"}",
")",
"const",
"bridge",
"=",
"JSXTag",
".",
"prototype",
".",
"render",
"?",
"new",
"JSXTag",
"(",
"props",
")",
".",
"render",
":",
"JSXTag",
"const",
"result",
"=",
"bridge",
"(",
"props",
")",
"switch",
"(",
"result",
")",
"{",
"case",
"'FRAGMENT'",
":",
"return",
"createFragmentFrom",
"(",
"children",
")",
"// Portals are useful to render modals",
"// allow render on a different element than the parent of the chain",
"// and leave a comment instead",
"case",
"'PORTAL'",
":",
"bridge",
".",
"target",
".",
"appendChild",
"(",
"createFragmentFrom",
"(",
"children",
")",
")",
"return",
"document",
".",
"createComment",
"(",
"'Portal Used'",
")",
"default",
":",
"return",
"result",
"}",
"}"
] |
The JSXTag will be unwrapped returning the html
@param {Function} JSXTag name as string, e.g. 'div', 'span', 'svg'
@param {Object} elementProps custom jsx attributes e.g. fn, strings
@param {Array} children html nodes from inside de elements
@return {Function} returns de 'dom' (fn) executed, leaving the HTMLElement
JSXTag: function Comp(props) {
return dom("span", null, props.num);
}
|
[
"The",
"JSXTag",
"will",
"be",
"unwrapped",
"returning",
"the",
"html"
] |
e7b261c7e4b4e516eaca40cc2c3d219a123af989
|
https://github.com/alecsgone/jsx-render/blob/e7b261c7e4b4e516eaca40cc2c3d219a123af989/src/dom.js#L55-L73
|
17,016
|
coatyio/coaty-js
|
scripts/release.js
|
versionRelease
|
function versionRelease(version) {
return new Promise((resolve, reject) => {
const [pkgPath, pkg] = getPackageObject();
const bumpVersion = (version, isReleaseType, throwOnEqual) => {
const newVersion = isReleaseType ? semver.inc(pkg.version, version) : semver.valid(version);
if (newVersion === null) {
reject(new Error(`version must be one of: "recommended", first", major", "minor", "patch", or a semantic version`));
return;
}
if (throwOnEqual && semver.eq(pkg.version, newVersion)) {
reject(new Error(`version to be bumped is equal to package version: ${newVersion}`));
return;
}
const oldVersion = pkg.version;
pkg.version = newVersion;
try {
fs.writeFileSync(pkgPath, JSON.stringify(pkg, undefined, tabAsSpace));
// Update version in package-lock file
const [pkgLckPath, pkgLck] = getPackageObject(undefined, "package-lock.json");
pkgLck.version = newVersion;
fs.writeFileSync(pkgLckPath, JSON.stringify(pkgLck, undefined, tabAsSpace));
} catch (err) {
reject(new Error(`version couldn't be bumped: ${err.message}`));
return;
}
resolve(`bumped from ${oldVersion} to ${newVersion}`);
};
if (version === "recommended") {
conventionalRecommendedBump({
preset: "angular"
}, (err, result) => {
if (err) {
reject(new Error(`conventional recommended bump failed: ${err.message}`));
return;
}
bumpVersion(result.releaseType, true, true);
});
return;
}
if (version === "first") {
bumpVersion(pkg.version, false, false);
return;
}
const isReleaseType = version === "major" || version === "minor" || version === "patch";
bumpVersion(version, isReleaseType, true);
});
}
|
javascript
|
function versionRelease(version) {
return new Promise((resolve, reject) => {
const [pkgPath, pkg] = getPackageObject();
const bumpVersion = (version, isReleaseType, throwOnEqual) => {
const newVersion = isReleaseType ? semver.inc(pkg.version, version) : semver.valid(version);
if (newVersion === null) {
reject(new Error(`version must be one of: "recommended", first", major", "minor", "patch", or a semantic version`));
return;
}
if (throwOnEqual && semver.eq(pkg.version, newVersion)) {
reject(new Error(`version to be bumped is equal to package version: ${newVersion}`));
return;
}
const oldVersion = pkg.version;
pkg.version = newVersion;
try {
fs.writeFileSync(pkgPath, JSON.stringify(pkg, undefined, tabAsSpace));
// Update version in package-lock file
const [pkgLckPath, pkgLck] = getPackageObject(undefined, "package-lock.json");
pkgLck.version = newVersion;
fs.writeFileSync(pkgLckPath, JSON.stringify(pkgLck, undefined, tabAsSpace));
} catch (err) {
reject(new Error(`version couldn't be bumped: ${err.message}`));
return;
}
resolve(`bumped from ${oldVersion} to ${newVersion}`);
};
if (version === "recommended") {
conventionalRecommendedBump({
preset: "angular"
}, (err, result) => {
if (err) {
reject(new Error(`conventional recommended bump failed: ${err.message}`));
return;
}
bumpVersion(result.releaseType, true, true);
});
return;
}
if (version === "first") {
bumpVersion(pkg.version, false, false);
return;
}
const isReleaseType = version === "major" || version === "minor" || version === "patch";
bumpVersion(version, isReleaseType, true);
});
}
|
[
"function",
"versionRelease",
"(",
"version",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"[",
"pkgPath",
",",
"pkg",
"]",
"=",
"getPackageObject",
"(",
")",
";",
"const",
"bumpVersion",
"=",
"(",
"version",
",",
"isReleaseType",
",",
"throwOnEqual",
")",
"=>",
"{",
"const",
"newVersion",
"=",
"isReleaseType",
"?",
"semver",
".",
"inc",
"(",
"pkg",
".",
"version",
",",
"version",
")",
":",
"semver",
".",
"valid",
"(",
"version",
")",
";",
"if",
"(",
"newVersion",
"===",
"null",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"`",
"`",
")",
")",
";",
"return",
";",
"}",
"if",
"(",
"throwOnEqual",
"&&",
"semver",
".",
"eq",
"(",
"pkg",
".",
"version",
",",
"newVersion",
")",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"newVersion",
"}",
"`",
")",
")",
";",
"return",
";",
"}",
"const",
"oldVersion",
"=",
"pkg",
".",
"version",
";",
"pkg",
".",
"version",
"=",
"newVersion",
";",
"try",
"{",
"fs",
".",
"writeFileSync",
"(",
"pkgPath",
",",
"JSON",
".",
"stringify",
"(",
"pkg",
",",
"undefined",
",",
"tabAsSpace",
")",
")",
";",
"// Update version in package-lock file",
"const",
"[",
"pkgLckPath",
",",
"pkgLck",
"]",
"=",
"getPackageObject",
"(",
"undefined",
",",
"\"package-lock.json\"",
")",
";",
"pkgLck",
".",
"version",
"=",
"newVersion",
";",
"fs",
".",
"writeFileSync",
"(",
"pkgLckPath",
",",
"JSON",
".",
"stringify",
"(",
"pkgLck",
",",
"undefined",
",",
"tabAsSpace",
")",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"err",
".",
"message",
"}",
"`",
")",
")",
";",
"return",
";",
"}",
"resolve",
"(",
"`",
"${",
"oldVersion",
"}",
"${",
"newVersion",
"}",
"`",
")",
";",
"}",
";",
"if",
"(",
"version",
"===",
"\"recommended\"",
")",
"{",
"conventionalRecommendedBump",
"(",
"{",
"preset",
":",
"\"angular\"",
"}",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"err",
".",
"message",
"}",
"`",
")",
")",
";",
"return",
";",
"}",
"bumpVersion",
"(",
"result",
".",
"releaseType",
",",
"true",
",",
"true",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"if",
"(",
"version",
"===",
"\"first\"",
")",
"{",
"bumpVersion",
"(",
"pkg",
".",
"version",
",",
"false",
",",
"false",
")",
";",
"return",
";",
"}",
"const",
"isReleaseType",
"=",
"version",
"===",
"\"major\"",
"||",
"version",
"===",
"\"minor\"",
"||",
"version",
"===",
"\"patch\"",
";",
"bumpVersion",
"(",
"version",
",",
"isReleaseType",
",",
"true",
")",
";",
"}",
")",
";",
"}"
] |
Automatically bumps the package version according to the
specified version parameter.
The given version parameter can have the following values:
"recommended", "first", major", "minor", "patch", or a valid
semantic version string.
If the version is `recommended`, a recommended version bump is computed based
on conventional commits. An error is reported, if the recommended version
cannot be computed because there are no commits for this release at all.
If the version is "first", the package version is bumped to
the current version specified in package.json.
If the version is "major", "minor" or "patch", the
package version is incremented to the next major, minor, or
patch version, respectively.
If the version is a valid semantic version string, the
package version is bumped to this version.
In any of the above cases except "first", an error is reported
if the new version to be bumped is equal to the current package version.
Returns a promise that resolves to the bumped version, or a promise
that is rejected in case an error occured.
|
[
"Automatically",
"bumps",
"the",
"package",
"version",
"according",
"to",
"the",
"specified",
"version",
"parameter",
"."
] |
0c4f6d725d7e02b36857dfabc083bc65fd92c585
|
https://github.com/coatyio/coaty-js/blob/0c4f6d725d7e02b36857dfabc083bc65fd92c585/scripts/release.js#L43-L98
|
17,017
|
coatyio/coaty-js
|
scripts/release.js
|
cutRelease
|
function cutRelease(releaseNote) {
const [pkgPath, pkg] = getPackageObject();
const msg = getCommitTagMessage(pkg.version);
return updateChangelogInternal(pkg.version, releaseNote)
// Stage and commit all new, modified, and deleted files in the entire working directory
.then(() => runCommand("git add --all"))
.then(() => runCommand(`git commit --no-verify -m "${msg}"`))
// Make an unsigned annotated tag, replacing an existing tag with the same version
.then(output => {
return runCommand(`git tag -a -f -m "${msg}" v${pkg.version}`)
.then(() => `updated CHANGELOG, committed and tagged ${output}\n\n` +
"You can now push the tagged release: npm run push-release");
});
}
|
javascript
|
function cutRelease(releaseNote) {
const [pkgPath, pkg] = getPackageObject();
const msg = getCommitTagMessage(pkg.version);
return updateChangelogInternal(pkg.version, releaseNote)
// Stage and commit all new, modified, and deleted files in the entire working directory
.then(() => runCommand("git add --all"))
.then(() => runCommand(`git commit --no-verify -m "${msg}"`))
// Make an unsigned annotated tag, replacing an existing tag with the same version
.then(output => {
return runCommand(`git tag -a -f -m "${msg}" v${pkg.version}`)
.then(() => `updated CHANGELOG, committed and tagged ${output}\n\n` +
"You can now push the tagged release: npm run push-release");
});
}
|
[
"function",
"cutRelease",
"(",
"releaseNote",
")",
"{",
"const",
"[",
"pkgPath",
",",
"pkg",
"]",
"=",
"getPackageObject",
"(",
")",
";",
"const",
"msg",
"=",
"getCommitTagMessage",
"(",
"pkg",
".",
"version",
")",
";",
"return",
"updateChangelogInternal",
"(",
"pkg",
".",
"version",
",",
"releaseNote",
")",
"// Stage and commit all new, modified, and deleted files in the entire working directory",
".",
"then",
"(",
"(",
")",
"=>",
"runCommand",
"(",
"\"git add --all\"",
")",
")",
".",
"then",
"(",
"(",
")",
"=>",
"runCommand",
"(",
"`",
"${",
"msg",
"}",
"`",
")",
")",
"// Make an unsigned annotated tag, replacing an existing tag with the same version",
".",
"then",
"(",
"output",
"=>",
"{",
"return",
"runCommand",
"(",
"`",
"${",
"msg",
"}",
"${",
"pkg",
".",
"version",
"}",
"`",
")",
".",
"then",
"(",
"(",
")",
"=>",
"`",
"${",
"output",
"}",
"\\n",
"\\n",
"`",
"+",
"\"You can now push the tagged release: npm run push-release\"",
")",
";",
"}",
")",
";",
"}"
] |
Updates the CHANGELOG with release information from the conventional commits,
commits all pending changes and creates an annotated git tag for the release.
If supplied with releaseNote, this text is prepended to the release information generated
by conventional commits.
|
[
"Updates",
"the",
"CHANGELOG",
"with",
"release",
"information",
"from",
"the",
"conventional",
"commits",
"commits",
"all",
"pending",
"changes",
"and",
"creates",
"an",
"annotated",
"git",
"tag",
"for",
"the",
"release",
"."
] |
0c4f6d725d7e02b36857dfabc083bc65fd92c585
|
https://github.com/coatyio/coaty-js/blob/0c4f6d725d7e02b36857dfabc083bc65fd92c585/scripts/release.js#L109-L122
|
17,018
|
coatyio/coaty-js
|
scripts/release.js
|
publishRelease
|
function publishRelease(npmDistTag) {
const tag = npmDistTag || "latest";
const distPath = path.resolve(process.cwd(), "dist");
const distFolders = [];
const asyncInSeries = (items, asyncFunc) => {
return new Promise((resolve, reject) => {
const series = index => {
if (index === items.length) {
resolve();
return;
}
asyncFunc(items[index])
.then(() => series(index + 1))
.catch(error => reject(error));
};
series(0);
});
};
for (const file of fs.readdirSync(distPath)) {
let projectPath = path.join(distPath, file);
if (fs.lstatSync(projectPath).isFile() && file === "package.json") {
// Assume the dist folder itself is the only project to be published
distFolders.splice(0);
distFolders.push(distPath);
break;
}
if (fs.lstatSync(projectPath).isDirectory()) {
distFolders.push(projectPath);
}
}
return Promise.resolve()
// Authentication is based on an OAuth provider.
// Get the relevant authentication and paste it into your ~/.npmrc or invoke "npm adduser".
// For details see here
// https://www.jfrog.com/confluence/display/RTF/Npm+Registry#NpmRegistry-NpmPublish(DeployingPackages)
// .then(() => runCommandWithRedirectedIo(`npm login --always-auth --registry=${reg}`))
.then(() => asyncInSeries(distFolders, folder => runCommandWithRedirectedIo(`npm publish "${folder}" --tag=${tag}`)))
.then(() => `published ${distFolders.length} distribution packages on '${tag}' tag to npm registry`);
}
|
javascript
|
function publishRelease(npmDistTag) {
const tag = npmDistTag || "latest";
const distPath = path.resolve(process.cwd(), "dist");
const distFolders = [];
const asyncInSeries = (items, asyncFunc) => {
return new Promise((resolve, reject) => {
const series = index => {
if (index === items.length) {
resolve();
return;
}
asyncFunc(items[index])
.then(() => series(index + 1))
.catch(error => reject(error));
};
series(0);
});
};
for (const file of fs.readdirSync(distPath)) {
let projectPath = path.join(distPath, file);
if (fs.lstatSync(projectPath).isFile() && file === "package.json") {
// Assume the dist folder itself is the only project to be published
distFolders.splice(0);
distFolders.push(distPath);
break;
}
if (fs.lstatSync(projectPath).isDirectory()) {
distFolders.push(projectPath);
}
}
return Promise.resolve()
// Authentication is based on an OAuth provider.
// Get the relevant authentication and paste it into your ~/.npmrc or invoke "npm adduser".
// For details see here
// https://www.jfrog.com/confluence/display/RTF/Npm+Registry#NpmRegistry-NpmPublish(DeployingPackages)
// .then(() => runCommandWithRedirectedIo(`npm login --always-auth --registry=${reg}`))
.then(() => asyncInSeries(distFolders, folder => runCommandWithRedirectedIo(`npm publish "${folder}" --tag=${tag}`)))
.then(() => `published ${distFolders.length} distribution packages on '${tag}' tag to npm registry`);
}
|
[
"function",
"publishRelease",
"(",
"npmDistTag",
")",
"{",
"const",
"tag",
"=",
"npmDistTag",
"||",
"\"latest\"",
";",
"const",
"distPath",
"=",
"path",
".",
"resolve",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"\"dist\"",
")",
";",
"const",
"distFolders",
"=",
"[",
"]",
";",
"const",
"asyncInSeries",
"=",
"(",
"items",
",",
"asyncFunc",
")",
"=>",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"series",
"=",
"index",
"=>",
"{",
"if",
"(",
"index",
"===",
"items",
".",
"length",
")",
"{",
"resolve",
"(",
")",
";",
"return",
";",
"}",
"asyncFunc",
"(",
"items",
"[",
"index",
"]",
")",
".",
"then",
"(",
"(",
")",
"=>",
"series",
"(",
"index",
"+",
"1",
")",
")",
".",
"catch",
"(",
"error",
"=>",
"reject",
"(",
"error",
")",
")",
";",
"}",
";",
"series",
"(",
"0",
")",
";",
"}",
")",
";",
"}",
";",
"for",
"(",
"const",
"file",
"of",
"fs",
".",
"readdirSync",
"(",
"distPath",
")",
")",
"{",
"let",
"projectPath",
"=",
"path",
".",
"join",
"(",
"distPath",
",",
"file",
")",
";",
"if",
"(",
"fs",
".",
"lstatSync",
"(",
"projectPath",
")",
".",
"isFile",
"(",
")",
"&&",
"file",
"===",
"\"package.json\"",
")",
"{",
"// Assume the dist folder itself is the only project to be published",
"distFolders",
".",
"splice",
"(",
"0",
")",
";",
"distFolders",
".",
"push",
"(",
"distPath",
")",
";",
"break",
";",
"}",
"if",
"(",
"fs",
".",
"lstatSync",
"(",
"projectPath",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"distFolders",
".",
"push",
"(",
"projectPath",
")",
";",
"}",
"}",
"return",
"Promise",
".",
"resolve",
"(",
")",
"// Authentication is based on an OAuth provider.",
"// Get the relevant authentication and paste it into your ~/.npmrc or invoke \"npm adduser\".",
"// For details see here",
"// https://www.jfrog.com/confluence/display/RTF/Npm+Registry#NpmRegistry-NpmPublish(DeployingPackages)",
"// .then(() => runCommandWithRedirectedIo(`npm login --always-auth --registry=${reg}`))",
".",
"then",
"(",
"(",
")",
"=>",
"asyncInSeries",
"(",
"distFolders",
",",
"folder",
"=>",
"runCommandWithRedirectedIo",
"(",
"`",
"${",
"folder",
"}",
"${",
"tag",
"}",
"`",
")",
")",
")",
".",
"then",
"(",
"(",
")",
"=>",
"`",
"${",
"distFolders",
".",
"length",
"}",
"${",
"tag",
"}",
"`",
")",
";",
"}"
] |
Publishes all the distribution packages of the new release on an
npm registry. Authentication is required to publish packages. The
registry location is determined by the `publishConfig` section in the
package.json, if present. If not present, the public npm registry is used.
Registers the published packages with the given tag, such that npm install
<name>@<tag> will install this version. By default, `npm install` installs the
`latest` tag.
|
[
"Publishes",
"all",
"the",
"distribution",
"packages",
"of",
"the",
"new",
"release",
"on",
"an",
"npm",
"registry",
".",
"Authentication",
"is",
"required",
"to",
"publish",
"packages",
".",
"The",
"registry",
"location",
"is",
"determined",
"by",
"the",
"publishConfig",
"section",
"in",
"the",
"package",
".",
"json",
"if",
"present",
".",
"If",
"not",
"present",
"the",
"public",
"npm",
"registry",
"is",
"used",
"."
] |
0c4f6d725d7e02b36857dfabc083bc65fd92c585
|
https://github.com/coatyio/coaty-js/blob/0c4f6d725d7e02b36857dfabc083bc65fd92c585/scripts/release.js#L147-L189
|
17,019
|
coatyio/coaty-js
|
scripts/release.js
|
runCommand
|
function runCommand(command) {
return new Promise((resolve, reject) => {
utils.logInfo(`Command: ${command}`);
childProcess.exec(command, (error, stdout, stderr) => {
// If exec returns content in stderr, but no error, print it as a warning.
// If exec returns an error, reject the promise.
if (error) {
reject(error);
return;
} else if (stderr) {
utils.logInfo(stderr);
}
resolve(stdout);
});
});
}
|
javascript
|
function runCommand(command) {
return new Promise((resolve, reject) => {
utils.logInfo(`Command: ${command}`);
childProcess.exec(command, (error, stdout, stderr) => {
// If exec returns content in stderr, but no error, print it as a warning.
// If exec returns an error, reject the promise.
if (error) {
reject(error);
return;
} else if (stderr) {
utils.logInfo(stderr);
}
resolve(stdout);
});
});
}
|
[
"function",
"runCommand",
"(",
"command",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"utils",
".",
"logInfo",
"(",
"`",
"${",
"command",
"}",
"`",
")",
";",
"childProcess",
".",
"exec",
"(",
"command",
",",
"(",
"error",
",",
"stdout",
",",
"stderr",
")",
"=>",
"{",
"// If exec returns content in stderr, but no error, print it as a warning.",
"// If exec returns an error, reject the promise.",
"if",
"(",
"error",
")",
"{",
"reject",
"(",
"error",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"stderr",
")",
"{",
"utils",
".",
"logInfo",
"(",
"stderr",
")",
";",
"}",
"resolve",
"(",
"stdout",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Runs the given command in a child process.
Returns a promise that is resolved with the generated
stdout of the command (as UTF-8 string) when the child process
terminates normally or rejected if the child process
terminates with a non-zero exit code.
|
[
"Runs",
"the",
"given",
"command",
"in",
"a",
"child",
"process",
"."
] |
0c4f6d725d7e02b36857dfabc083bc65fd92c585
|
https://github.com/coatyio/coaty-js/blob/0c4f6d725d7e02b36857dfabc083bc65fd92c585/scripts/release.js#L240-L255
|
17,020
|
coatyio/coaty-js
|
build/builder.js
|
clean
|
function clean() {
const distDir = "./dist";
try {
fse.readdirSync(distDir).forEach(file => {
let filePath = path.resolve(distDir, file);
if (fse.lstatSync(filePath).isDirectory()) {
logInfo("Clean distribution package " + file);
try {
rimraf.sync(filePath);
} catch (e) {
logError("Could not clean distribution package: " + e);
}
}
});
} catch (e) { }
}
|
javascript
|
function clean() {
const distDir = "./dist";
try {
fse.readdirSync(distDir).forEach(file => {
let filePath = path.resolve(distDir, file);
if (fse.lstatSync(filePath).isDirectory()) {
logInfo("Clean distribution package " + file);
try {
rimraf.sync(filePath);
} catch (e) {
logError("Could not clean distribution package: " + e);
}
}
});
} catch (e) { }
}
|
[
"function",
"clean",
"(",
")",
"{",
"const",
"distDir",
"=",
"\"./dist\"",
";",
"try",
"{",
"fse",
".",
"readdirSync",
"(",
"distDir",
")",
".",
"forEach",
"(",
"file",
"=>",
"{",
"let",
"filePath",
"=",
"path",
".",
"resolve",
"(",
"distDir",
",",
"file",
")",
";",
"if",
"(",
"fse",
".",
"lstatSync",
"(",
"filePath",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"logInfo",
"(",
"\"Clean distribution package \"",
"+",
"file",
")",
";",
"try",
"{",
"rimraf",
".",
"sync",
"(",
"filePath",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"logError",
"(",
"\"Could not clean distribution package: \"",
"+",
"e",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"}"
] |
Clean all distribution packages.
|
[
"Clean",
"all",
"distribution",
"packages",
"."
] |
0c4f6d725d7e02b36857dfabc083bc65fd92c585
|
https://github.com/coatyio/coaty-js/blob/0c4f6d725d7e02b36857dfabc083bc65fd92c585/build/builder.js#L84-L100
|
17,021
|
coatyio/coaty-js
|
build/builder.js
|
build
|
function build(pkgName, pkgVersion) {
clean();
// Update framework name/version/build date in Runtime class
updateRuntimeInfo(Date.now(), pkgName, pkgVersion);
const buildDir = "./build";
fse.readdirSync(buildDir).forEach(file => {
if (file.match(/tsconfig\..+\.json/gi)) {
const tsconfigPath = path.resolve(buildDir, file);
const opts = require(tsconfigPath).compilerOptions;
const target = opts.target + "-" + opts.module;
const targetDir = "./dist/" + target + "/";
logInfo("Build distribution package " + target);
// First, bring the desired tsconfig file into place
fse.copySync(tsconfigPath, "./" + TS_TARGETDIR + "/tsconfig.json");
// Transpile TS into JS code, using TS compiler in local typescript npm package.
// Remove all comments except copy-right header comments, and do not
// generate corresponding .d.ts files (see next step below).
childProcess.execSync(path.resolve("./node_modules/.bin/tsc") +
" --project " + TS_TARGETDIR +
" --outDir " + targetDir +
" --removeComments true --declaration false",
// redirect child output to parent's stdin, stdout and stderr
{ stdio: "inherit" });
// Only emit .d.ts files, using TS compiler in local typescript npm package.
// The generated declaration files include all comments so that
// IDEs can provide this information to developers.
childProcess.execSync(path.resolve("./node_modules/.bin/tsc") +
" --project " + TS_TARGETDIR +
" --outDir " + targetDir +
" --removeComments false --declaration true --emitDeclarationOnly true",
// redirect child output to parent's stdin, stdout and stderr
{ stdio: "inherit" });
// Copy scripts folder into distribution package
fse.copySync("./scripts", targetDir + "scripts");
// Copy readme into distribution package
fse.copySync("./README.md", targetDir + "README.md");
// Copy license into distribution package
fse.copySync("./LICENSE", targetDir + "LICENSE");
// Copy tslint.json into distribution package (for use by Coaty projects)
fse.copySync("./build/tslint.json", targetDir + "tslint-config.json");
// Copy .npmignore into distribution package
fse.copySync("./.npmignore", targetDir + ".npmignore");
// Copy package.json into distribution package
fse.copySync("./package.json", targetDir + "package.json");
// Update package.json to include distribution as prerelease in version
updatePackageInfo(target, targetDir + "package.json", file !== "tsconfig.es5-commonjs.json");
}
});
}
|
javascript
|
function build(pkgName, pkgVersion) {
clean();
// Update framework name/version/build date in Runtime class
updateRuntimeInfo(Date.now(), pkgName, pkgVersion);
const buildDir = "./build";
fse.readdirSync(buildDir).forEach(file => {
if (file.match(/tsconfig\..+\.json/gi)) {
const tsconfigPath = path.resolve(buildDir, file);
const opts = require(tsconfigPath).compilerOptions;
const target = opts.target + "-" + opts.module;
const targetDir = "./dist/" + target + "/";
logInfo("Build distribution package " + target);
// First, bring the desired tsconfig file into place
fse.copySync(tsconfigPath, "./" + TS_TARGETDIR + "/tsconfig.json");
// Transpile TS into JS code, using TS compiler in local typescript npm package.
// Remove all comments except copy-right header comments, and do not
// generate corresponding .d.ts files (see next step below).
childProcess.execSync(path.resolve("./node_modules/.bin/tsc") +
" --project " + TS_TARGETDIR +
" --outDir " + targetDir +
" --removeComments true --declaration false",
// redirect child output to parent's stdin, stdout and stderr
{ stdio: "inherit" });
// Only emit .d.ts files, using TS compiler in local typescript npm package.
// The generated declaration files include all comments so that
// IDEs can provide this information to developers.
childProcess.execSync(path.resolve("./node_modules/.bin/tsc") +
" --project " + TS_TARGETDIR +
" --outDir " + targetDir +
" --removeComments false --declaration true --emitDeclarationOnly true",
// redirect child output to parent's stdin, stdout and stderr
{ stdio: "inherit" });
// Copy scripts folder into distribution package
fse.copySync("./scripts", targetDir + "scripts");
// Copy readme into distribution package
fse.copySync("./README.md", targetDir + "README.md");
// Copy license into distribution package
fse.copySync("./LICENSE", targetDir + "LICENSE");
// Copy tslint.json into distribution package (for use by Coaty projects)
fse.copySync("./build/tslint.json", targetDir + "tslint-config.json");
// Copy .npmignore into distribution package
fse.copySync("./.npmignore", targetDir + ".npmignore");
// Copy package.json into distribution package
fse.copySync("./package.json", targetDir + "package.json");
// Update package.json to include distribution as prerelease in version
updatePackageInfo(target, targetDir + "package.json", file !== "tsconfig.es5-commonjs.json");
}
});
}
|
[
"function",
"build",
"(",
"pkgName",
",",
"pkgVersion",
")",
"{",
"clean",
"(",
")",
";",
"// Update framework name/version/build date in Runtime class",
"updateRuntimeInfo",
"(",
"Date",
".",
"now",
"(",
")",
",",
"pkgName",
",",
"pkgVersion",
")",
";",
"const",
"buildDir",
"=",
"\"./build\"",
";",
"fse",
".",
"readdirSync",
"(",
"buildDir",
")",
".",
"forEach",
"(",
"file",
"=>",
"{",
"if",
"(",
"file",
".",
"match",
"(",
"/",
"tsconfig\\..+\\.json",
"/",
"gi",
")",
")",
"{",
"const",
"tsconfigPath",
"=",
"path",
".",
"resolve",
"(",
"buildDir",
",",
"file",
")",
";",
"const",
"opts",
"=",
"require",
"(",
"tsconfigPath",
")",
".",
"compilerOptions",
";",
"const",
"target",
"=",
"opts",
".",
"target",
"+",
"\"-\"",
"+",
"opts",
".",
"module",
";",
"const",
"targetDir",
"=",
"\"./dist/\"",
"+",
"target",
"+",
"\"/\"",
";",
"logInfo",
"(",
"\"Build distribution package \"",
"+",
"target",
")",
";",
"// First, bring the desired tsconfig file into place",
"fse",
".",
"copySync",
"(",
"tsconfigPath",
",",
"\"./\"",
"+",
"TS_TARGETDIR",
"+",
"\"/tsconfig.json\"",
")",
";",
"// Transpile TS into JS code, using TS compiler in local typescript npm package.",
"// Remove all comments except copy-right header comments, and do not",
"// generate corresponding .d.ts files (see next step below).",
"childProcess",
".",
"execSync",
"(",
"path",
".",
"resolve",
"(",
"\"./node_modules/.bin/tsc\"",
")",
"+",
"\" --project \"",
"+",
"TS_TARGETDIR",
"+",
"\" --outDir \"",
"+",
"targetDir",
"+",
"\" --removeComments true --declaration false\"",
",",
"// redirect child output to parent's stdin, stdout and stderr",
"{",
"stdio",
":",
"\"inherit\"",
"}",
")",
";",
"// Only emit .d.ts files, using TS compiler in local typescript npm package.",
"// The generated declaration files include all comments so that",
"// IDEs can provide this information to developers.",
"childProcess",
".",
"execSync",
"(",
"path",
".",
"resolve",
"(",
"\"./node_modules/.bin/tsc\"",
")",
"+",
"\" --project \"",
"+",
"TS_TARGETDIR",
"+",
"\" --outDir \"",
"+",
"targetDir",
"+",
"\" --removeComments false --declaration true --emitDeclarationOnly true\"",
",",
"// redirect child output to parent's stdin, stdout and stderr",
"{",
"stdio",
":",
"\"inherit\"",
"}",
")",
";",
"// Copy scripts folder into distribution package",
"fse",
".",
"copySync",
"(",
"\"./scripts\"",
",",
"targetDir",
"+",
"\"scripts\"",
")",
";",
"// Copy readme into distribution package",
"fse",
".",
"copySync",
"(",
"\"./README.md\"",
",",
"targetDir",
"+",
"\"README.md\"",
")",
";",
"// Copy license into distribution package",
"fse",
".",
"copySync",
"(",
"\"./LICENSE\"",
",",
"targetDir",
"+",
"\"LICENSE\"",
")",
";",
"// Copy tslint.json into distribution package (for use by Coaty projects)",
"fse",
".",
"copySync",
"(",
"\"./build/tslint.json\"",
",",
"targetDir",
"+",
"\"tslint-config.json\"",
")",
";",
"// Copy .npmignore into distribution package",
"fse",
".",
"copySync",
"(",
"\"./.npmignore\"",
",",
"targetDir",
"+",
"\".npmignore\"",
")",
";",
"// Copy package.json into distribution package",
"fse",
".",
"copySync",
"(",
"\"./package.json\"",
",",
"targetDir",
"+",
"\"package.json\"",
")",
";",
"// Update package.json to include distribution as prerelease in version",
"updatePackageInfo",
"(",
"target",
",",
"targetDir",
"+",
"\"package.json\"",
",",
"file",
"!==",
"\"tsconfig.es5-commonjs.json\"",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Build distribution packages with modules and test specs for all defined
ECMAScript versions and module formats.
|
[
"Build",
"distribution",
"packages",
"with",
"modules",
"and",
"test",
"specs",
"for",
"all",
"defined",
"ECMAScript",
"versions",
"and",
"module",
"formats",
"."
] |
0c4f6d725d7e02b36857dfabc083bc65fd92c585
|
https://github.com/coatyio/coaty-js/blob/0c4f6d725d7e02b36857dfabc083bc65fd92c585/build/builder.js#L106-L168
|
17,022
|
coatyio/coaty-js
|
scripts/info.js
|
info
|
function info(agentInfoFolder, defaultBuildMode) {
return new Promise((resolve, reject) => {
const result = generateAgentInfoFile(agentInfoFolder || "./src/", undefined, undefined, defaultBuildMode);
resolve(result[1]);
});
}
|
javascript
|
function info(agentInfoFolder, defaultBuildMode) {
return new Promise((resolve, reject) => {
const result = generateAgentInfoFile(agentInfoFolder || "./src/", undefined, undefined, defaultBuildMode);
resolve(result[1]);
});
}
|
[
"function",
"info",
"(",
"agentInfoFolder",
",",
"defaultBuildMode",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"result",
"=",
"generateAgentInfoFile",
"(",
"agentInfoFolder",
"||",
"\"./src/\"",
",",
"undefined",
",",
"undefined",
",",
"defaultBuildMode",
")",
";",
"resolve",
"(",
"result",
"[",
"1",
"]",
")",
";",
"}",
")",
";",
"}"
] |
Coaty script command for generating agent info file.
Returns a promise that resolves to the generated `AgentInfo` object.
|
[
"Coaty",
"script",
"command",
"for",
"generating",
"agent",
"info",
"file",
".",
"Returns",
"a",
"promise",
"that",
"resolves",
"to",
"the",
"generated",
"AgentInfo",
"object",
"."
] |
0c4f6d725d7e02b36857dfabc083bc65fd92c585
|
https://github.com/coatyio/coaty-js/blob/0c4f6d725d7e02b36857dfabc083bc65fd92c585/scripts/info.js#L9-L14
|
17,023
|
coatyio/coaty-js
|
scripts/info.js
|
gulpBuildAgentInfo
|
function gulpBuildAgentInfo(agentInfoFolder, agentInfoFilename, packageFile) {
if (agentInfoFilename === undefined) {
agentInfoFilename = "agent.info.ts";
}
if (packageFile === undefined) {
packageFile = "package.json";
}
return () => {
const gulp = require("gulp");
const result = generateAgentInfoFile(agentInfoFolder, agentInfoFilename, packageFile);
return gulp.src(result[0]);
};
}
|
javascript
|
function gulpBuildAgentInfo(agentInfoFolder, agentInfoFilename, packageFile) {
if (agentInfoFilename === undefined) {
agentInfoFilename = "agent.info.ts";
}
if (packageFile === undefined) {
packageFile = "package.json";
}
return () => {
const gulp = require("gulp");
const result = generateAgentInfoFile(agentInfoFolder, agentInfoFilename, packageFile);
return gulp.src(result[0]);
};
}
|
[
"function",
"gulpBuildAgentInfo",
"(",
"agentInfoFolder",
",",
"agentInfoFilename",
",",
"packageFile",
")",
"{",
"if",
"(",
"agentInfoFilename",
"===",
"undefined",
")",
"{",
"agentInfoFilename",
"=",
"\"agent.info.ts\"",
";",
"}",
"if",
"(",
"packageFile",
"===",
"undefined",
")",
"{",
"packageFile",
"=",
"\"package.json\"",
";",
"}",
"return",
"(",
")",
"=>",
"{",
"const",
"gulp",
"=",
"require",
"(",
"\"gulp\"",
")",
";",
"const",
"result",
"=",
"generateAgentInfoFile",
"(",
"agentInfoFolder",
",",
"agentInfoFilename",
",",
"packageFile",
")",
";",
"return",
"gulp",
".",
"src",
"(",
"result",
"[",
"0",
"]",
")",
";",
"}",
";",
"}"
] |
Returns a gulp task function for generating a TypeScript file including agent
info in the specified folder.
Agent project package information is acquired from the specified package.json
file and the build mode is determined by environment variable setting
`COATY_ENV`. Set `COATY_ENV` to "development", "production", "testing", etc.
before building your application. If the `COATY_ENV` variable is not set, its
value defaults to "development".
This function is intended to be used in a gulp task definition within a
gulpfile.
@param agentInfoFolder the folder where to write the agent info file
@param agentInfoFilename the file name of the agent info file (defaults to
"agent.info.ts")
@param packageFile the path to the package.json to extract package
information from (defaults to "package.json")
|
[
"Returns",
"a",
"gulp",
"task",
"function",
"for",
"generating",
"a",
"TypeScript",
"file",
"including",
"agent",
"info",
"in",
"the",
"specified",
"folder",
"."
] |
0c4f6d725d7e02b36857dfabc083bc65fd92c585
|
https://github.com/coatyio/coaty-js/blob/0c4f6d725d7e02b36857dfabc083bc65fd92c585/scripts/info.js#L37-L49
|
17,024
|
coatyio/coaty-js
|
scripts/info.js
|
generateAgentInfoFile
|
function generateAgentInfoFile(agentInfoFolder, agentInfoFilename, packageFile, defaultBuildMode) {
if (agentInfoFilename === undefined) {
agentInfoFilename = "agent.info.ts";
}
if (packageFile === undefined) {
packageFile = "package.json";
}
const fs = require("fs");
const path = require("path");
const agentInfoResult = generateAgentInfo(packageFile, defaultBuildMode);
const agentInfoCode = agentInfoResult[0];
const buildMode = agentInfoResult[1];
const file = path.resolve(agentInfoFolder, agentInfoFilename);
if (fs.statSync(path.resolve(agentInfoFolder)).isDirectory()) {
fs.writeFileSync(file, agentInfoCode);
return [file, buildMode];
}
throw new Error(`specified agentInfoFolder is not a directory: ${agentInfoFolder}`);
}
|
javascript
|
function generateAgentInfoFile(agentInfoFolder, agentInfoFilename, packageFile, defaultBuildMode) {
if (agentInfoFilename === undefined) {
agentInfoFilename = "agent.info.ts";
}
if (packageFile === undefined) {
packageFile = "package.json";
}
const fs = require("fs");
const path = require("path");
const agentInfoResult = generateAgentInfo(packageFile, defaultBuildMode);
const agentInfoCode = agentInfoResult[0];
const buildMode = agentInfoResult[1];
const file = path.resolve(agentInfoFolder, agentInfoFilename);
if (fs.statSync(path.resolve(agentInfoFolder)).isDirectory()) {
fs.writeFileSync(file, agentInfoCode);
return [file, buildMode];
}
throw new Error(`specified agentInfoFolder is not a directory: ${agentInfoFolder}`);
}
|
[
"function",
"generateAgentInfoFile",
"(",
"agentInfoFolder",
",",
"agentInfoFilename",
",",
"packageFile",
",",
"defaultBuildMode",
")",
"{",
"if",
"(",
"agentInfoFilename",
"===",
"undefined",
")",
"{",
"agentInfoFilename",
"=",
"\"agent.info.ts\"",
";",
"}",
"if",
"(",
"packageFile",
"===",
"undefined",
")",
"{",
"packageFile",
"=",
"\"package.json\"",
";",
"}",
"const",
"fs",
"=",
"require",
"(",
"\"fs\"",
")",
";",
"const",
"path",
"=",
"require",
"(",
"\"path\"",
")",
";",
"const",
"agentInfoResult",
"=",
"generateAgentInfo",
"(",
"packageFile",
",",
"defaultBuildMode",
")",
";",
"const",
"agentInfoCode",
"=",
"agentInfoResult",
"[",
"0",
"]",
";",
"const",
"buildMode",
"=",
"agentInfoResult",
"[",
"1",
"]",
";",
"const",
"file",
"=",
"path",
".",
"resolve",
"(",
"agentInfoFolder",
",",
"agentInfoFilename",
")",
";",
"if",
"(",
"fs",
".",
"statSync",
"(",
"path",
".",
"resolve",
"(",
"agentInfoFolder",
")",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"fs",
".",
"writeFileSync",
"(",
"file",
",",
"agentInfoCode",
")",
";",
"return",
"[",
"file",
",",
"buildMode",
"]",
";",
"}",
"throw",
"new",
"Error",
"(",
"`",
"${",
"agentInfoFolder",
"}",
"`",
")",
";",
"}"
] |
Generates a TypeScript file including agent info in the specified folder and
returns its absolute file path and the build mode as a tuple array.
Agent project package information is acquired from the specified package.json
file and the build mode is determined by environment variable setting
`COATY_ENV`. Set `COATY_ENV` to "development", "production", "staging", etc.
before building your application. If the `COATY_ENV` variable is not set, its
value defaults to "development", unless overriden by the given
`defaultBuildMode` parameter. The service host name is acquired from the
environment variable `COATY_SERVICE_HOST`.
This function is intended to be used in a Node.js program only.
@param agentInfoFolder the folder where to write the agent info file
@param agentInfoFilename the file name of the agent info file (defaults to
"agent.info.ts")
@param packageFile the path to the package.json to extract package
information from (defaults to "package.json")
@param defaultBuildMode the default build mode to use (if not overriden by
COATY_ENV)
|
[
"Generates",
"a",
"TypeScript",
"file",
"including",
"agent",
"info",
"in",
"the",
"specified",
"folder",
"and",
"returns",
"its",
"absolute",
"file",
"path",
"and",
"the",
"build",
"mode",
"as",
"a",
"tuple",
"array",
"."
] |
0c4f6d725d7e02b36857dfabc083bc65fd92c585
|
https://github.com/coatyio/coaty-js/blob/0c4f6d725d7e02b36857dfabc083bc65fd92c585/scripts/info.js#L75-L93
|
17,025
|
coatyio/coaty-js
|
scripts/info.js
|
generateAgentInfo
|
function generateAgentInfo(packageFile, defaultBuildMode) {
if (defaultBuildMode === undefined) {
defaultBuildMode = "development";
}
const path = require("path");
const pkg = require(path.resolve(packageFile));
const buildMode = process.env.COATY_ENV || defaultBuildMode;
const buildDate = utils.toLocalIsoString(new Date());
const serviceHost = process.env.COATY_SERVICE_HOST || "";
const copyrightYear = new Date().getFullYear();
return ["/*! -----------------------------------------------------------------------------\n * <auto-generated>\n * This code was generated by a tool.\n * Changes to this file may cause incorrect behavior and will be lost if\n * the code is regenerated.\n * </auto-generated>\n * ------------------------------------------------------------------------------\n * Copyright (c) " + copyrightYear + " Siemens AG. Licensed under the MIT License.\n */\n\nimport { AgentInfo } from \"coaty/runtime\";\n\nexport const agentInfo: AgentInfo = {\n packageInfo: {\n name: \"" + (pkg.name || "n.a.") + "\",\n version: \"" + (pkg.version || "n.a.") + "\",\n },\n buildInfo: {\n buildDate: \"" + buildDate + "\",\n buildMode: \"" + buildMode + "\",\n },\n configInfo: {\n serviceHost: \"" + serviceHost + "\",\n },\n};\n",
buildMode];
}
|
javascript
|
function generateAgentInfo(packageFile, defaultBuildMode) {
if (defaultBuildMode === undefined) {
defaultBuildMode = "development";
}
const path = require("path");
const pkg = require(path.resolve(packageFile));
const buildMode = process.env.COATY_ENV || defaultBuildMode;
const buildDate = utils.toLocalIsoString(new Date());
const serviceHost = process.env.COATY_SERVICE_HOST || "";
const copyrightYear = new Date().getFullYear();
return ["/*! -----------------------------------------------------------------------------\n * <auto-generated>\n * This code was generated by a tool.\n * Changes to this file may cause incorrect behavior and will be lost if\n * the code is regenerated.\n * </auto-generated>\n * ------------------------------------------------------------------------------\n * Copyright (c) " + copyrightYear + " Siemens AG. Licensed under the MIT License.\n */\n\nimport { AgentInfo } from \"coaty/runtime\";\n\nexport const agentInfo: AgentInfo = {\n packageInfo: {\n name: \"" + (pkg.name || "n.a.") + "\",\n version: \"" + (pkg.version || "n.a.") + "\",\n },\n buildInfo: {\n buildDate: \"" + buildDate + "\",\n buildMode: \"" + buildMode + "\",\n },\n configInfo: {\n serviceHost: \"" + serviceHost + "\",\n },\n};\n",
buildMode];
}
|
[
"function",
"generateAgentInfo",
"(",
"packageFile",
",",
"defaultBuildMode",
")",
"{",
"if",
"(",
"defaultBuildMode",
"===",
"undefined",
")",
"{",
"defaultBuildMode",
"=",
"\"development\"",
";",
"}",
"const",
"path",
"=",
"require",
"(",
"\"path\"",
")",
";",
"const",
"pkg",
"=",
"require",
"(",
"path",
".",
"resolve",
"(",
"packageFile",
")",
")",
";",
"const",
"buildMode",
"=",
"process",
".",
"env",
".",
"COATY_ENV",
"||",
"defaultBuildMode",
";",
"const",
"buildDate",
"=",
"utils",
".",
"toLocalIsoString",
"(",
"new",
"Date",
"(",
")",
")",
";",
"const",
"serviceHost",
"=",
"process",
".",
"env",
".",
"COATY_SERVICE_HOST",
"||",
"\"\"",
";",
"const",
"copyrightYear",
"=",
"new",
"Date",
"(",
")",
".",
"getFullYear",
"(",
")",
";",
"return",
"[",
"\"/*! -----------------------------------------------------------------------------\\n * <auto-generated>\\n * This code was generated by a tool.\\n * Changes to this file may cause incorrect behavior and will be lost if\\n * the code is regenerated.\\n * </auto-generated>\\n * ------------------------------------------------------------------------------\\n * Copyright (c) \"",
"+",
"copyrightYear",
"+",
"\" Siemens AG. Licensed under the MIT License.\\n */\\n\\nimport { AgentInfo } from \\\"coaty/runtime\\\";\\n\\nexport const agentInfo: AgentInfo = {\\n packageInfo: {\\n name: \\\"\"",
"+",
"(",
"pkg",
".",
"name",
"||",
"\"n.a.\"",
")",
"+",
"\"\\\",\\n version: \\\"\"",
"+",
"(",
"pkg",
".",
"version",
"||",
"\"n.a.\"",
")",
"+",
"\"\\\",\\n },\\n buildInfo: {\\n buildDate: \\\"\"",
"+",
"buildDate",
"+",
"\"\\\",\\n buildMode: \\\"\"",
"+",
"buildMode",
"+",
"\"\\\",\\n },\\n configInfo: {\\n serviceHost: \\\"\"",
"+",
"serviceHost",
"+",
"\"\\\",\\n },\\n};\\n\"",
",",
"buildMode",
"]",
";",
"}"
] |
Generates code for a TypeScript file which exports agent information as a
`AgentInfo` object on a variable named `agentInfo`. The information is
acquired from the specified package.json file and build mode from environment
variable setting `COATY_ENV`, unless overriden by the given
`defaultBuildMode` parameter. The service host name is acquired from the
environment variable `COATY_SERVICE_HOST`.
@param packageFile the path to the package.json to extract package
information from
@param defaultBuildMode the default build mode (defaults to "development")
|
[
"Generates",
"code",
"for",
"a",
"TypeScript",
"file",
"which",
"exports",
"agent",
"information",
"as",
"a",
"AgentInfo",
"object",
"on",
"a",
"variable",
"named",
"agentInfo",
".",
"The",
"information",
"is",
"acquired",
"from",
"the",
"specified",
"package",
".",
"json",
"file",
"and",
"build",
"mode",
"from",
"environment",
"variable",
"setting",
"COATY_ENV",
"unless",
"overriden",
"by",
"the",
"given",
"defaultBuildMode",
"parameter",
".",
"The",
"service",
"host",
"name",
"is",
"acquired",
"from",
"the",
"environment",
"variable",
"COATY_SERVICE_HOST",
"."
] |
0c4f6d725d7e02b36857dfabc083bc65fd92c585
|
https://github.com/coatyio/coaty-js/blob/0c4f6d725d7e02b36857dfabc083bc65fd92c585/scripts/info.js#L109-L121
|
17,026
|
coatyio/coaty-js
|
scripts/utils.js
|
toLocalIsoString
|
function toLocalIsoString(date, includeMillis) {
if (includeMillis === undefined) {
includeMillis = false;
}
const pad = (n, length, padChar) => {
if (length === undefined) { length = 2; }
if (padChar === undefined) { padChar = "0"; }
let str = "" + n;
while (str.length < length) {
str = padChar + str;
}
return str;
};
const getOffsetFromUTC = () => {
const offset = date.getTimezoneOffset();
if (offset === 0) {
return "Z";
}
return (offset < 0 ? "+" : "-")
+ pad(Math.abs(offset / 60), 2) + ":"
+ pad(Math.abs(offset % 60), 2);
};
return date.getFullYear() + "-"
+ pad(date.getMonth() + 1) + "-"
+ pad(date.getDate()) + "T"
+ pad(date.getHours()) + ":"
+ pad(date.getMinutes()) + ":"
+ pad(date.getSeconds())
+ (includeMillis ? "." + pad(date.getMilliseconds(), 3) : "")
+ getOffsetFromUTC();
}
|
javascript
|
function toLocalIsoString(date, includeMillis) {
if (includeMillis === undefined) {
includeMillis = false;
}
const pad = (n, length, padChar) => {
if (length === undefined) { length = 2; }
if (padChar === undefined) { padChar = "0"; }
let str = "" + n;
while (str.length < length) {
str = padChar + str;
}
return str;
};
const getOffsetFromUTC = () => {
const offset = date.getTimezoneOffset();
if (offset === 0) {
return "Z";
}
return (offset < 0 ? "+" : "-")
+ pad(Math.abs(offset / 60), 2) + ":"
+ pad(Math.abs(offset % 60), 2);
};
return date.getFullYear() + "-"
+ pad(date.getMonth() + 1) + "-"
+ pad(date.getDate()) + "T"
+ pad(date.getHours()) + ":"
+ pad(date.getMinutes()) + ":"
+ pad(date.getSeconds())
+ (includeMillis ? "." + pad(date.getMilliseconds(), 3) : "")
+ getOffsetFromUTC();
}
|
[
"function",
"toLocalIsoString",
"(",
"date",
",",
"includeMillis",
")",
"{",
"if",
"(",
"includeMillis",
"===",
"undefined",
")",
"{",
"includeMillis",
"=",
"false",
";",
"}",
"const",
"pad",
"=",
"(",
"n",
",",
"length",
",",
"padChar",
")",
"=>",
"{",
"if",
"(",
"length",
"===",
"undefined",
")",
"{",
"length",
"=",
"2",
";",
"}",
"if",
"(",
"padChar",
"===",
"undefined",
")",
"{",
"padChar",
"=",
"\"0\"",
";",
"}",
"let",
"str",
"=",
"\"\"",
"+",
"n",
";",
"while",
"(",
"str",
".",
"length",
"<",
"length",
")",
"{",
"str",
"=",
"padChar",
"+",
"str",
";",
"}",
"return",
"str",
";",
"}",
";",
"const",
"getOffsetFromUTC",
"=",
"(",
")",
"=>",
"{",
"const",
"offset",
"=",
"date",
".",
"getTimezoneOffset",
"(",
")",
";",
"if",
"(",
"offset",
"===",
"0",
")",
"{",
"return",
"\"Z\"",
";",
"}",
"return",
"(",
"offset",
"<",
"0",
"?",
"\"+\"",
":",
"\"-\"",
")",
"+",
"pad",
"(",
"Math",
".",
"abs",
"(",
"offset",
"/",
"60",
")",
",",
"2",
")",
"+",
"\":\"",
"+",
"pad",
"(",
"Math",
".",
"abs",
"(",
"offset",
"%",
"60",
")",
",",
"2",
")",
";",
"}",
";",
"return",
"date",
".",
"getFullYear",
"(",
")",
"+",
"\"-\"",
"+",
"pad",
"(",
"date",
".",
"getMonth",
"(",
")",
"+",
"1",
")",
"+",
"\"-\"",
"+",
"pad",
"(",
"date",
".",
"getDate",
"(",
")",
")",
"+",
"\"T\"",
"+",
"pad",
"(",
"date",
".",
"getHours",
"(",
")",
")",
"+",
"\":\"",
"+",
"pad",
"(",
"date",
".",
"getMinutes",
"(",
")",
")",
"+",
"\":\"",
"+",
"pad",
"(",
"date",
".",
"getSeconds",
"(",
")",
")",
"+",
"(",
"includeMillis",
"?",
"\".\"",
"+",
"pad",
"(",
"date",
".",
"getMilliseconds",
"(",
")",
",",
"3",
")",
":",
"\"\"",
")",
"+",
"getOffsetFromUTC",
"(",
")",
";",
"}"
] |
Returns a string in ISO 8601 format including timezone offset information.
@param date a Date object
@param includeMillis whether to include milliseconds in the string (defaults to false)
|
[
"Returns",
"a",
"string",
"in",
"ISO",
"8601",
"format",
"including",
"timezone",
"offset",
"information",
"."
] |
0c4f6d725d7e02b36857dfabc083bc65fd92c585
|
https://github.com/coatyio/coaty-js/blob/0c4f6d725d7e02b36857dfabc083bc65fd92c585/scripts/utils.js#L30-L60
|
17,027
|
mapbox/execcommand-copy
|
index.js
|
copy
|
function copy(text) {
var fakeElem = document.body.appendChild(document.createElement('textarea'));
fakeElem.style.position = 'absolute';
fakeElem.style.left = '-9999px';
fakeElem.setAttribute('readonly', '');
fakeElem.value = text;
fakeElem.select();
try {
return document.execCommand('copy');
} catch (err) {
return false;
} finally {
fakeElem.parentNode.removeChild(fakeElem);
}
}
|
javascript
|
function copy(text) {
var fakeElem = document.body.appendChild(document.createElement('textarea'));
fakeElem.style.position = 'absolute';
fakeElem.style.left = '-9999px';
fakeElem.setAttribute('readonly', '');
fakeElem.value = text;
fakeElem.select();
try {
return document.execCommand('copy');
} catch (err) {
return false;
} finally {
fakeElem.parentNode.removeChild(fakeElem);
}
}
|
[
"function",
"copy",
"(",
"text",
")",
"{",
"var",
"fakeElem",
"=",
"document",
".",
"body",
".",
"appendChild",
"(",
"document",
".",
"createElement",
"(",
"'textarea'",
")",
")",
";",
"fakeElem",
".",
"style",
".",
"position",
"=",
"'absolute'",
";",
"fakeElem",
".",
"style",
".",
"left",
"=",
"'-9999px'",
";",
"fakeElem",
".",
"setAttribute",
"(",
"'readonly'",
",",
"''",
")",
";",
"fakeElem",
".",
"value",
"=",
"text",
";",
"fakeElem",
".",
"select",
"(",
")",
";",
"try",
"{",
"return",
"document",
".",
"execCommand",
"(",
"'copy'",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"false",
";",
"}",
"finally",
"{",
"fakeElem",
".",
"parentNode",
".",
"removeChild",
"(",
"fakeElem",
")",
";",
"}",
"}"
] |
Copy a snippet of text to a user's pasteboard if the user has
proper browser support.
@param {string} text text snippet
@returns {boolean} whether the text was copied
@example
// using browser events with a click
var eCopy = require('execcommand-copy');
var a = document.getElementById('mybutton');
a.addEventListener('click', function() {
eCopy.copy(this.innerHTML);
});
|
[
"Copy",
"a",
"snippet",
"of",
"text",
"to",
"a",
"user",
"s",
"pasteboard",
"if",
"the",
"user",
"has",
"proper",
"browser",
"support",
"."
] |
5b306826fe6b831a2354dd19383273eb8b132a04
|
https://github.com/mapbox/execcommand-copy/blob/5b306826fe6b831a2354dd19383273eb8b132a04/index.js#L24-L38
|
17,028
|
pubkey/broadcast-channel
|
dist/es/methods/node.js
|
cleanPipeName
|
function cleanPipeName(str) {
if (process.platform === 'win32' && !str.startsWith('\\\\.\\pipe\\')) {
str = str.replace(/^\//, '');
str = str.replace(/\//g, '-');
return '\\\\.\\pipe\\' + str;
} else {
return str;
}
}
|
javascript
|
function cleanPipeName(str) {
if (process.platform === 'win32' && !str.startsWith('\\\\.\\pipe\\')) {
str = str.replace(/^\//, '');
str = str.replace(/\//g, '-');
return '\\\\.\\pipe\\' + str;
} else {
return str;
}
}
|
[
"function",
"cleanPipeName",
"(",
"str",
")",
"{",
"if",
"(",
"process",
".",
"platform",
"===",
"'win32'",
"&&",
"!",
"str",
".",
"startsWith",
"(",
"'\\\\\\\\.\\\\pipe\\\\'",
")",
")",
"{",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"^\\/",
"/",
",",
"''",
")",
";",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"\\/",
"/",
"g",
",",
"'-'",
")",
";",
"return",
"'\\\\\\\\.\\\\pipe\\\\'",
"+",
"str",
";",
"}",
"else",
"{",
"return",
"str",
";",
"}",
"}"
] |
windows sucks, so we have handle windows-type of socket-paths
@link https://gist.github.com/domenic/2790533#gistcomment-331356
|
[
"windows",
"sucks",
"so",
"we",
"have",
"handle",
"windows",
"-",
"type",
"of",
"socket",
"-",
"paths"
] |
b1a1c4538d33be91ce950a800140289fbdf9f792
|
https://github.com/pubkey/broadcast-channel/blob/b1a1c4538d33be91ce950a800140289fbdf9f792/dist/es/methods/node.js#L44-L52
|
17,029
|
pubkey/broadcast-channel
|
dist/es/methods/node.js
|
emitOverFastPath
|
function emitOverFastPath(state, msgObj, messageJson) {
if (!state.options.node.useFastPath) return; // disabled
var others = OTHER_INSTANCES[state.channelName].filter(function (s) {
return s !== state;
});
var checkObj = {
time: msgObj.time,
senderUuid: msgObj.uuid,
token: msgObj.token
};
others.filter(function (otherState) {
return _filterMessage(checkObj, otherState);
}).forEach(function (otherState) {
otherState.messagesCallback(messageJson);
});
}
|
javascript
|
function emitOverFastPath(state, msgObj, messageJson) {
if (!state.options.node.useFastPath) return; // disabled
var others = OTHER_INSTANCES[state.channelName].filter(function (s) {
return s !== state;
});
var checkObj = {
time: msgObj.time,
senderUuid: msgObj.uuid,
token: msgObj.token
};
others.filter(function (otherState) {
return _filterMessage(checkObj, otherState);
}).forEach(function (otherState) {
otherState.messagesCallback(messageJson);
});
}
|
[
"function",
"emitOverFastPath",
"(",
"state",
",",
"msgObj",
",",
"messageJson",
")",
"{",
"if",
"(",
"!",
"state",
".",
"options",
".",
"node",
".",
"useFastPath",
")",
"return",
";",
"// disabled",
"var",
"others",
"=",
"OTHER_INSTANCES",
"[",
"state",
".",
"channelName",
"]",
".",
"filter",
"(",
"function",
"(",
"s",
")",
"{",
"return",
"s",
"!==",
"state",
";",
"}",
")",
";",
"var",
"checkObj",
"=",
"{",
"time",
":",
"msgObj",
".",
"time",
",",
"senderUuid",
":",
"msgObj",
".",
"uuid",
",",
"token",
":",
"msgObj",
".",
"token",
"}",
";",
"others",
".",
"filter",
"(",
"function",
"(",
"otherState",
")",
"{",
"return",
"_filterMessage",
"(",
"checkObj",
",",
"otherState",
")",
";",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"otherState",
")",
"{",
"otherState",
".",
"messagesCallback",
"(",
"messageJson",
")",
";",
"}",
")",
";",
"}"
] |
When multiple BroadcastChannels with the same name
are created in a single node-process, we can access them directly and emit messages.
This might not happen often in production
but will speed up things when this module is used in unit-tests.
|
[
"When",
"multiple",
"BroadcastChannels",
"with",
"the",
"same",
"name",
"are",
"created",
"in",
"a",
"single",
"node",
"-",
"process",
"we",
"can",
"access",
"them",
"directly",
"and",
"emit",
"messages",
".",
"This",
"might",
"not",
"happen",
"often",
"in",
"production",
"but",
"will",
"speed",
"up",
"things",
"when",
"this",
"module",
"is",
"used",
"in",
"unit",
"-",
"tests",
"."
] |
b1a1c4538d33be91ce950a800140289fbdf9f792
|
https://github.com/pubkey/broadcast-channel/blob/b1a1c4538d33be91ce950a800140289fbdf9f792/dist/es/methods/node.js#L1050-L1066
|
17,030
|
pubkey/broadcast-channel
|
dist/es/leader-election/index.js
|
whenDeathListener
|
function whenDeathListener(msg) {
if (msg.context === 'leader' && msg.action === 'death') {
leaderElector.applyOnce().then(function () {
if (leaderElector.isLeader) finish();
});
}
}
|
javascript
|
function whenDeathListener(msg) {
if (msg.context === 'leader' && msg.action === 'death') {
leaderElector.applyOnce().then(function () {
if (leaderElector.isLeader) finish();
});
}
}
|
[
"function",
"whenDeathListener",
"(",
"msg",
")",
"{",
"if",
"(",
"msg",
".",
"context",
"===",
"'leader'",
"&&",
"msg",
".",
"action",
"===",
"'death'",
")",
"{",
"leaderElector",
".",
"applyOnce",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"leaderElector",
".",
"isLeader",
")",
"finish",
"(",
")",
";",
"}",
")",
";",
"}",
"}"
] |
try when other leader dies
|
[
"try",
"when",
"other",
"leader",
"dies"
] |
b1a1c4538d33be91ce950a800140289fbdf9f792
|
https://github.com/pubkey/broadcast-channel/blob/b1a1c4538d33be91ce950a800140289fbdf9f792/dist/es/leader-election/index.js#L150-L156
|
17,031
|
pubkey/broadcast-channel
|
dist/lib/methods/indexed-db.js
|
writeMessage
|
function writeMessage(db, readerUuid, messageJson) {
var time = new Date().getTime();
var writeObject = {
uuid: readerUuid,
time: time,
data: messageJson
};
var transaction = db.transaction([OBJECT_STORE_ID], 'readwrite');
return new Promise(function (res, rej) {
transaction.oncomplete = function () {
return res();
};
transaction.onerror = function (ev) {
return rej(ev);
};
var objectStore = transaction.objectStore(OBJECT_STORE_ID);
objectStore.add(writeObject);
});
}
|
javascript
|
function writeMessage(db, readerUuid, messageJson) {
var time = new Date().getTime();
var writeObject = {
uuid: readerUuid,
time: time,
data: messageJson
};
var transaction = db.transaction([OBJECT_STORE_ID], 'readwrite');
return new Promise(function (res, rej) {
transaction.oncomplete = function () {
return res();
};
transaction.onerror = function (ev) {
return rej(ev);
};
var objectStore = transaction.objectStore(OBJECT_STORE_ID);
objectStore.add(writeObject);
});
}
|
[
"function",
"writeMessage",
"(",
"db",
",",
"readerUuid",
",",
"messageJson",
")",
"{",
"var",
"time",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"var",
"writeObject",
"=",
"{",
"uuid",
":",
"readerUuid",
",",
"time",
":",
"time",
",",
"data",
":",
"messageJson",
"}",
";",
"var",
"transaction",
"=",
"db",
".",
"transaction",
"(",
"[",
"OBJECT_STORE_ID",
"]",
",",
"'readwrite'",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"res",
",",
"rej",
")",
"{",
"transaction",
".",
"oncomplete",
"=",
"function",
"(",
")",
"{",
"return",
"res",
"(",
")",
";",
"}",
";",
"transaction",
".",
"onerror",
"=",
"function",
"(",
"ev",
")",
"{",
"return",
"rej",
"(",
"ev",
")",
";",
"}",
";",
"var",
"objectStore",
"=",
"transaction",
".",
"objectStore",
"(",
"OBJECT_STORE_ID",
")",
";",
"objectStore",
".",
"add",
"(",
"writeObject",
")",
";",
"}",
")",
";",
"}"
] |
writes the new message to the database
so other readers can find it
|
[
"writes",
"the",
"new",
"message",
"to",
"the",
"database",
"so",
"other",
"readers",
"can",
"find",
"it"
] |
b1a1c4538d33be91ce950a800140289fbdf9f792
|
https://github.com/pubkey/broadcast-channel/blob/b1a1c4538d33be91ce950a800140289fbdf9f792/dist/lib/methods/indexed-db.js#L83-L103
|
17,032
|
pubkey/broadcast-channel
|
dist/lib/methods/indexed-db.js
|
readNewMessages
|
function readNewMessages(state) {
// channel already closed
if (state.closed) return Promise.resolve(); // if no one is listening, we do not need to scan for new messages
if (!state.messagesCallback) return Promise.resolve();
return getMessagesHigherThen(state.db, state.lastCursorId).then(function (newerMessages) {
var useMessages = newerMessages.map(function (msgObj) {
if (msgObj.id > state.lastCursorId) {
state.lastCursorId = msgObj.id;
}
return msgObj;
}).filter(function (msgObj) {
return _filterMessage(msgObj, state);
}).sort(function (msgObjA, msgObjB) {
return msgObjA.time - msgObjB.time;
}); // sort by time
useMessages.forEach(function (msgObj) {
if (state.messagesCallback) {
state.eMIs.add(msgObj.id);
state.messagesCallback(msgObj.data);
}
});
return Promise.resolve();
});
}
|
javascript
|
function readNewMessages(state) {
// channel already closed
if (state.closed) return Promise.resolve(); // if no one is listening, we do not need to scan for new messages
if (!state.messagesCallback) return Promise.resolve();
return getMessagesHigherThen(state.db, state.lastCursorId).then(function (newerMessages) {
var useMessages = newerMessages.map(function (msgObj) {
if (msgObj.id > state.lastCursorId) {
state.lastCursorId = msgObj.id;
}
return msgObj;
}).filter(function (msgObj) {
return _filterMessage(msgObj, state);
}).sort(function (msgObjA, msgObjB) {
return msgObjA.time - msgObjB.time;
}); // sort by time
useMessages.forEach(function (msgObj) {
if (state.messagesCallback) {
state.eMIs.add(msgObj.id);
state.messagesCallback(msgObj.data);
}
});
return Promise.resolve();
});
}
|
[
"function",
"readNewMessages",
"(",
"state",
")",
"{",
"// channel already closed",
"if",
"(",
"state",
".",
"closed",
")",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"// if no one is listening, we do not need to scan for new messages",
"if",
"(",
"!",
"state",
".",
"messagesCallback",
")",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"return",
"getMessagesHigherThen",
"(",
"state",
".",
"db",
",",
"state",
".",
"lastCursorId",
")",
".",
"then",
"(",
"function",
"(",
"newerMessages",
")",
"{",
"var",
"useMessages",
"=",
"newerMessages",
".",
"map",
"(",
"function",
"(",
"msgObj",
")",
"{",
"if",
"(",
"msgObj",
".",
"id",
">",
"state",
".",
"lastCursorId",
")",
"{",
"state",
".",
"lastCursorId",
"=",
"msgObj",
".",
"id",
";",
"}",
"return",
"msgObj",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"msgObj",
")",
"{",
"return",
"_filterMessage",
"(",
"msgObj",
",",
"state",
")",
";",
"}",
")",
".",
"sort",
"(",
"function",
"(",
"msgObjA",
",",
"msgObjB",
")",
"{",
"return",
"msgObjA",
".",
"time",
"-",
"msgObjB",
".",
"time",
";",
"}",
")",
";",
"// sort by time",
"useMessages",
".",
"forEach",
"(",
"function",
"(",
"msgObj",
")",
"{",
"if",
"(",
"state",
".",
"messagesCallback",
")",
"{",
"state",
".",
"eMIs",
".",
"add",
"(",
"msgObj",
".",
"id",
")",
";",
"state",
".",
"messagesCallback",
"(",
"msgObj",
".",
"data",
")",
";",
"}",
"}",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}"
] |
reads all new messages from the database and emits them
|
[
"reads",
"all",
"new",
"messages",
"from",
"the",
"database",
"and",
"emits",
"them"
] |
b1a1c4538d33be91ce950a800140289fbdf9f792
|
https://github.com/pubkey/broadcast-channel/blob/b1a1c4538d33be91ce950a800140289fbdf9f792/dist/lib/methods/indexed-db.js#L243-L269
|
17,033
|
pubkey/broadcast-channel
|
dist/lib/index.js
|
listenerFn
|
function listenerFn(msgObj) {
channel._addEL[msgObj.type].forEach(function (obj) {
if (msgObj.time >= obj.time) {
obj.fn(msgObj.data);
}
});
}
|
javascript
|
function listenerFn(msgObj) {
channel._addEL[msgObj.type].forEach(function (obj) {
if (msgObj.time >= obj.time) {
obj.fn(msgObj.data);
}
});
}
|
[
"function",
"listenerFn",
"(",
"msgObj",
")",
"{",
"channel",
".",
"_addEL",
"[",
"msgObj",
".",
"type",
"]",
".",
"forEach",
"(",
"function",
"(",
"obj",
")",
"{",
"if",
"(",
"msgObj",
".",
"time",
">=",
"obj",
".",
"time",
")",
"{",
"obj",
".",
"fn",
"(",
"msgObj",
".",
"data",
")",
";",
"}",
"}",
")",
";",
"}"
] |
someone is listening, start subscribing
|
[
"someone",
"is",
"listening",
"start",
"subscribing"
] |
b1a1c4538d33be91ce950a800140289fbdf9f792
|
https://github.com/pubkey/broadcast-channel/blob/b1a1c4538d33be91ce950a800140289fbdf9f792/dist/lib/index.js#L201-L207
|
17,034
|
pubkey/broadcast-channel
|
src/leader-election/index.js
|
_sendMessage
|
function _sendMessage(leaderElector, action) {
const msgJson = {
context: 'leader',
action,
token: leaderElector.token
};
return leaderElector._channel.postInternal(msgJson);
}
|
javascript
|
function _sendMessage(leaderElector, action) {
const msgJson = {
context: 'leader',
action,
token: leaderElector.token
};
return leaderElector._channel.postInternal(msgJson);
}
|
[
"function",
"_sendMessage",
"(",
"leaderElector",
",",
"action",
")",
"{",
"const",
"msgJson",
"=",
"{",
"context",
":",
"'leader'",
",",
"action",
",",
"token",
":",
"leaderElector",
".",
"token",
"}",
";",
"return",
"leaderElector",
".",
"_channel",
".",
"postInternal",
"(",
"msgJson",
")",
";",
"}"
] |
sends and internal message over the broadcast-channel
|
[
"sends",
"and",
"internal",
"message",
"over",
"the",
"broadcast",
"-",
"channel"
] |
b1a1c4538d33be91ce950a800140289fbdf9f792
|
https://github.com/pubkey/broadcast-channel/blob/b1a1c4538d33be91ce950a800140289fbdf9f792/src/leader-election/index.js#L153-L160
|
17,035
|
pubkey/broadcast-channel
|
src/methods/node.js
|
createSocketInfoFile
|
function createSocketInfoFile(channelName, readerUuid, paths) {
const pathToFile = socketInfoPath(channelName, readerUuid, paths);
return writeFile(
pathToFile,
JSON.stringify({
time: microSeconds()
})
).then(() => pathToFile);
}
|
javascript
|
function createSocketInfoFile(channelName, readerUuid, paths) {
const pathToFile = socketInfoPath(channelName, readerUuid, paths);
return writeFile(
pathToFile,
JSON.stringify({
time: microSeconds()
})
).then(() => pathToFile);
}
|
[
"function",
"createSocketInfoFile",
"(",
"channelName",
",",
"readerUuid",
",",
"paths",
")",
"{",
"const",
"pathToFile",
"=",
"socketInfoPath",
"(",
"channelName",
",",
"readerUuid",
",",
"paths",
")",
";",
"return",
"writeFile",
"(",
"pathToFile",
",",
"JSON",
".",
"stringify",
"(",
"{",
"time",
":",
"microSeconds",
"(",
")",
"}",
")",
")",
".",
"then",
"(",
"(",
")",
"=>",
"pathToFile",
")",
";",
"}"
] |
Because it is not possible to get all socket-files in a folder,
when used under fucking windows,
we have to set a normal file so other readers know our socket exists
|
[
"Because",
"it",
"is",
"not",
"possible",
"to",
"get",
"all",
"socket",
"-",
"files",
"in",
"a",
"folder",
"when",
"used",
"under",
"fucking",
"windows",
"we",
"have",
"to",
"set",
"a",
"normal",
"file",
"so",
"other",
"readers",
"know",
"our",
"socket",
"exists"
] |
b1a1c4538d33be91ce950a800140289fbdf9f792
|
https://github.com/pubkey/broadcast-channel/blob/b1a1c4538d33be91ce950a800140289fbdf9f792/src/methods/node.js#L159-L167
|
17,036
|
pubkey/broadcast-channel
|
src/methods/node.js
|
countChannelFolders
|
async function countChannelFolders() {
await ensureBaseFolderExists();
const folders = await readdir(TMP_FOLDER_BASE);
return folders.length;
}
|
javascript
|
async function countChannelFolders() {
await ensureBaseFolderExists();
const folders = await readdir(TMP_FOLDER_BASE);
return folders.length;
}
|
[
"async",
"function",
"countChannelFolders",
"(",
")",
"{",
"await",
"ensureBaseFolderExists",
"(",
")",
";",
"const",
"folders",
"=",
"await",
"readdir",
"(",
"TMP_FOLDER_BASE",
")",
";",
"return",
"folders",
".",
"length",
";",
"}"
] |
returns the amount of channel-folders in the tmp-directory
@return {Promise<number>}
|
[
"returns",
"the",
"amount",
"of",
"channel",
"-",
"folders",
"in",
"the",
"tmp",
"-",
"directory"
] |
b1a1c4538d33be91ce950a800140289fbdf9f792
|
https://github.com/pubkey/broadcast-channel/blob/b1a1c4538d33be91ce950a800140289fbdf9f792/src/methods/node.js#L173-L177
|
17,037
|
pubkey/broadcast-channel
|
src/methods/node.js
|
getReadersUuids
|
async function getReadersUuids(channelName, paths) {
paths = paths || getPaths(channelName);
const readersPath = paths.readers;
const files = await readdir(readersPath);
return files
.map(file => file.split('.'))
.filter(split => split[1] === 'json') // do not scan .socket-files
.map(split => split[0]);
}
|
javascript
|
async function getReadersUuids(channelName, paths) {
paths = paths || getPaths(channelName);
const readersPath = paths.readers;
const files = await readdir(readersPath);
return files
.map(file => file.split('.'))
.filter(split => split[1] === 'json') // do not scan .socket-files
.map(split => split[0]);
}
|
[
"async",
"function",
"getReadersUuids",
"(",
"channelName",
",",
"paths",
")",
"{",
"paths",
"=",
"paths",
"||",
"getPaths",
"(",
"channelName",
")",
";",
"const",
"readersPath",
"=",
"paths",
".",
"readers",
";",
"const",
"files",
"=",
"await",
"readdir",
"(",
"readersPath",
")",
";",
"return",
"files",
".",
"map",
"(",
"file",
"=>",
"file",
".",
"split",
"(",
"'.'",
")",
")",
".",
"filter",
"(",
"split",
"=>",
"split",
"[",
"1",
"]",
"===",
"'json'",
")",
"// do not scan .socket-files",
".",
"map",
"(",
"split",
"=>",
"split",
"[",
"0",
"]",
")",
";",
"}"
] |
returns the uuids of all readers
@return {string[]}
|
[
"returns",
"the",
"uuids",
"of",
"all",
"readers"
] |
b1a1c4538d33be91ce950a800140289fbdf9f792
|
https://github.com/pubkey/broadcast-channel/blob/b1a1c4538d33be91ce950a800140289fbdf9f792/src/methods/node.js#L287-L296
|
17,038
|
pubkey/broadcast-channel
|
src/methods/node.js
|
create
|
async function create(channelName, options = {}) {
options = fillOptionsWithDefaults(options);
const time = microSeconds();
const paths = getPaths(channelName);
const ensureFolderExistsPromise = ensureFoldersExist(channelName, paths);
const uuid = randomToken(10);
const state = {
time,
channelName,
options,
uuid,
paths,
// contains all messages that have been emitted before
emittedMessagesIds: new ObliviousSet(options.node.ttl * 2),
messagesCallbackTime: null,
messagesCallback: null,
// ensures we do not read messages in parrallel
writeBlockPromise: Promise.resolve(),
otherReaderClients: {},
// ensure if process crashes, everything is cleaned up
removeUnload: unload.add(() => close(state)),
closed: false
};
if (!OTHER_INSTANCES[channelName]) OTHER_INSTANCES[channelName] = [];
OTHER_INSTANCES[channelName].push(state);
await ensureFolderExistsPromise;
const [
socketEE,
infoFilePath
] = await Promise.all([
createSocketEventEmitter(channelName, uuid, paths),
createSocketInfoFile(channelName, uuid, paths),
refreshReaderClients(state)
]);
state.socketEE = socketEE;
state.infoFilePath = infoFilePath;
// when new message comes in, we read it and emit it
socketEE.emitter.on('data', data => {
// if the socket is used fast, it may appear that multiple messages are flushed at once
// so we have to split them before
const singleOnes = data.split('|');
singleOnes
.filter(single => single !== '')
.forEach(single => {
try {
const obj = JSON.parse(single);
handleMessagePing(state, obj);
} catch (err) {
throw new Error('could not parse data: ' + single);
}
});
});
return state;
}
|
javascript
|
async function create(channelName, options = {}) {
options = fillOptionsWithDefaults(options);
const time = microSeconds();
const paths = getPaths(channelName);
const ensureFolderExistsPromise = ensureFoldersExist(channelName, paths);
const uuid = randomToken(10);
const state = {
time,
channelName,
options,
uuid,
paths,
// contains all messages that have been emitted before
emittedMessagesIds: new ObliviousSet(options.node.ttl * 2),
messagesCallbackTime: null,
messagesCallback: null,
// ensures we do not read messages in parrallel
writeBlockPromise: Promise.resolve(),
otherReaderClients: {},
// ensure if process crashes, everything is cleaned up
removeUnload: unload.add(() => close(state)),
closed: false
};
if (!OTHER_INSTANCES[channelName]) OTHER_INSTANCES[channelName] = [];
OTHER_INSTANCES[channelName].push(state);
await ensureFolderExistsPromise;
const [
socketEE,
infoFilePath
] = await Promise.all([
createSocketEventEmitter(channelName, uuid, paths),
createSocketInfoFile(channelName, uuid, paths),
refreshReaderClients(state)
]);
state.socketEE = socketEE;
state.infoFilePath = infoFilePath;
// when new message comes in, we read it and emit it
socketEE.emitter.on('data', data => {
// if the socket is used fast, it may appear that multiple messages are flushed at once
// so we have to split them before
const singleOnes = data.split('|');
singleOnes
.filter(single => single !== '')
.forEach(single => {
try {
const obj = JSON.parse(single);
handleMessagePing(state, obj);
} catch (err) {
throw new Error('could not parse data: ' + single);
}
});
});
return state;
}
|
[
"async",
"function",
"create",
"(",
"channelName",
",",
"options",
"=",
"{",
"}",
")",
"{",
"options",
"=",
"fillOptionsWithDefaults",
"(",
"options",
")",
";",
"const",
"time",
"=",
"microSeconds",
"(",
")",
";",
"const",
"paths",
"=",
"getPaths",
"(",
"channelName",
")",
";",
"const",
"ensureFolderExistsPromise",
"=",
"ensureFoldersExist",
"(",
"channelName",
",",
"paths",
")",
";",
"const",
"uuid",
"=",
"randomToken",
"(",
"10",
")",
";",
"const",
"state",
"=",
"{",
"time",
",",
"channelName",
",",
"options",
",",
"uuid",
",",
"paths",
",",
"// contains all messages that have been emitted before",
"emittedMessagesIds",
":",
"new",
"ObliviousSet",
"(",
"options",
".",
"node",
".",
"ttl",
"*",
"2",
")",
",",
"messagesCallbackTime",
":",
"null",
",",
"messagesCallback",
":",
"null",
",",
"// ensures we do not read messages in parrallel",
"writeBlockPromise",
":",
"Promise",
".",
"resolve",
"(",
")",
",",
"otherReaderClients",
":",
"{",
"}",
",",
"// ensure if process crashes, everything is cleaned up",
"removeUnload",
":",
"unload",
".",
"add",
"(",
"(",
")",
"=>",
"close",
"(",
"state",
")",
")",
",",
"closed",
":",
"false",
"}",
";",
"if",
"(",
"!",
"OTHER_INSTANCES",
"[",
"channelName",
"]",
")",
"OTHER_INSTANCES",
"[",
"channelName",
"]",
"=",
"[",
"]",
";",
"OTHER_INSTANCES",
"[",
"channelName",
"]",
".",
"push",
"(",
"state",
")",
";",
"await",
"ensureFolderExistsPromise",
";",
"const",
"[",
"socketEE",
",",
"infoFilePath",
"]",
"=",
"await",
"Promise",
".",
"all",
"(",
"[",
"createSocketEventEmitter",
"(",
"channelName",
",",
"uuid",
",",
"paths",
")",
",",
"createSocketInfoFile",
"(",
"channelName",
",",
"uuid",
",",
"paths",
")",
",",
"refreshReaderClients",
"(",
"state",
")",
"]",
")",
";",
"state",
".",
"socketEE",
"=",
"socketEE",
";",
"state",
".",
"infoFilePath",
"=",
"infoFilePath",
";",
"// when new message comes in, we read it and emit it",
"socketEE",
".",
"emitter",
".",
"on",
"(",
"'data'",
",",
"data",
"=>",
"{",
"// if the socket is used fast, it may appear that multiple messages are flushed at once",
"// so we have to split them before",
"const",
"singleOnes",
"=",
"data",
".",
"split",
"(",
"'|'",
")",
";",
"singleOnes",
".",
"filter",
"(",
"single",
"=>",
"single",
"!==",
"''",
")",
".",
"forEach",
"(",
"single",
"=>",
"{",
"try",
"{",
"const",
"obj",
"=",
"JSON",
".",
"parse",
"(",
"single",
")",
";",
"handleMessagePing",
"(",
"state",
",",
"obj",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"'could not parse data: '",
"+",
"single",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"return",
"state",
";",
"}"
] |
creates a new channelState
@return {Promise<any>}
|
[
"creates",
"a",
"new",
"channelState"
] |
b1a1c4538d33be91ce950a800140289fbdf9f792
|
https://github.com/pubkey/broadcast-channel/blob/b1a1c4538d33be91ce950a800140289fbdf9f792/src/methods/node.js#L365-L424
|
17,039
|
pubkey/broadcast-channel
|
src/methods/node.js
|
handleMessagePing
|
async function handleMessagePing(state, msgObj) {
/**
* when there are no listener, we do nothing
*/
if (!state.messagesCallback) return;
let messages;
if (!msgObj) {
// get all
messages = await getAllMessages(state.channelName, state.paths);
} else {
// get single message
messages = [
getSingleMessage(state.channelName, msgObj, state.paths)
];
}
const useMessages = messages
.filter(msgObj => _filterMessage(msgObj, state))
.sort((msgObjA, msgObjB) => msgObjA.time - msgObjB.time); // sort by time
// if no listener or message, so not do anything
if (!useMessages.length || !state.messagesCallback) return;
// read contents
await Promise.all(
useMessages
.map(
msgObj => readMessage(msgObj).then(content => msgObj.content = content)
)
);
useMessages.forEach(msgObj => {
state.emittedMessagesIds.add(msgObj.token);
if (state.messagesCallback) {
// emit to subscribers
state.messagesCallback(msgObj.content.data);
}
});
}
|
javascript
|
async function handleMessagePing(state, msgObj) {
/**
* when there are no listener, we do nothing
*/
if (!state.messagesCallback) return;
let messages;
if (!msgObj) {
// get all
messages = await getAllMessages(state.channelName, state.paths);
} else {
// get single message
messages = [
getSingleMessage(state.channelName, msgObj, state.paths)
];
}
const useMessages = messages
.filter(msgObj => _filterMessage(msgObj, state))
.sort((msgObjA, msgObjB) => msgObjA.time - msgObjB.time); // sort by time
// if no listener or message, so not do anything
if (!useMessages.length || !state.messagesCallback) return;
// read contents
await Promise.all(
useMessages
.map(
msgObj => readMessage(msgObj).then(content => msgObj.content = content)
)
);
useMessages.forEach(msgObj => {
state.emittedMessagesIds.add(msgObj.token);
if (state.messagesCallback) {
// emit to subscribers
state.messagesCallback(msgObj.content.data);
}
});
}
|
[
"async",
"function",
"handleMessagePing",
"(",
"state",
",",
"msgObj",
")",
"{",
"/**\n * when there are no listener, we do nothing\n */",
"if",
"(",
"!",
"state",
".",
"messagesCallback",
")",
"return",
";",
"let",
"messages",
";",
"if",
"(",
"!",
"msgObj",
")",
"{",
"// get all",
"messages",
"=",
"await",
"getAllMessages",
"(",
"state",
".",
"channelName",
",",
"state",
".",
"paths",
")",
";",
"}",
"else",
"{",
"// get single message",
"messages",
"=",
"[",
"getSingleMessage",
"(",
"state",
".",
"channelName",
",",
"msgObj",
",",
"state",
".",
"paths",
")",
"]",
";",
"}",
"const",
"useMessages",
"=",
"messages",
".",
"filter",
"(",
"msgObj",
"=>",
"_filterMessage",
"(",
"msgObj",
",",
"state",
")",
")",
".",
"sort",
"(",
"(",
"msgObjA",
",",
"msgObjB",
")",
"=>",
"msgObjA",
".",
"time",
"-",
"msgObjB",
".",
"time",
")",
";",
"// sort by time",
"// if no listener or message, so not do anything",
"if",
"(",
"!",
"useMessages",
".",
"length",
"||",
"!",
"state",
".",
"messagesCallback",
")",
"return",
";",
"// read contents",
"await",
"Promise",
".",
"all",
"(",
"useMessages",
".",
"map",
"(",
"msgObj",
"=>",
"readMessage",
"(",
"msgObj",
")",
".",
"then",
"(",
"content",
"=>",
"msgObj",
".",
"content",
"=",
"content",
")",
")",
")",
";",
"useMessages",
".",
"forEach",
"(",
"msgObj",
"=>",
"{",
"state",
".",
"emittedMessagesIds",
".",
"add",
"(",
"msgObj",
".",
"token",
")",
";",
"if",
"(",
"state",
".",
"messagesCallback",
")",
"{",
"// emit to subscribers",
"state",
".",
"messagesCallback",
"(",
"msgObj",
".",
"content",
".",
"data",
")",
";",
"}",
"}",
")",
";",
"}"
] |
when the socket pings, so that we now new messages came,
run this
|
[
"when",
"the",
"socket",
"pings",
"so",
"that",
"we",
"now",
"new",
"messages",
"came",
"run",
"this"
] |
b1a1c4538d33be91ce950a800140289fbdf9f792
|
https://github.com/pubkey/broadcast-channel/blob/b1a1c4538d33be91ce950a800140289fbdf9f792/src/methods/node.js#L441-L483
|
17,040
|
angular-ui/ui-ace
|
src/ui-ace.js
|
function () {
/**
* The callback function grabbed from the array-like arguments
* object. The first argument should always be the callback.
*
* @see [arguments]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments}
* @type {*}
*/
var callback = arguments[0];
/**
* Arguments to be passed to the callback. These are taken
* from the array-like arguments object. The first argument
* is stripped because that should be the callback function.
*
* @see [arguments]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments}
* @type {Array}
*/
var args = Array.prototype.slice.call(arguments, 1);
if (angular.isDefined(callback)) {
scope.$evalAsync(function () {
if (angular.isFunction(callback)) {
callback(args);
} else {
throw new Error('ui-ace use a function as callback.');
}
});
}
}
|
javascript
|
function () {
/**
* The callback function grabbed from the array-like arguments
* object. The first argument should always be the callback.
*
* @see [arguments]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments}
* @type {*}
*/
var callback = arguments[0];
/**
* Arguments to be passed to the callback. These are taken
* from the array-like arguments object. The first argument
* is stripped because that should be the callback function.
*
* @see [arguments]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments}
* @type {Array}
*/
var args = Array.prototype.slice.call(arguments, 1);
if (angular.isDefined(callback)) {
scope.$evalAsync(function () {
if (angular.isFunction(callback)) {
callback(args);
} else {
throw new Error('ui-ace use a function as callback.');
}
});
}
}
|
[
"function",
"(",
")",
"{",
"/**\n * The callback function grabbed from the array-like arguments\n * object. The first argument should always be the callback.\n *\n * @see [arguments]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments}\n * @type {*}\n */",
"var",
"callback",
"=",
"arguments",
"[",
"0",
"]",
";",
"/**\n * Arguments to be passed to the callback. These are taken\n * from the array-like arguments object. The first argument\n * is stripped because that should be the callback function.\n *\n * @see [arguments]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments}\n * @type {Array}\n */",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"if",
"(",
"angular",
".",
"isDefined",
"(",
"callback",
")",
")",
"{",
"scope",
".",
"$evalAsync",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"angular",
".",
"isFunction",
"(",
"callback",
")",
")",
"{",
"callback",
"(",
"args",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'ui-ace use a function as callback.'",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] |
Calls a callback by checking its existing. The argument list
is variable and thus this function is relying on the arguments
object.
@throws {Error} If the callback isn't a function
|
[
"Calls",
"a",
"callback",
"by",
"checking",
"its",
"existing",
".",
"The",
"argument",
"list",
"is",
"variable",
"and",
"thus",
"this",
"function",
"is",
"relying",
"on",
"the",
"arguments",
"object",
"."
] |
4c62a97e0adc60b7cde2be4caf902ac95c5c8c34
|
https://github.com/angular-ui/ui-ace/blob/4c62a97e0adc60b7cde2be4caf902ac95c5c8c34/src/ui-ace.js#L177-L207
|
|
17,041
|
angular-ui/ui-ace
|
src/ui-ace.js
|
function (callback) {
return function (e) {
var newValue = session.getValue();
if (ngModel && newValue !== ngModel.$viewValue &&
// HACK make sure to only trigger the apply outside of the
// digest loop 'cause ACE is actually using this callback
// for any text transformation !
!scope.$$phase && !scope.$root.$$phase) {
scope.$evalAsync(function () {
ngModel.$setViewValue(newValue);
});
}
executeUserCallback(callback, e, acee);
};
}
|
javascript
|
function (callback) {
return function (e) {
var newValue = session.getValue();
if (ngModel && newValue !== ngModel.$viewValue &&
// HACK make sure to only trigger the apply outside of the
// digest loop 'cause ACE is actually using this callback
// for any text transformation !
!scope.$$phase && !scope.$root.$$phase) {
scope.$evalAsync(function () {
ngModel.$setViewValue(newValue);
});
}
executeUserCallback(callback, e, acee);
};
}
|
[
"function",
"(",
"callback",
")",
"{",
"return",
"function",
"(",
"e",
")",
"{",
"var",
"newValue",
"=",
"session",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"ngModel",
"&&",
"newValue",
"!==",
"ngModel",
".",
"$viewValue",
"&&",
"// HACK make sure to only trigger the apply outside of the",
"// digest loop 'cause ACE is actually using this callback",
"// for any text transformation !",
"!",
"scope",
".",
"$$phase",
"&&",
"!",
"scope",
".",
"$root",
".",
"$$phase",
")",
"{",
"scope",
".",
"$evalAsync",
"(",
"function",
"(",
")",
"{",
"ngModel",
".",
"$setViewValue",
"(",
"newValue",
")",
";",
"}",
")",
";",
"}",
"executeUserCallback",
"(",
"callback",
",",
"e",
",",
"acee",
")",
";",
"}",
";",
"}"
] |
Creates a change listener which propagates the change event
and the editor session to the callback from the user option
onChange. It might be exchanged during runtime, if this
happens the old listener will be unbound.
@param callback callback function defined in the user options
@see onChangeListener
|
[
"Creates",
"a",
"change",
"listener",
"which",
"propagates",
"the",
"change",
"event",
"and",
"the",
"editor",
"session",
"to",
"the",
"callback",
"from",
"the",
"user",
"option",
"onChange",
".",
"It",
"might",
"be",
"exchanged",
"during",
"runtime",
"if",
"this",
"happens",
"the",
"old",
"listener",
"will",
"be",
"unbound",
"."
] |
4c62a97e0adc60b7cde2be4caf902ac95c5c8c34
|
https://github.com/angular-ui/ui-ace/blob/4c62a97e0adc60b7cde2be4caf902ac95c5c8c34/src/ui-ace.js#L223-L239
|
|
17,042
|
angular-ui/ui-ace
|
src/ui-ace.js
|
function (current, previous) {
if (current === previous) return;
opts = angular.extend({}, options, scope.$eval(attrs.uiAce));
opts.callbacks = [ opts.onLoad ];
if (opts.onLoad !== options.onLoad) {
// also call the global onLoad handler
opts.callbacks.unshift(options.onLoad);
}
// EVENTS
// unbind old change listener
session.removeListener('change', onChangeListener);
// bind new change listener
onChangeListener = listenerFactory.onChange(opts.onChange);
session.on('change', onChangeListener);
// unbind old blur listener
//session.removeListener('blur', onBlurListener);
acee.removeListener('blur', onBlurListener);
// bind new blur listener
onBlurListener = listenerFactory.onBlur(opts.onBlur);
acee.on('blur', onBlurListener);
setOptions(acee, session, opts);
}
|
javascript
|
function (current, previous) {
if (current === previous) return;
opts = angular.extend({}, options, scope.$eval(attrs.uiAce));
opts.callbacks = [ opts.onLoad ];
if (opts.onLoad !== options.onLoad) {
// also call the global onLoad handler
opts.callbacks.unshift(options.onLoad);
}
// EVENTS
// unbind old change listener
session.removeListener('change', onChangeListener);
// bind new change listener
onChangeListener = listenerFactory.onChange(opts.onChange);
session.on('change', onChangeListener);
// unbind old blur listener
//session.removeListener('blur', onBlurListener);
acee.removeListener('blur', onBlurListener);
// bind new blur listener
onBlurListener = listenerFactory.onBlur(opts.onBlur);
acee.on('blur', onBlurListener);
setOptions(acee, session, opts);
}
|
[
"function",
"(",
"current",
",",
"previous",
")",
"{",
"if",
"(",
"current",
"===",
"previous",
")",
"return",
";",
"opts",
"=",
"angular",
".",
"extend",
"(",
"{",
"}",
",",
"options",
",",
"scope",
".",
"$eval",
"(",
"attrs",
".",
"uiAce",
")",
")",
";",
"opts",
".",
"callbacks",
"=",
"[",
"opts",
".",
"onLoad",
"]",
";",
"if",
"(",
"opts",
".",
"onLoad",
"!==",
"options",
".",
"onLoad",
")",
"{",
"// also call the global onLoad handler",
"opts",
".",
"callbacks",
".",
"unshift",
"(",
"options",
".",
"onLoad",
")",
";",
"}",
"// EVENTS",
"// unbind old change listener",
"session",
".",
"removeListener",
"(",
"'change'",
",",
"onChangeListener",
")",
";",
"// bind new change listener",
"onChangeListener",
"=",
"listenerFactory",
".",
"onChange",
"(",
"opts",
".",
"onChange",
")",
";",
"session",
".",
"on",
"(",
"'change'",
",",
"onChangeListener",
")",
";",
"// unbind old blur listener",
"//session.removeListener('blur', onBlurListener);",
"acee",
".",
"removeListener",
"(",
"'blur'",
",",
"onBlurListener",
")",
";",
"// bind new blur listener",
"onBlurListener",
"=",
"listenerFactory",
".",
"onBlur",
"(",
"opts",
".",
"onBlur",
")",
";",
"acee",
".",
"on",
"(",
"'blur'",
",",
"onBlurListener",
")",
";",
"setOptions",
"(",
"acee",
",",
"session",
",",
"opts",
")",
";",
"}"
] |
Listen for option updates
|
[
"Listen",
"for",
"option",
"updates"
] |
4c62a97e0adc60b7cde2be4caf902ac95c5c8c34
|
https://github.com/angular-ui/ui-ace/blob/4c62a97e0adc60b7cde2be4caf902ac95c5c8c34/src/ui-ace.js#L278-L306
|
|
17,043
|
Esri/angular-esri-map
|
site/app/examples/chaining-promises.js
|
addGraphics
|
function addGraphics(buffer) {
layer.add(new Graphic({
geometry: meteorPoint,
symbol: pointSym
}));
layer.add(new Graphic({
geometry: buffer,
symbol: polySym
}));
return buffer;
}
|
javascript
|
function addGraphics(buffer) {
layer.add(new Graphic({
geometry: meteorPoint,
symbol: pointSym
}));
layer.add(new Graphic({
geometry: buffer,
symbol: polySym
}));
return buffer;
}
|
[
"function",
"addGraphics",
"(",
"buffer",
")",
"{",
"layer",
".",
"add",
"(",
"new",
"Graphic",
"(",
"{",
"geometry",
":",
"meteorPoint",
",",
"symbol",
":",
"pointSym",
"}",
")",
")",
";",
"layer",
".",
"add",
"(",
"new",
"Graphic",
"(",
"{",
"geometry",
":",
"buffer",
",",
"symbol",
":",
"polySym",
"}",
")",
")",
";",
"return",
"buffer",
";",
"}"
] |
adds the point and buffer graphics to the layer
|
[
"adds",
"the",
"point",
"and",
"buffer",
"graphics",
"to",
"the",
"layer"
] |
4623710f54adcd847c79df08180d6b1ec6d25f88
|
https://github.com/Esri/angular-esri-map/blob/4623710f54adcd847c79df08180d6b1ec6d25f88/site/app/examples/chaining-promises.js#L84-L95
|
17,044
|
Esri/angular-esri-map
|
site/app/examples/chaining-promises.js
|
zoomTo
|
function zoomTo(geom) {
// when the view is ready
return self.view.when(function() {
// zoom to the buffer geometry
return self.view.goTo({
target: geom,
scale: 24000,
tilt: 0,
heading: 0
}).then(function() {
// resolve the promises with the input geometry
return geom;
});
});
}
|
javascript
|
function zoomTo(geom) {
// when the view is ready
return self.view.when(function() {
// zoom to the buffer geometry
return self.view.goTo({
target: geom,
scale: 24000,
tilt: 0,
heading: 0
}).then(function() {
// resolve the promises with the input geometry
return geom;
});
});
}
|
[
"function",
"zoomTo",
"(",
"geom",
")",
"{",
"// when the view is ready",
"return",
"self",
".",
"view",
".",
"when",
"(",
"function",
"(",
")",
"{",
"// zoom to the buffer geometry",
"return",
"self",
".",
"view",
".",
"goTo",
"(",
"{",
"target",
":",
"geom",
",",
"scale",
":",
"24000",
",",
"tilt",
":",
"0",
",",
"heading",
":",
"0",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"// resolve the promises with the input geometry",
"return",
"geom",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
zooms to the buffer location
|
[
"zooms",
"to",
"the",
"buffer",
"location"
] |
4623710f54adcd847c79df08180d6b1ec6d25f88
|
https://github.com/Esri/angular-esri-map/blob/4623710f54adcd847c79df08180d6b1ec6d25f88/site/app/examples/chaining-promises.js#L98-L112
|
17,045
|
Esri/angular-esri-map
|
site/app/common/pathService.js
|
function(path) {
var pathParts = this.getPathParts(path),
tabs,
page;
if (pathParts.length === 0) {
return;
}
page = pathParts[0];
if (!page) {
return;
}
if (page === 'examples' && pathParts.length > 1) {
tabs = [];
tabs.push('app/examples/' + pathParts[1] + '.html');
tabs.push('app/examples/' + pathParts[1] + '.js');
return tabs;
}
}
|
javascript
|
function(path) {
var pathParts = this.getPathParts(path),
tabs,
page;
if (pathParts.length === 0) {
return;
}
page = pathParts[0];
if (!page) {
return;
}
if (page === 'examples' && pathParts.length > 1) {
tabs = [];
tabs.push('app/examples/' + pathParts[1] + '.html');
tabs.push('app/examples/' + pathParts[1] + '.js');
return tabs;
}
}
|
[
"function",
"(",
"path",
")",
"{",
"var",
"pathParts",
"=",
"this",
".",
"getPathParts",
"(",
"path",
")",
",",
"tabs",
",",
"page",
";",
"if",
"(",
"pathParts",
".",
"length",
"===",
"0",
")",
"{",
"return",
";",
"}",
"page",
"=",
"pathParts",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"page",
")",
"{",
"return",
";",
"}",
"if",
"(",
"page",
"===",
"'examples'",
"&&",
"pathParts",
".",
"length",
">",
"1",
")",
"{",
"tabs",
"=",
"[",
"]",
";",
"tabs",
".",
"push",
"(",
"'app/examples/'",
"+",
"pathParts",
"[",
"1",
"]",
"+",
"'.html'",
")",
";",
"tabs",
".",
"push",
"(",
"'app/examples/'",
"+",
"pathParts",
"[",
"1",
"]",
"+",
"'.js'",
")",
";",
"return",
"tabs",
";",
"}",
"}"
] |
parse snippet include file locations from route
|
[
"parse",
"snippet",
"include",
"file",
"locations",
"from",
"route"
] |
4623710f54adcd847c79df08180d6b1ec6d25f88
|
https://github.com/Esri/angular-esri-map/blob/4623710f54adcd847c79df08180d6b1ec6d25f88/site/app/common/pathService.js#L14-L31
|
|
17,046
|
witoldsz/angular-http-auth
|
dist/http-auth-interceptor.js
|
function(data, configUpdater) {
var updater = configUpdater || function(config) {return config;};
$rootScope.$broadcast('event:auth-loginConfirmed', data);
httpBuffer.retryAll(updater);
}
|
javascript
|
function(data, configUpdater) {
var updater = configUpdater || function(config) {return config;};
$rootScope.$broadcast('event:auth-loginConfirmed', data);
httpBuffer.retryAll(updater);
}
|
[
"function",
"(",
"data",
",",
"configUpdater",
")",
"{",
"var",
"updater",
"=",
"configUpdater",
"||",
"function",
"(",
"config",
")",
"{",
"return",
"config",
";",
"}",
";",
"$rootScope",
".",
"$broadcast",
"(",
"'event:auth-loginConfirmed'",
",",
"data",
")",
";",
"httpBuffer",
".",
"retryAll",
"(",
"updater",
")",
";",
"}"
] |
Call this function to indicate that authentication was successful and trigger a
retry of all deferred requests.
@param data an optional argument to pass on to $broadcast which may be useful for
example if you need to pass through details of the user that was logged in
@param configUpdater an optional transformation function that can modify the
requests that are retried after having logged in. This can be used for example
to add an authentication token. It must return the request.
|
[
"Call",
"this",
"function",
"to",
"indicate",
"that",
"authentication",
"was",
"successful",
"and",
"trigger",
"a",
"retry",
"of",
"all",
"deferred",
"requests",
"."
] |
8563641456cd84be1c8ed778c6346d01fb51daa8
|
https://github.com/witoldsz/angular-http-auth/blob/8563641456cd84be1c8ed778c6346d01fb51daa8/dist/http-auth-interceptor.js#L25-L29
|
|
17,047
|
witoldsz/angular-http-auth
|
dist/http-auth-interceptor.js
|
function(updater) {
for (var i = 0; i < buffer.length; ++i) {
var _cfg = updater(buffer[i].config);
if (_cfg !== false)
retryHttpRequest(_cfg, buffer[i].deferred);
}
buffer = [];
}
|
javascript
|
function(updater) {
for (var i = 0; i < buffer.length; ++i) {
var _cfg = updater(buffer[i].config);
if (_cfg !== false)
retryHttpRequest(_cfg, buffer[i].deferred);
}
buffer = [];
}
|
[
"function",
"(",
"updater",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"buffer",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"_cfg",
"=",
"updater",
"(",
"buffer",
"[",
"i",
"]",
".",
"config",
")",
";",
"if",
"(",
"_cfg",
"!==",
"false",
")",
"retryHttpRequest",
"(",
"_cfg",
",",
"buffer",
"[",
"i",
"]",
".",
"deferred",
")",
";",
"}",
"buffer",
"=",
"[",
"]",
";",
"}"
] |
Retries all the buffered requests clears the buffer.
|
[
"Retries",
"all",
"the",
"buffered",
"requests",
"clears",
"the",
"buffer",
"."
] |
8563641456cd84be1c8ed778c6346d01fb51daa8
|
https://github.com/witoldsz/angular-http-auth/blob/8563641456cd84be1c8ed778c6346d01fb51daa8/dist/http-auth-interceptor.js#L126-L133
|
|
17,048
|
tkrotoff/jquery-simplecolorpicker
|
jquery.simplecolorpicker.js
|
function(color) {
var self = this;
var $colorSpan = self.$colorList.find('> span.color').filter(function() {
return $(this).data('color').toLowerCase() === color.toLowerCase();
});
if ($colorSpan.length > 0) {
self.selectColorSpan($colorSpan);
} else {
console.error("The given color '" + color + "' could not be found");
}
}
|
javascript
|
function(color) {
var self = this;
var $colorSpan = self.$colorList.find('> span.color').filter(function() {
return $(this).data('color').toLowerCase() === color.toLowerCase();
});
if ($colorSpan.length > 0) {
self.selectColorSpan($colorSpan);
} else {
console.error("The given color '" + color + "' could not be found");
}
}
|
[
"function",
"(",
"color",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"$colorSpan",
"=",
"self",
".",
"$colorList",
".",
"find",
"(",
"'> span.color'",
")",
".",
"filter",
"(",
"function",
"(",
")",
"{",
"return",
"$",
"(",
"this",
")",
".",
"data",
"(",
"'color'",
")",
".",
"toLowerCase",
"(",
")",
"===",
"color",
".",
"toLowerCase",
"(",
")",
";",
"}",
")",
";",
"if",
"(",
"$colorSpan",
".",
"length",
">",
"0",
")",
"{",
"self",
".",
"selectColorSpan",
"(",
"$colorSpan",
")",
";",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"\"The given color '\"",
"+",
"color",
"+",
"\"' could not be found\"",
")",
";",
"}",
"}"
] |
Changes the selected color.
@param color the hexadecimal color to select, ex: '#fbd75b'
|
[
"Changes",
"the",
"selected",
"color",
"."
] |
5ab2a268766825c46247e37e7c8875de6f85aa6e
|
https://github.com/tkrotoff/jquery-simplecolorpicker/blob/5ab2a268766825c46247e37e7c8875de6f85aa6e/jquery.simplecolorpicker.js#L112-L124
|
|
17,049
|
olofd/react-native-photos-framework
|
local-cli/runIOS/findMatchingSimulator.js
|
findMatchingSimulator
|
function findMatchingSimulator(simulators, simulatorName) {
if (!simulators.devices) {
return null;
}
const devices = simulators.devices;
var match;
for (let version in devices) {
// Making sure the version of the simulator is an iOS (Removes Apple Watch, etc)
if (version.indexOf('iOS') !== 0) {
continue;
}
for (let i in devices[version]) {
let simulator = devices[version][i];
// Skipping non-available simulator
if (simulator.availability !== '(available)') {
continue;
}
// If there is a booted simulator, we'll use that as instruments will not boot a second simulator
if (simulator.state === 'Booted') {
if (simulatorName !== null) {
console.warn("We couldn't boot your defined simulator due to an already booted simulator. We are limited to one simulator launched at a time.");
}
return {
udid: simulator.udid,
name: simulator.name,
version
};
}
if (simulator.name === simulatorName) {
return {
udid: simulator.udid,
name: simulator.name,
version
};
}
// Keeps track of the first available simulator for use if we can't find one above.
if (simulatorName === null && !match) {
match = {
udid: simulator.udid,
name: simulator.name,
version
};
}
}
}
if (match) {
return match;
}
return null;
}
|
javascript
|
function findMatchingSimulator(simulators, simulatorName) {
if (!simulators.devices) {
return null;
}
const devices = simulators.devices;
var match;
for (let version in devices) {
// Making sure the version of the simulator is an iOS (Removes Apple Watch, etc)
if (version.indexOf('iOS') !== 0) {
continue;
}
for (let i in devices[version]) {
let simulator = devices[version][i];
// Skipping non-available simulator
if (simulator.availability !== '(available)') {
continue;
}
// If there is a booted simulator, we'll use that as instruments will not boot a second simulator
if (simulator.state === 'Booted') {
if (simulatorName !== null) {
console.warn("We couldn't boot your defined simulator due to an already booted simulator. We are limited to one simulator launched at a time.");
}
return {
udid: simulator.udid,
name: simulator.name,
version
};
}
if (simulator.name === simulatorName) {
return {
udid: simulator.udid,
name: simulator.name,
version
};
}
// Keeps track of the first available simulator for use if we can't find one above.
if (simulatorName === null && !match) {
match = {
udid: simulator.udid,
name: simulator.name,
version
};
}
}
}
if (match) {
return match;
}
return null;
}
|
[
"function",
"findMatchingSimulator",
"(",
"simulators",
",",
"simulatorName",
")",
"{",
"if",
"(",
"!",
"simulators",
".",
"devices",
")",
"{",
"return",
"null",
";",
"}",
"const",
"devices",
"=",
"simulators",
".",
"devices",
";",
"var",
"match",
";",
"for",
"(",
"let",
"version",
"in",
"devices",
")",
"{",
"// Making sure the version of the simulator is an iOS (Removes Apple Watch, etc)",
"if",
"(",
"version",
".",
"indexOf",
"(",
"'iOS'",
")",
"!==",
"0",
")",
"{",
"continue",
";",
"}",
"for",
"(",
"let",
"i",
"in",
"devices",
"[",
"version",
"]",
")",
"{",
"let",
"simulator",
"=",
"devices",
"[",
"version",
"]",
"[",
"i",
"]",
";",
"// Skipping non-available simulator",
"if",
"(",
"simulator",
".",
"availability",
"!==",
"'(available)'",
")",
"{",
"continue",
";",
"}",
"// If there is a booted simulator, we'll use that as instruments will not boot a second simulator",
"if",
"(",
"simulator",
".",
"state",
"===",
"'Booted'",
")",
"{",
"if",
"(",
"simulatorName",
"!==",
"null",
")",
"{",
"console",
".",
"warn",
"(",
"\"We couldn't boot your defined simulator due to an already booted simulator. We are limited to one simulator launched at a time.\"",
")",
";",
"}",
"return",
"{",
"udid",
":",
"simulator",
".",
"udid",
",",
"name",
":",
"simulator",
".",
"name",
",",
"version",
"}",
";",
"}",
"if",
"(",
"simulator",
".",
"name",
"===",
"simulatorName",
")",
"{",
"return",
"{",
"udid",
":",
"simulator",
".",
"udid",
",",
"name",
":",
"simulator",
".",
"name",
",",
"version",
"}",
";",
"}",
"// Keeps track of the first available simulator for use if we can't find one above.",
"if",
"(",
"simulatorName",
"===",
"null",
"&&",
"!",
"match",
")",
"{",
"match",
"=",
"{",
"udid",
":",
"simulator",
".",
"udid",
",",
"name",
":",
"simulator",
".",
"name",
",",
"version",
"}",
";",
"}",
"}",
"}",
"if",
"(",
"match",
")",
"{",
"return",
"match",
";",
"}",
"return",
"null",
";",
"}"
] |
Takes in a parsed simulator list and a desired name, and returns an object with the matching simulator.
If the simulatorName argument is null, we'll go into default mode and return the currently booted simulator, or if
none is booted, it will be the first in the list.
@param Object simulators a parsed list from `xcrun simctl list --json devices` command
@param String|null simulatorName the string with the name of desired simulator. If null, it will use the currently
booted simulator, or if none are booted, the first in the list.
@returns {Object} {udid, name, version}
|
[
"Takes",
"in",
"a",
"parsed",
"simulator",
"list",
"and",
"a",
"desired",
"name",
"and",
"returns",
"an",
"object",
"with",
"the",
"matching",
"simulator",
"."
] |
adaa91d8bd13e93cb18c5884d9fde27228a44ebb
|
https://github.com/olofd/react-native-photos-framework/blob/adaa91d8bd13e93cb18c5884d9fde27228a44ebb/local-cli/runIOS/findMatchingSimulator.js#L22-L71
|
17,050
|
olofd/react-native-photos-framework
|
local-cli/bundle/signedsource.js
|
sign
|
function sign(file_data) {
var first_time = file_data.indexOf(TOKEN) !== -1;
if (!first_time) {
if (is_signed(file_data))
file_data = file_data.replace(PATTERN, signing_token());
else
throw exports.TokenNotFoundError;
}
var signature = md5_hash_hex(file_data, 'utf8');
var signed_data = file_data.replace(TOKEN, 'SignedSource<<'+signature+'>>');
return { first_time: first_time, signed_data: signed_data };
}
|
javascript
|
function sign(file_data) {
var first_time = file_data.indexOf(TOKEN) !== -1;
if (!first_time) {
if (is_signed(file_data))
file_data = file_data.replace(PATTERN, signing_token());
else
throw exports.TokenNotFoundError;
}
var signature = md5_hash_hex(file_data, 'utf8');
var signed_data = file_data.replace(TOKEN, 'SignedSource<<'+signature+'>>');
return { first_time: first_time, signed_data: signed_data };
}
|
[
"function",
"sign",
"(",
"file_data",
")",
"{",
"var",
"first_time",
"=",
"file_data",
".",
"indexOf",
"(",
"TOKEN",
")",
"!==",
"-",
"1",
";",
"if",
"(",
"!",
"first_time",
")",
"{",
"if",
"(",
"is_signed",
"(",
"file_data",
")",
")",
"file_data",
"=",
"file_data",
".",
"replace",
"(",
"PATTERN",
",",
"signing_token",
"(",
")",
")",
";",
"else",
"throw",
"exports",
".",
"TokenNotFoundError",
";",
"}",
"var",
"signature",
"=",
"md5_hash_hex",
"(",
"file_data",
",",
"'utf8'",
")",
";",
"var",
"signed_data",
"=",
"file_data",
".",
"replace",
"(",
"TOKEN",
",",
"'SignedSource<<'",
"+",
"signature",
"+",
"'>>'",
")",
";",
"return",
"{",
"first_time",
":",
"first_time",
",",
"signed_data",
":",
"signed_data",
"}",
";",
"}"
] |
Sign a source file which you have previously embedded a signing token into. Signing modifies only the signing token, so the semantics of the file will not change if you've put it in a comment. @param str File contents as a string (with embedded token). @return str Signed data.
|
[
"Sign",
"a",
"source",
"file",
"which",
"you",
"have",
"previously",
"embedded",
"a",
"signing",
"token",
"into",
".",
"Signing",
"modifies",
"only",
"the",
"signing",
"token",
"so",
"the",
"semantics",
"of",
"the",
"file",
"will",
"not",
"change",
"if",
"you",
"ve",
"put",
"it",
"in",
"a",
"comment",
"."
] |
adaa91d8bd13e93cb18c5884d9fde27228a44ebb
|
https://github.com/olofd/react-native-photos-framework/blob/adaa91d8bd13e93cb18c5884d9fde27228a44ebb/local-cli/bundle/signedsource.js#L59-L70
|
17,051
|
olofd/react-native-photos-framework
|
local-cli/bundle/signedsource.js
|
verify_signature
|
function verify_signature(file_data) {
var match = PATTERN.exec(file_data);
if (!match)
return exports.SIGN_UNSIGNED;
// Replace the signature with the TOKEN, then hash and see if it matches
// the value in the file. For backwards compatibility, also try with
// OLDTOKEN if that doesn't match.
var k, token, with_token, actual_md5, expected_md5 = match[1];
for (k in TOKENS) {
token = TOKENS[k];
with_token = file_data.replace(PATTERN, '@'+'generated '+token);
actual_md5 = md5_hash_hex(with_token, 'utf8');
if (expected_md5 === actual_md5)
return exports.SIGN_OK;
}
return exports.SIGN_INVALID;
}
|
javascript
|
function verify_signature(file_data) {
var match = PATTERN.exec(file_data);
if (!match)
return exports.SIGN_UNSIGNED;
// Replace the signature with the TOKEN, then hash and see if it matches
// the value in the file. For backwards compatibility, also try with
// OLDTOKEN if that doesn't match.
var k, token, with_token, actual_md5, expected_md5 = match[1];
for (k in TOKENS) {
token = TOKENS[k];
with_token = file_data.replace(PATTERN, '@'+'generated '+token);
actual_md5 = md5_hash_hex(with_token, 'utf8');
if (expected_md5 === actual_md5)
return exports.SIGN_OK;
}
return exports.SIGN_INVALID;
}
|
[
"function",
"verify_signature",
"(",
"file_data",
")",
"{",
"var",
"match",
"=",
"PATTERN",
".",
"exec",
"(",
"file_data",
")",
";",
"if",
"(",
"!",
"match",
")",
"return",
"exports",
".",
"SIGN_UNSIGNED",
";",
"// Replace the signature with the TOKEN, then hash and see if it matches",
"// the value in the file. For backwards compatibility, also try with",
"// OLDTOKEN if that doesn't match.",
"var",
"k",
",",
"token",
",",
"with_token",
",",
"actual_md5",
",",
"expected_md5",
"=",
"match",
"[",
"1",
"]",
";",
"for",
"(",
"k",
"in",
"TOKENS",
")",
"{",
"token",
"=",
"TOKENS",
"[",
"k",
"]",
";",
"with_token",
"=",
"file_data",
".",
"replace",
"(",
"PATTERN",
",",
"'@'",
"+",
"'generated '",
"+",
"token",
")",
";",
"actual_md5",
"=",
"md5_hash_hex",
"(",
"with_token",
",",
"'utf8'",
")",
";",
"if",
"(",
"expected_md5",
"===",
"actual_md5",
")",
"return",
"exports",
".",
"SIGN_OK",
";",
"}",
"return",
"exports",
".",
"SIGN_INVALID",
";",
"}"
] |
Verify a file's signature. @param str File contents as a string. @return Returns SIGN_OK if the data contains a valid signature, SIGN_UNSIGNED if it contains no signature, or SIGN_INVALID if it contains an invalid signature.
|
[
"Verify",
"a",
"file",
"s",
"signature",
"."
] |
adaa91d8bd13e93cb18c5884d9fde27228a44ebb
|
https://github.com/olofd/react-native-photos-framework/blob/adaa91d8bd13e93cb18c5884d9fde27228a44ebb/local-cli/bundle/signedsource.js#L79-L95
|
17,052
|
olofd/react-native-photos-framework
|
local-cli/server/util/copyToClipBoard.js
|
copyToClipBoard
|
function copyToClipBoard(content) {
switch (process.platform) {
case 'darwin':
var child = spawn('pbcopy', []);
child.stdin.end(new Buffer(content, 'utf8'));
return true;
default:
return false;
}
}
|
javascript
|
function copyToClipBoard(content) {
switch (process.platform) {
case 'darwin':
var child = spawn('pbcopy', []);
child.stdin.end(new Buffer(content, 'utf8'));
return true;
default:
return false;
}
}
|
[
"function",
"copyToClipBoard",
"(",
"content",
")",
"{",
"switch",
"(",
"process",
".",
"platform",
")",
"{",
"case",
"'darwin'",
":",
"var",
"child",
"=",
"spawn",
"(",
"'pbcopy'",
",",
"[",
"]",
")",
";",
"child",
".",
"stdin",
".",
"end",
"(",
"new",
"Buffer",
"(",
"content",
",",
"'utf8'",
")",
")",
";",
"return",
"true",
";",
"default",
":",
"return",
"false",
";",
"}",
"}"
] |
Copy the content to host system clipboard.
This is only supported on Mac for now.
|
[
"Copy",
"the",
"content",
"to",
"host",
"system",
"clipboard",
".",
"This",
"is",
"only",
"supported",
"on",
"Mac",
"for",
"now",
"."
] |
adaa91d8bd13e93cb18c5884d9fde27228a44ebb
|
https://github.com/olofd/react-native-photos-framework/blob/adaa91d8bd13e93cb18c5884d9fde27228a44ebb/local-cli/server/util/copyToClipBoard.js#L18-L27
|
17,053
|
olofd/react-native-photos-framework
|
local-cli/generate/generate.js
|
generate
|
function generate(argv, config) {
return new Promise((resolve, reject) => {
_generate(argv, config, resolve, reject);
});
}
|
javascript
|
function generate(argv, config) {
return new Promise((resolve, reject) => {
_generate(argv, config, resolve, reject);
});
}
|
[
"function",
"generate",
"(",
"argv",
",",
"config",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"_generate",
"(",
"argv",
",",
"config",
",",
"resolve",
",",
"reject",
")",
";",
"}",
")",
";",
"}"
] |
Generates the template for the given platform.
|
[
"Generates",
"the",
"template",
"for",
"the",
"given",
"platform",
"."
] |
adaa91d8bd13e93cb18c5884d9fde27228a44ebb
|
https://github.com/olofd/react-native-photos-framework/blob/adaa91d8bd13e93cb18c5884d9fde27228a44ebb/local-cli/generate/generate.js#L19-L23
|
17,054
|
olofd/react-native-photos-framework
|
local-cli/server/server.js
|
server
|
function server(argv, config, args) {
const roots = args.projectRoots.concat(args.root);
args.projectRoots = roots.concat(
findSymlinksPaths(NODE_MODULES, roots)
);
console.log(formatBanner(
'Running packager on port ' + args.port + '.\n\n' +
'Keep this packager running while developing on any JS projects. ' +
'Feel free to close this tab and run your own packager instance if you ' +
'prefer.\n\n' +
'https://github.com/facebook/react-native', {
marginLeft: 1,
marginRight: 1,
paddingBottom: 1,
})
);
console.log(
'Looking for JS files in\n ',
chalk.dim(args.projectRoots.join('\n ')),
'\n'
);
process.on('uncaughtException', error => {
if (error.code === 'EADDRINUSE') {
console.log(
chalk.bgRed.bold(' ERROR '),
chalk.red('Packager can\'t listen on port', chalk.bold(args.port))
);
console.log('Most likely another process is already using this port');
console.log('Run the following command to find out which process:');
console.log('\n ', chalk.bold('lsof -n -i4TCP:' + args.port), '\n');
console.log('You can either shut down the other process:');
console.log('\n ', chalk.bold('kill -9 <PID>'), '\n');
console.log('or run packager on different port.');
} else {
console.log(chalk.bgRed.bold(' ERROR '), chalk.red(error.message));
const errorAttributes = JSON.stringify(error);
if (errorAttributes !== '{}') {
console.error(chalk.red(errorAttributes));
}
console.error(chalk.red(error.stack));
}
console.log('\nSee', chalk.underline('http://facebook.github.io/react-native/docs/troubleshooting.html'));
console.log('for common problems and solutions.');
process.exit(11);
});
runServer(args, config, () => console.log('\nReact packager ready.\n'));
}
|
javascript
|
function server(argv, config, args) {
const roots = args.projectRoots.concat(args.root);
args.projectRoots = roots.concat(
findSymlinksPaths(NODE_MODULES, roots)
);
console.log(formatBanner(
'Running packager on port ' + args.port + '.\n\n' +
'Keep this packager running while developing on any JS projects. ' +
'Feel free to close this tab and run your own packager instance if you ' +
'prefer.\n\n' +
'https://github.com/facebook/react-native', {
marginLeft: 1,
marginRight: 1,
paddingBottom: 1,
})
);
console.log(
'Looking for JS files in\n ',
chalk.dim(args.projectRoots.join('\n ')),
'\n'
);
process.on('uncaughtException', error => {
if (error.code === 'EADDRINUSE') {
console.log(
chalk.bgRed.bold(' ERROR '),
chalk.red('Packager can\'t listen on port', chalk.bold(args.port))
);
console.log('Most likely another process is already using this port');
console.log('Run the following command to find out which process:');
console.log('\n ', chalk.bold('lsof -n -i4TCP:' + args.port), '\n');
console.log('You can either shut down the other process:');
console.log('\n ', chalk.bold('kill -9 <PID>'), '\n');
console.log('or run packager on different port.');
} else {
console.log(chalk.bgRed.bold(' ERROR '), chalk.red(error.message));
const errorAttributes = JSON.stringify(error);
if (errorAttributes !== '{}') {
console.error(chalk.red(errorAttributes));
}
console.error(chalk.red(error.stack));
}
console.log('\nSee', chalk.underline('http://facebook.github.io/react-native/docs/troubleshooting.html'));
console.log('for common problems and solutions.');
process.exit(11);
});
runServer(args, config, () => console.log('\nReact packager ready.\n'));
}
|
[
"function",
"server",
"(",
"argv",
",",
"config",
",",
"args",
")",
"{",
"const",
"roots",
"=",
"args",
".",
"projectRoots",
".",
"concat",
"(",
"args",
".",
"root",
")",
";",
"args",
".",
"projectRoots",
"=",
"roots",
".",
"concat",
"(",
"findSymlinksPaths",
"(",
"NODE_MODULES",
",",
"roots",
")",
")",
";",
"console",
".",
"log",
"(",
"formatBanner",
"(",
"'Running packager on port '",
"+",
"args",
".",
"port",
"+",
"'.\\n\\n'",
"+",
"'Keep this packager running while developing on any JS projects. '",
"+",
"'Feel free to close this tab and run your own packager instance if you '",
"+",
"'prefer.\\n\\n'",
"+",
"'https://github.com/facebook/react-native'",
",",
"{",
"marginLeft",
":",
"1",
",",
"marginRight",
":",
"1",
",",
"paddingBottom",
":",
"1",
",",
"}",
")",
")",
";",
"console",
".",
"log",
"(",
"'Looking for JS files in\\n '",
",",
"chalk",
".",
"dim",
"(",
"args",
".",
"projectRoots",
".",
"join",
"(",
"'\\n '",
")",
")",
",",
"'\\n'",
")",
";",
"process",
".",
"on",
"(",
"'uncaughtException'",
",",
"error",
"=>",
"{",
"if",
"(",
"error",
".",
"code",
"===",
"'EADDRINUSE'",
")",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"bgRed",
".",
"bold",
"(",
"' ERROR '",
")",
",",
"chalk",
".",
"red",
"(",
"'Packager can\\'t listen on port'",
",",
"chalk",
".",
"bold",
"(",
"args",
".",
"port",
")",
")",
")",
";",
"console",
".",
"log",
"(",
"'Most likely another process is already using this port'",
")",
";",
"console",
".",
"log",
"(",
"'Run the following command to find out which process:'",
")",
";",
"console",
".",
"log",
"(",
"'\\n '",
",",
"chalk",
".",
"bold",
"(",
"'lsof -n -i4TCP:'",
"+",
"args",
".",
"port",
")",
",",
"'\\n'",
")",
";",
"console",
".",
"log",
"(",
"'You can either shut down the other process:'",
")",
";",
"console",
".",
"log",
"(",
"'\\n '",
",",
"chalk",
".",
"bold",
"(",
"'kill -9 <PID>'",
")",
",",
"'\\n'",
")",
";",
"console",
".",
"log",
"(",
"'or run packager on different port.'",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"bgRed",
".",
"bold",
"(",
"' ERROR '",
")",
",",
"chalk",
".",
"red",
"(",
"error",
".",
"message",
")",
")",
";",
"const",
"errorAttributes",
"=",
"JSON",
".",
"stringify",
"(",
"error",
")",
";",
"if",
"(",
"errorAttributes",
"!==",
"'{}'",
")",
"{",
"console",
".",
"error",
"(",
"chalk",
".",
"red",
"(",
"errorAttributes",
")",
")",
";",
"}",
"console",
".",
"error",
"(",
"chalk",
".",
"red",
"(",
"error",
".",
"stack",
")",
")",
";",
"}",
"console",
".",
"log",
"(",
"'\\nSee'",
",",
"chalk",
".",
"underline",
"(",
"'http://facebook.github.io/react-native/docs/troubleshooting.html'",
")",
")",
";",
"console",
".",
"log",
"(",
"'for common problems and solutions.'",
")",
";",
"process",
".",
"exit",
"(",
"11",
")",
";",
"}",
")",
";",
"runServer",
"(",
"args",
",",
"config",
",",
"(",
")",
"=>",
"console",
".",
"log",
"(",
"'\\nReact packager ready.\\n'",
")",
")",
";",
"}"
] |
Starts the React Native Packager Server.
|
[
"Starts",
"the",
"React",
"Native",
"Packager",
"Server",
"."
] |
adaa91d8bd13e93cb18c5884d9fde27228a44ebb
|
https://github.com/olofd/react-native-photos-framework/blob/adaa91d8bd13e93cb18c5884d9fde27228a44ebb/local-cli/server/server.js#L21-L71
|
17,055
|
olofd/react-native-photos-framework
|
local-cli/util/Config.js
|
findParentDirectory
|
function findParentDirectory(currentFullPath, filename) {
const root = path.parse(currentFullPath).root;
const testDir = (parts) => {
if (parts.length === 0) {
return null;
}
const fullPath = path.join(root, parts.join(path.sep));
var exists = fs.existsSync(path.join(fullPath, filename));
return exists ? fullPath : testDir(parts.slice(0, -1));
};
return testDir(currentFullPath.substring(root.length).split(path.sep));
}
|
javascript
|
function findParentDirectory(currentFullPath, filename) {
const root = path.parse(currentFullPath).root;
const testDir = (parts) => {
if (parts.length === 0) {
return null;
}
const fullPath = path.join(root, parts.join(path.sep));
var exists = fs.existsSync(path.join(fullPath, filename));
return exists ? fullPath : testDir(parts.slice(0, -1));
};
return testDir(currentFullPath.substring(root.length).split(path.sep));
}
|
[
"function",
"findParentDirectory",
"(",
"currentFullPath",
",",
"filename",
")",
"{",
"const",
"root",
"=",
"path",
".",
"parse",
"(",
"currentFullPath",
")",
".",
"root",
";",
"const",
"testDir",
"=",
"(",
"parts",
")",
"=>",
"{",
"if",
"(",
"parts",
".",
"length",
"===",
"0",
")",
"{",
"return",
"null",
";",
"}",
"const",
"fullPath",
"=",
"path",
".",
"join",
"(",
"root",
",",
"parts",
".",
"join",
"(",
"path",
".",
"sep",
")",
")",
";",
"var",
"exists",
"=",
"fs",
".",
"existsSync",
"(",
"path",
".",
"join",
"(",
"fullPath",
",",
"filename",
")",
")",
";",
"return",
"exists",
"?",
"fullPath",
":",
"testDir",
"(",
"parts",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
")",
";",
"}",
";",
"return",
"testDir",
"(",
"currentFullPath",
".",
"substring",
"(",
"root",
".",
"length",
")",
".",
"split",
"(",
"path",
".",
"sep",
")",
")",
";",
"}"
] |
Finds the most near ancestor starting at `currentFullPath` that has a file named `filename`
|
[
"Finds",
"the",
"most",
"near",
"ancestor",
"starting",
"at",
"currentFullPath",
"that",
"has",
"a",
"file",
"named",
"filename"
] |
adaa91d8bd13e93cb18c5884d9fde27228a44ebb
|
https://github.com/olofd/react-native-photos-framework/blob/adaa91d8bd13e93cb18c5884d9fde27228a44ebb/local-cli/util/Config.js#L63-L77
|
17,056
|
ember-redux/ember-redux
|
addon/core.js
|
changedKeys
|
function changedKeys(props, newProps) {
return Object.keys(props).filter(key => {
return props[key] !== newProps[key];
});
}
|
javascript
|
function changedKeys(props, newProps) {
return Object.keys(props).filter(key => {
return props[key] !== newProps[key];
});
}
|
[
"function",
"changedKeys",
"(",
"props",
",",
"newProps",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"props",
")",
".",
"filter",
"(",
"key",
"=>",
"{",
"return",
"props",
"[",
"key",
"]",
"!==",
"newProps",
"[",
"key",
"]",
";",
"}",
")",
";",
"}"
] |
Returns a list of keys that have different values between the two objects.
@method changedKeys
@return {Array} keys that have changed
@private
|
[
"Returns",
"a",
"list",
"of",
"keys",
"that",
"have",
"different",
"values",
"between",
"the",
"two",
"objects",
"."
] |
6f4f643e83ded175041cf36dc2f4aee4212da518
|
https://github.com/ember-redux/ember-redux/blob/6f4f643e83ded175041cf36dc2f4aee4212da518/addon/core.js#L13-L17
|
17,057
|
ember-redux/ember-redux
|
addon/core.js
|
computedReduxProperty
|
function computedReduxProperty(key, getProps) {
return computed({
get: () => getProps()[key],
set: () => { assert(`Cannot set redux property "${key}". Try dispatching a redux action instead.`); }
});
}
|
javascript
|
function computedReduxProperty(key, getProps) {
return computed({
get: () => getProps()[key],
set: () => { assert(`Cannot set redux property "${key}". Try dispatching a redux action instead.`); }
});
}
|
[
"function",
"computedReduxProperty",
"(",
"key",
",",
"getProps",
")",
"{",
"return",
"computed",
"(",
"{",
"get",
":",
"(",
")",
"=>",
"getProps",
"(",
")",
"[",
"key",
"]",
",",
"set",
":",
"(",
")",
"=>",
"{",
"assert",
"(",
"`",
"${",
"key",
"}",
"`",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Creates a read-only computed property for accessing redux state.
@method computedReduxProperty
@return {Function} an Ember computed property
@private
|
[
"Creates",
"a",
"read",
"-",
"only",
"computed",
"property",
"for",
"accessing",
"redux",
"state",
"."
] |
6f4f643e83ded175041cf36dc2f4aee4212da518
|
https://github.com/ember-redux/ember-redux/blob/6f4f643e83ded175041cf36dc2f4aee4212da518/addon/core.js#L26-L31
|
17,058
|
ember-redux/ember-redux
|
addon/core.js
|
getAttrs
|
function getAttrs(context) {
const keys = Object.keys(context.attrs || {});
return getProperties(context, keys);
}
|
javascript
|
function getAttrs(context) {
const keys = Object.keys(context.attrs || {});
return getProperties(context, keys);
}
|
[
"function",
"getAttrs",
"(",
"context",
")",
"{",
"const",
"keys",
"=",
"Object",
".",
"keys",
"(",
"context",
".",
"attrs",
"||",
"{",
"}",
")",
";",
"return",
"getProperties",
"(",
"context",
",",
"keys",
")",
";",
"}"
] |
Return an object of attrs passed to this Component.
`Component.attrs` is an object that can look like this:
{
myAttr: {
value: 'myValue'
}
}
Ember provides that a `get` will return the value:
this.get('myAttr') === 'myValue'
@method getAttrs
@private
|
[
"Return",
"an",
"object",
"of",
"attrs",
"passed",
"to",
"this",
"Component",
"."
] |
6f4f643e83ded175041cf36dc2f4aee4212da518
|
https://github.com/ember-redux/ember-redux/blob/6f4f643e83ded175041cf36dc2f4aee4212da518/addon/core.js#L51-L54
|
17,059
|
dreyescat/bootstrap-rating
|
bootstrap-rating.js
|
function (index) {
var $rating = this.$rating;
// Get the index of the last whole symbol.
var i = Math.floor(index);
// Hide completely hidden symbols background.
$rating.find('.rating-symbol-background')
.css('visibility', 'visible')
.slice(0, i).css('visibility', 'hidden');
var $rates = $rating.find('.rating-symbol-foreground');
// Reset foreground
$rates.width(0);
// Fill all the foreground symbols up to the selected one.
$rates.slice(0, i).width('auto')
.find('span').attr('class', this.options.filled);
// Amend selected symbol.
$rates.eq(index % 1 ? i : i - 1)
.find('span').attr('class', this.options.filledSelected);
// Partially fill the fractional one.
$rates.eq(i).width(index % 1 * 100 + '%');
}
|
javascript
|
function (index) {
var $rating = this.$rating;
// Get the index of the last whole symbol.
var i = Math.floor(index);
// Hide completely hidden symbols background.
$rating.find('.rating-symbol-background')
.css('visibility', 'visible')
.slice(0, i).css('visibility', 'hidden');
var $rates = $rating.find('.rating-symbol-foreground');
// Reset foreground
$rates.width(0);
// Fill all the foreground symbols up to the selected one.
$rates.slice(0, i).width('auto')
.find('span').attr('class', this.options.filled);
// Amend selected symbol.
$rates.eq(index % 1 ? i : i - 1)
.find('span').attr('class', this.options.filledSelected);
// Partially fill the fractional one.
$rates.eq(i).width(index % 1 * 100 + '%');
}
|
[
"function",
"(",
"index",
")",
"{",
"var",
"$rating",
"=",
"this",
".",
"$rating",
";",
"// Get the index of the last whole symbol.",
"var",
"i",
"=",
"Math",
".",
"floor",
"(",
"index",
")",
";",
"// Hide completely hidden symbols background.",
"$rating",
".",
"find",
"(",
"'.rating-symbol-background'",
")",
".",
"css",
"(",
"'visibility'",
",",
"'visible'",
")",
".",
"slice",
"(",
"0",
",",
"i",
")",
".",
"css",
"(",
"'visibility'",
",",
"'hidden'",
")",
";",
"var",
"$rates",
"=",
"$rating",
".",
"find",
"(",
"'.rating-symbol-foreground'",
")",
";",
"// Reset foreground",
"$rates",
".",
"width",
"(",
"0",
")",
";",
"// Fill all the foreground symbols up to the selected one.",
"$rates",
".",
"slice",
"(",
"0",
",",
"i",
")",
".",
"width",
"(",
"'auto'",
")",
".",
"find",
"(",
"'span'",
")",
".",
"attr",
"(",
"'class'",
",",
"this",
".",
"options",
".",
"filled",
")",
";",
"// Amend selected symbol.",
"$rates",
".",
"eq",
"(",
"index",
"%",
"1",
"?",
"i",
":",
"i",
"-",
"1",
")",
".",
"find",
"(",
"'span'",
")",
".",
"attr",
"(",
"'class'",
",",
"this",
".",
"options",
".",
"filledSelected",
")",
";",
"// Partially fill the fractional one.",
"$rates",
".",
"eq",
"(",
"i",
")",
".",
"width",
"(",
"index",
"%",
"1",
"*",
"100",
"+",
"'%'",
")",
";",
"}"
] |
Fill rating symbols until index.
|
[
"Fill",
"rating",
"symbols",
"until",
"index",
"."
] |
af10cba7c9e27ae891ae4e517b8e828f2eb23c10
|
https://github.com/dreyescat/bootstrap-rating/blob/af10cba7c9e27ae891ae4e517b8e828f2eb23c10/bootstrap-rating.js#L152-L171
|
|
17,060
|
dreyescat/bootstrap-rating
|
bootstrap-rating.js
|
function (index) {
return this.options.start + Math.floor(index) * this.options.step +
this.options.step * this._roundToFraction(index % 1);
}
|
javascript
|
function (index) {
return this.options.start + Math.floor(index) * this.options.step +
this.options.step * this._roundToFraction(index % 1);
}
|
[
"function",
"(",
"index",
")",
"{",
"return",
"this",
".",
"options",
".",
"start",
"+",
"Math",
".",
"floor",
"(",
"index",
")",
"*",
"this",
".",
"options",
".",
"step",
"+",
"this",
".",
"options",
".",
"step",
"*",
"this",
".",
"_roundToFraction",
"(",
"index",
"%",
"1",
")",
";",
"}"
] |
Calculate the rate of an index according the the start and step.
|
[
"Calculate",
"the",
"rate",
"of",
"an",
"index",
"according",
"the",
"the",
"start",
"and",
"step",
"."
] |
af10cba7c9e27ae891ae4e517b8e828f2eb23c10
|
https://github.com/dreyescat/bootstrap-rating/blob/af10cba7c9e27ae891ae4e517b8e828f2eb23c10/bootstrap-rating.js#L173-L176
|
|
17,061
|
dreyescat/bootstrap-rating
|
bootstrap-rating.js
|
function (index) {
// Get the closest top fraction.
var fraction = Math.ceil(index % 1 * this.options.fractions) / this.options.fractions;
// Truncate decimal trying to avoid float precission issues.
var p = Math.pow(10, this.options.scale);
return Math.floor(index) + Math.floor(fraction * p) / p;
}
|
javascript
|
function (index) {
// Get the closest top fraction.
var fraction = Math.ceil(index % 1 * this.options.fractions) / this.options.fractions;
// Truncate decimal trying to avoid float precission issues.
var p = Math.pow(10, this.options.scale);
return Math.floor(index) + Math.floor(fraction * p) / p;
}
|
[
"function",
"(",
"index",
")",
"{",
"// Get the closest top fraction.",
"var",
"fraction",
"=",
"Math",
".",
"ceil",
"(",
"index",
"%",
"1",
"*",
"this",
".",
"options",
".",
"fractions",
")",
"/",
"this",
".",
"options",
".",
"fractions",
";",
"// Truncate decimal trying to avoid float precission issues.",
"var",
"p",
"=",
"Math",
".",
"pow",
"(",
"10",
",",
"this",
".",
"options",
".",
"scale",
")",
";",
"return",
"Math",
".",
"floor",
"(",
"index",
")",
"+",
"Math",
".",
"floor",
"(",
"fraction",
"*",
"p",
")",
"/",
"p",
";",
"}"
] |
Round index to the configured opts.fractions.
|
[
"Round",
"index",
"to",
"the",
"configured",
"opts",
".",
"fractions",
"."
] |
af10cba7c9e27ae891ae4e517b8e828f2eb23c10
|
https://github.com/dreyescat/bootstrap-rating/blob/af10cba7c9e27ae891ae4e517b8e828f2eb23c10/bootstrap-rating.js#L182-L188
|
|
17,062
|
dreyescat/bootstrap-rating
|
bootstrap-rating.js
|
function (rate) {
var value = parseFloat(rate);
if (this._contains(value)) {
this._fillUntil(this._rateToIndex(value));
this.$input.val(value);
} else if (rate === '') {
this._fillUntil(0);
this.$input.val('');
}
}
|
javascript
|
function (rate) {
var value = parseFloat(rate);
if (this._contains(value)) {
this._fillUntil(this._rateToIndex(value));
this.$input.val(value);
} else if (rate === '') {
this._fillUntil(0);
this.$input.val('');
}
}
|
[
"function",
"(",
"rate",
")",
"{",
"var",
"value",
"=",
"parseFloat",
"(",
"rate",
")",
";",
"if",
"(",
"this",
".",
"_contains",
"(",
"value",
")",
")",
"{",
"this",
".",
"_fillUntil",
"(",
"this",
".",
"_rateToIndex",
"(",
"value",
")",
")",
";",
"this",
".",
"$input",
".",
"val",
"(",
"value",
")",
";",
"}",
"else",
"if",
"(",
"rate",
"===",
"''",
")",
"{",
"this",
".",
"_fillUntil",
"(",
"0",
")",
";",
"this",
".",
"$input",
".",
"val",
"(",
"''",
")",
";",
"}",
"}"
] |
Update empty and filled rating symbols according to a rate.
|
[
"Update",
"empty",
"and",
"filled",
"rating",
"symbols",
"according",
"to",
"a",
"rate",
"."
] |
af10cba7c9e27ae891ae4e517b8e828f2eb23c10
|
https://github.com/dreyescat/bootstrap-rating/blob/af10cba7c9e27ae891ae4e517b8e828f2eb23c10/bootstrap-rating.js#L196-L205
|
|
17,063
|
wikimedia/restbase
|
sys/parsoid.js
|
isModifiedSince
|
function isModifiedSince(req, res) {
try {
if (req.headers['if-unmodified-since']) {
const jobTime = Date.parse(req.headers['if-unmodified-since']);
const revInfo = mwUtil.parseETag(res.headers.etag);
return revInfo && uuid.fromString(revInfo.tid).getDate() >= jobTime;
}
} catch (e) {
// Ignore errors from date parsing
}
return false;
}
|
javascript
|
function isModifiedSince(req, res) {
try {
if (req.headers['if-unmodified-since']) {
const jobTime = Date.parse(req.headers['if-unmodified-since']);
const revInfo = mwUtil.parseETag(res.headers.etag);
return revInfo && uuid.fromString(revInfo.tid).getDate() >= jobTime;
}
} catch (e) {
// Ignore errors from date parsing
}
return false;
}
|
[
"function",
"isModifiedSince",
"(",
"req",
",",
"res",
")",
"{",
"try",
"{",
"if",
"(",
"req",
".",
"headers",
"[",
"'if-unmodified-since'",
"]",
")",
"{",
"const",
"jobTime",
"=",
"Date",
".",
"parse",
"(",
"req",
".",
"headers",
"[",
"'if-unmodified-since'",
"]",
")",
";",
"const",
"revInfo",
"=",
"mwUtil",
".",
"parseETag",
"(",
"res",
".",
"headers",
".",
"etag",
")",
";",
"return",
"revInfo",
"&&",
"uuid",
".",
"fromString",
"(",
"revInfo",
".",
"tid",
")",
".",
"getDate",
"(",
")",
">=",
"jobTime",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"// Ignore errors from date parsing",
"}",
"return",
"false",
";",
"}"
] |
Checks whether the content has been modified since the timestamp
in `if-unmodified-since` header of the request
@param {Object} req the request
@param {Object} res the response
@return {boolean} true if content has beed modified
|
[
"Checks",
"whether",
"the",
"content",
"has",
"been",
"modified",
"since",
"the",
"timestamp",
"in",
"if",
"-",
"unmodified",
"-",
"since",
"header",
"of",
"the",
"request"
] |
91b5176b7d5d38a7c4d3fa9c31f297f9737c3fcb
|
https://github.com/wikimedia/restbase/blob/91b5176b7d5d38a7c4d3fa9c31f297f9737c3fcb/sys/parsoid.js#L57-L68
|
17,064
|
wikimedia/restbase
|
sys/parsoid.js
|
_dependenciesUpdate
|
function _dependenciesUpdate(hyper, req, newContent = true) {
const rp = req.params;
return mwUtil.getSiteInfo(hyper, req)
.then((siteInfo) => {
const baseUri = siteInfo.baseUri.replace(/^https?:/, '');
const publicURI = `${baseUri}/page/html/${encodeURIComponent(rp.title)}`;
const body = [ { meta: { uri: `${publicURI}/${rp.revision}` } } ];
if (newContent) {
body.push({ meta: { uri: publicURI } });
}
return hyper.post({
uri: new URI([rp.domain, 'sys', 'events', '']),
body
}).catch((e) => {
hyper.logger.log('warn/bg-updates', e);
});
});
}
|
javascript
|
function _dependenciesUpdate(hyper, req, newContent = true) {
const rp = req.params;
return mwUtil.getSiteInfo(hyper, req)
.then((siteInfo) => {
const baseUri = siteInfo.baseUri.replace(/^https?:/, '');
const publicURI = `${baseUri}/page/html/${encodeURIComponent(rp.title)}`;
const body = [ { meta: { uri: `${publicURI}/${rp.revision}` } } ];
if (newContent) {
body.push({ meta: { uri: publicURI } });
}
return hyper.post({
uri: new URI([rp.domain, 'sys', 'events', '']),
body
}).catch((e) => {
hyper.logger.log('warn/bg-updates', e);
});
});
}
|
[
"function",
"_dependenciesUpdate",
"(",
"hyper",
",",
"req",
",",
"newContent",
"=",
"true",
")",
"{",
"const",
"rp",
"=",
"req",
".",
"params",
";",
"return",
"mwUtil",
".",
"getSiteInfo",
"(",
"hyper",
",",
"req",
")",
".",
"then",
"(",
"(",
"siteInfo",
")",
"=>",
"{",
"const",
"baseUri",
"=",
"siteInfo",
".",
"baseUri",
".",
"replace",
"(",
"/",
"^https?:",
"/",
",",
"''",
")",
";",
"const",
"publicURI",
"=",
"`",
"${",
"baseUri",
"}",
"${",
"encodeURIComponent",
"(",
"rp",
".",
"title",
")",
"}",
"`",
";",
"const",
"body",
"=",
"[",
"{",
"meta",
":",
"{",
"uri",
":",
"`",
"${",
"publicURI",
"}",
"${",
"rp",
".",
"revision",
"}",
"`",
"}",
"}",
"]",
";",
"if",
"(",
"newContent",
")",
"{",
"body",
".",
"push",
"(",
"{",
"meta",
":",
"{",
"uri",
":",
"publicURI",
"}",
"}",
")",
";",
"}",
"return",
"hyper",
".",
"post",
"(",
"{",
"uri",
":",
"new",
"URI",
"(",
"[",
"rp",
".",
"domain",
",",
"'sys'",
",",
"'events'",
",",
"''",
"]",
")",
",",
"body",
"}",
")",
".",
"catch",
"(",
"(",
"e",
")",
"=>",
"{",
"hyper",
".",
"logger",
".",
"log",
"(",
"'warn/bg-updates'",
",",
"e",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
HTML resource_change event emission
@param {HyperSwitch} hyper the hyperswitch router object
@param {Object} req the request
@param {boolean} [newContent] whether this is the newest revision
@return {Object} update response
|
[
"HTML",
"resource_change",
"event",
"emission"
] |
91b5176b7d5d38a7c4d3fa9c31f297f9737c3fcb
|
https://github.com/wikimedia/restbase/blob/91b5176b7d5d38a7c4d3fa9c31f297f9737c3fcb/sys/parsoid.js#L76-L93
|
17,065
|
wikimedia/restbase
|
lib/ensure_content_type.js
|
checkContentType
|
function checkContentType(hyper, req, next, expectedContentType, responsePromise) {
return responsePromise
.then((res) => {
// Do not check or re-render if the response was only rendered within
// the last two minutes.
if (res.headers && res.headers.etag &&
Date.now() - mwUtil.extractDateFromEtag(res.headers.etag) < 120000) {
return res;
}
if (res.headers && res.headers === undefined) {
delete res.headers['content-type'];
}
if (res.headers &&
res.headers['content-type'] &&
res.headers['content-type'] !== expectedContentType) {
// Parse the expected & response content type, and compare profiles.
const expectedProfile = cType.parse(expectedContentType).parameters.profile;
const actualProfile = cType.parse(res.headers['content-type']).parameters.profile;
if (actualProfile && actualProfile !== expectedProfile) {
if (!expectedProfile) {
return res;
}
// Check if actual content type is newer than the spec
const actualProfileParts = splitProfile(actualProfile);
const expectedProfileParts = splitProfile(expectedProfile);
if (actualProfileParts.path === expectedProfileParts.path &&
semver.gt(actualProfileParts.version, expectedProfileParts.version)) {
return res;
}
}
// Re-try request with no-cache header
if (!mwUtil.isNoCacheRequest(req)) {
req.headers['cache-control'] = 'no-cache';
return checkContentType(hyper, req, next, expectedContentType, next(hyper, req));
} else {
// Log issue
hyper.logger.log('warn/content-type/upgrade_failed', {
msg: 'Could not update the content-type',
expected: expectedContentType,
actual: res.headers['content-type']
});
// Disable response caching, as we aren't setting a vary
// either.
res.headers['cache-control'] = 'max-age=0, s-maxage=0';
}
}
// Default: Just return.
return res;
});
}
|
javascript
|
function checkContentType(hyper, req, next, expectedContentType, responsePromise) {
return responsePromise
.then((res) => {
// Do not check or re-render if the response was only rendered within
// the last two minutes.
if (res.headers && res.headers.etag &&
Date.now() - mwUtil.extractDateFromEtag(res.headers.etag) < 120000) {
return res;
}
if (res.headers && res.headers === undefined) {
delete res.headers['content-type'];
}
if (res.headers &&
res.headers['content-type'] &&
res.headers['content-type'] !== expectedContentType) {
// Parse the expected & response content type, and compare profiles.
const expectedProfile = cType.parse(expectedContentType).parameters.profile;
const actualProfile = cType.parse(res.headers['content-type']).parameters.profile;
if (actualProfile && actualProfile !== expectedProfile) {
if (!expectedProfile) {
return res;
}
// Check if actual content type is newer than the spec
const actualProfileParts = splitProfile(actualProfile);
const expectedProfileParts = splitProfile(expectedProfile);
if (actualProfileParts.path === expectedProfileParts.path &&
semver.gt(actualProfileParts.version, expectedProfileParts.version)) {
return res;
}
}
// Re-try request with no-cache header
if (!mwUtil.isNoCacheRequest(req)) {
req.headers['cache-control'] = 'no-cache';
return checkContentType(hyper, req, next, expectedContentType, next(hyper, req));
} else {
// Log issue
hyper.logger.log('warn/content-type/upgrade_failed', {
msg: 'Could not update the content-type',
expected: expectedContentType,
actual: res.headers['content-type']
});
// Disable response caching, as we aren't setting a vary
// either.
res.headers['cache-control'] = 'max-age=0, s-maxage=0';
}
}
// Default: Just return.
return res;
});
}
|
[
"function",
"checkContentType",
"(",
"hyper",
",",
"req",
",",
"next",
",",
"expectedContentType",
",",
"responsePromise",
")",
"{",
"return",
"responsePromise",
".",
"then",
"(",
"(",
"res",
")",
"=>",
"{",
"// Do not check or re-render if the response was only rendered within",
"// the last two minutes.",
"if",
"(",
"res",
".",
"headers",
"&&",
"res",
".",
"headers",
".",
"etag",
"&&",
"Date",
".",
"now",
"(",
")",
"-",
"mwUtil",
".",
"extractDateFromEtag",
"(",
"res",
".",
"headers",
".",
"etag",
")",
"<",
"120000",
")",
"{",
"return",
"res",
";",
"}",
"if",
"(",
"res",
".",
"headers",
"&&",
"res",
".",
"headers",
"===",
"undefined",
")",
"{",
"delete",
"res",
".",
"headers",
"[",
"'content-type'",
"]",
";",
"}",
"if",
"(",
"res",
".",
"headers",
"&&",
"res",
".",
"headers",
"[",
"'content-type'",
"]",
"&&",
"res",
".",
"headers",
"[",
"'content-type'",
"]",
"!==",
"expectedContentType",
")",
"{",
"// Parse the expected & response content type, and compare profiles.",
"const",
"expectedProfile",
"=",
"cType",
".",
"parse",
"(",
"expectedContentType",
")",
".",
"parameters",
".",
"profile",
";",
"const",
"actualProfile",
"=",
"cType",
".",
"parse",
"(",
"res",
".",
"headers",
"[",
"'content-type'",
"]",
")",
".",
"parameters",
".",
"profile",
";",
"if",
"(",
"actualProfile",
"&&",
"actualProfile",
"!==",
"expectedProfile",
")",
"{",
"if",
"(",
"!",
"expectedProfile",
")",
"{",
"return",
"res",
";",
"}",
"// Check if actual content type is newer than the spec",
"const",
"actualProfileParts",
"=",
"splitProfile",
"(",
"actualProfile",
")",
";",
"const",
"expectedProfileParts",
"=",
"splitProfile",
"(",
"expectedProfile",
")",
";",
"if",
"(",
"actualProfileParts",
".",
"path",
"===",
"expectedProfileParts",
".",
"path",
"&&",
"semver",
".",
"gt",
"(",
"actualProfileParts",
".",
"version",
",",
"expectedProfileParts",
".",
"version",
")",
")",
"{",
"return",
"res",
";",
"}",
"}",
"// Re-try request with no-cache header",
"if",
"(",
"!",
"mwUtil",
".",
"isNoCacheRequest",
"(",
"req",
")",
")",
"{",
"req",
".",
"headers",
"[",
"'cache-control'",
"]",
"=",
"'no-cache'",
";",
"return",
"checkContentType",
"(",
"hyper",
",",
"req",
",",
"next",
",",
"expectedContentType",
",",
"next",
"(",
"hyper",
",",
"req",
")",
")",
";",
"}",
"else",
"{",
"// Log issue",
"hyper",
".",
"logger",
".",
"log",
"(",
"'warn/content-type/upgrade_failed'",
",",
"{",
"msg",
":",
"'Could not update the content-type'",
",",
"expected",
":",
"expectedContentType",
",",
"actual",
":",
"res",
".",
"headers",
"[",
"'content-type'",
"]",
"}",
")",
";",
"// Disable response caching, as we aren't setting a vary",
"// either.",
"res",
".",
"headers",
"[",
"'cache-control'",
"]",
"=",
"'max-age=0, s-maxage=0'",
";",
"}",
"}",
"// Default: Just return.",
"return",
"res",
";",
"}",
")",
";",
"}"
] |
Simple content type enforcement
- Assumes that the first `produces` array entry is the latest.
- Repeats request with `no-cache` header set if the content-type does not
match the latest version.
|
[
"Simple",
"content",
"type",
"enforcement"
] |
91b5176b7d5d38a7c4d3fa9c31f297f9737c3fcb
|
https://github.com/wikimedia/restbase/blob/91b5176b7d5d38a7c4d3fa9c31f297f9737c3fcb/lib/ensure_content_type.js#L25-L78
|
17,066
|
ioBroker/ioBroker.socketio
|
lib/socket.js
|
getUserFromSocket
|
function getUserFromSocket(socket, callback) {
let wait = false;
try {
if (socket.handshake.headers.cookie && (!socket.request || !socket.request._query || !socket.request._query.user)) {
let cookie = decodeURIComponent(socket.handshake.headers.cookie);
let m = cookie.match(/connect\.sid=(.+)/);
if (m) {
// If session cookie exists
let c = m[1].split(';')[0];
let sessionID = cookieParser.signedCookie(c, that.settings.secret);
if (sessionID) {
// Get user for session
wait = true;
that.settings.store.get(sessionID, function (err, obj) {
if (obj && obj.passport && obj.passport.user) {
socket._sessionID = sessionID;
if (typeof callback === 'function') {
callback(null, obj.passport.user);
} else {
that.adapter.log.warn('[getUserFromSocket] Invalid callback')
}
} else {
if (typeof callback === 'function') {
callback('unknown user');
} else {
that.adapter.log.warn('[getUserFromSocket] Invalid callback')
}
}
});
}
}
}
if (!wait) {
let user = socket.request._query.user;
let pass = socket.request._query.pass;
if (user && pass) {
wait = true;
that.adapter.checkPassword(user, pass, function (res) {
if (res) {
that.adapter.log.debug('Logged in: ' + user);
if (typeof callback === 'function') {
callback(null, user);
} else {
that.adapter.log.warn('[getUserFromSocket] Invalid callback')
}
} else {
that.adapter.log.warn('Invalid password or user name: ' + user + ', ' + pass[0] + '***(' + pass.length + ')');
if (typeof callback === 'function') {
callback('unknown user');
} else {
that.adapter.log.warn('[getUserFromSocket] Invalid callback')
}
}
});
}
}
} catch (e) {
that.adapter.log.error(e);
wait = false;
}
if (!wait && typeof callback === 'function') {
callback('Cannot detect user');
}
}
|
javascript
|
function getUserFromSocket(socket, callback) {
let wait = false;
try {
if (socket.handshake.headers.cookie && (!socket.request || !socket.request._query || !socket.request._query.user)) {
let cookie = decodeURIComponent(socket.handshake.headers.cookie);
let m = cookie.match(/connect\.sid=(.+)/);
if (m) {
// If session cookie exists
let c = m[1].split(';')[0];
let sessionID = cookieParser.signedCookie(c, that.settings.secret);
if (sessionID) {
// Get user for session
wait = true;
that.settings.store.get(sessionID, function (err, obj) {
if (obj && obj.passport && obj.passport.user) {
socket._sessionID = sessionID;
if (typeof callback === 'function') {
callback(null, obj.passport.user);
} else {
that.adapter.log.warn('[getUserFromSocket] Invalid callback')
}
} else {
if (typeof callback === 'function') {
callback('unknown user');
} else {
that.adapter.log.warn('[getUserFromSocket] Invalid callback')
}
}
});
}
}
}
if (!wait) {
let user = socket.request._query.user;
let pass = socket.request._query.pass;
if (user && pass) {
wait = true;
that.adapter.checkPassword(user, pass, function (res) {
if (res) {
that.adapter.log.debug('Logged in: ' + user);
if (typeof callback === 'function') {
callback(null, user);
} else {
that.adapter.log.warn('[getUserFromSocket] Invalid callback')
}
} else {
that.adapter.log.warn('Invalid password or user name: ' + user + ', ' + pass[0] + '***(' + pass.length + ')');
if (typeof callback === 'function') {
callback('unknown user');
} else {
that.adapter.log.warn('[getUserFromSocket] Invalid callback')
}
}
});
}
}
} catch (e) {
that.adapter.log.error(e);
wait = false;
}
if (!wait && typeof callback === 'function') {
callback('Cannot detect user');
}
}
|
[
"function",
"getUserFromSocket",
"(",
"socket",
",",
"callback",
")",
"{",
"let",
"wait",
"=",
"false",
";",
"try",
"{",
"if",
"(",
"socket",
".",
"handshake",
".",
"headers",
".",
"cookie",
"&&",
"(",
"!",
"socket",
".",
"request",
"||",
"!",
"socket",
".",
"request",
".",
"_query",
"||",
"!",
"socket",
".",
"request",
".",
"_query",
".",
"user",
")",
")",
"{",
"let",
"cookie",
"=",
"decodeURIComponent",
"(",
"socket",
".",
"handshake",
".",
"headers",
".",
"cookie",
")",
";",
"let",
"m",
"=",
"cookie",
".",
"match",
"(",
"/",
"connect\\.sid=(.+)",
"/",
")",
";",
"if",
"(",
"m",
")",
"{",
"// If session cookie exists\r",
"let",
"c",
"=",
"m",
"[",
"1",
"]",
".",
"split",
"(",
"';'",
")",
"[",
"0",
"]",
";",
"let",
"sessionID",
"=",
"cookieParser",
".",
"signedCookie",
"(",
"c",
",",
"that",
".",
"settings",
".",
"secret",
")",
";",
"if",
"(",
"sessionID",
")",
"{",
"// Get user for session\r",
"wait",
"=",
"true",
";",
"that",
".",
"settings",
".",
"store",
".",
"get",
"(",
"sessionID",
",",
"function",
"(",
"err",
",",
"obj",
")",
"{",
"if",
"(",
"obj",
"&&",
"obj",
".",
"passport",
"&&",
"obj",
".",
"passport",
".",
"user",
")",
"{",
"socket",
".",
"_sessionID",
"=",
"sessionID",
";",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"callback",
"(",
"null",
",",
"obj",
".",
"passport",
".",
"user",
")",
";",
"}",
"else",
"{",
"that",
".",
"adapter",
".",
"log",
".",
"warn",
"(",
"'[getUserFromSocket] Invalid callback'",
")",
"}",
"}",
"else",
"{",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"callback",
"(",
"'unknown user'",
")",
";",
"}",
"else",
"{",
"that",
".",
"adapter",
".",
"log",
".",
"warn",
"(",
"'[getUserFromSocket] Invalid callback'",
")",
"}",
"}",
"}",
")",
";",
"}",
"}",
"}",
"if",
"(",
"!",
"wait",
")",
"{",
"let",
"user",
"=",
"socket",
".",
"request",
".",
"_query",
".",
"user",
";",
"let",
"pass",
"=",
"socket",
".",
"request",
".",
"_query",
".",
"pass",
";",
"if",
"(",
"user",
"&&",
"pass",
")",
"{",
"wait",
"=",
"true",
";",
"that",
".",
"adapter",
".",
"checkPassword",
"(",
"user",
",",
"pass",
",",
"function",
"(",
"res",
")",
"{",
"if",
"(",
"res",
")",
"{",
"that",
".",
"adapter",
".",
"log",
".",
"debug",
"(",
"'Logged in: '",
"+",
"user",
")",
";",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"callback",
"(",
"null",
",",
"user",
")",
";",
"}",
"else",
"{",
"that",
".",
"adapter",
".",
"log",
".",
"warn",
"(",
"'[getUserFromSocket] Invalid callback'",
")",
"}",
"}",
"else",
"{",
"that",
".",
"adapter",
".",
"log",
".",
"warn",
"(",
"'Invalid password or user name: '",
"+",
"user",
"+",
"', '",
"+",
"pass",
"[",
"0",
"]",
"+",
"'***('",
"+",
"pass",
".",
"length",
"+",
"')'",
")",
";",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"callback",
"(",
"'unknown user'",
")",
";",
"}",
"else",
"{",
"that",
".",
"adapter",
".",
"log",
".",
"warn",
"(",
"'[getUserFromSocket] Invalid callback'",
")",
"}",
"}",
"}",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"that",
".",
"adapter",
".",
"log",
".",
"error",
"(",
"e",
")",
";",
"wait",
"=",
"false",
";",
"}",
"if",
"(",
"!",
"wait",
"&&",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"callback",
"(",
"'Cannot detect user'",
")",
";",
"}",
"}"
] |
Extract user name from socket
|
[
"Extract",
"user",
"name",
"from",
"socket"
] |
40d46b71d7341e00b796e85aa80a02941cd7f93f
|
https://github.com/ioBroker/ioBroker.socketio/blob/40d46b71d7341e00b796e85aa80a02941cd7f93f/lib/socket.js#L37-L100
|
17,067
|
ioBroker/ioBroker.socketio
|
lib/socket.js
|
updateSession
|
function updateSession(socket) {
if (socket._sessionID) {
let time = (new Date()).getTime();
if (socket._lastActivity && time - socket._lastActivity > settings.ttl * 1000) {
socket.emit('reauthenticate');
socket.disconnect();
return false;
}
socket._lastActivity = time;
if (!socket._sessionTimer) {
socket._sessionTimer = setTimeout(function () {
socket._sessionTimer = null;
that.settings.store.get(socket._sessionID, function (err, obj) {
if (obj) {
that.adapter.setSession(socket._sessionID, settings.ttl, obj);
} else {
socket.emit('reauthenticate');
socket.disconnect();
}
});
}, 60000);
}
}
return true;
}
|
javascript
|
function updateSession(socket) {
if (socket._sessionID) {
let time = (new Date()).getTime();
if (socket._lastActivity && time - socket._lastActivity > settings.ttl * 1000) {
socket.emit('reauthenticate');
socket.disconnect();
return false;
}
socket._lastActivity = time;
if (!socket._sessionTimer) {
socket._sessionTimer = setTimeout(function () {
socket._sessionTimer = null;
that.settings.store.get(socket._sessionID, function (err, obj) {
if (obj) {
that.adapter.setSession(socket._sessionID, settings.ttl, obj);
} else {
socket.emit('reauthenticate');
socket.disconnect();
}
});
}, 60000);
}
}
return true;
}
|
[
"function",
"updateSession",
"(",
"socket",
")",
"{",
"if",
"(",
"socket",
".",
"_sessionID",
")",
"{",
"let",
"time",
"=",
"(",
"new",
"Date",
"(",
")",
")",
".",
"getTime",
"(",
")",
";",
"if",
"(",
"socket",
".",
"_lastActivity",
"&&",
"time",
"-",
"socket",
".",
"_lastActivity",
">",
"settings",
".",
"ttl",
"*",
"1000",
")",
"{",
"socket",
".",
"emit",
"(",
"'reauthenticate'",
")",
";",
"socket",
".",
"disconnect",
"(",
")",
";",
"return",
"false",
";",
"}",
"socket",
".",
"_lastActivity",
"=",
"time",
";",
"if",
"(",
"!",
"socket",
".",
"_sessionTimer",
")",
"{",
"socket",
".",
"_sessionTimer",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"socket",
".",
"_sessionTimer",
"=",
"null",
";",
"that",
".",
"settings",
".",
"store",
".",
"get",
"(",
"socket",
".",
"_sessionID",
",",
"function",
"(",
"err",
",",
"obj",
")",
"{",
"if",
"(",
"obj",
")",
"{",
"that",
".",
"adapter",
".",
"setSession",
"(",
"socket",
".",
"_sessionID",
",",
"settings",
".",
"ttl",
",",
"obj",
")",
";",
"}",
"else",
"{",
"socket",
".",
"emit",
"(",
"'reauthenticate'",
")",
";",
"socket",
".",
"disconnect",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"60000",
")",
";",
"}",
"}",
"return",
"true",
";",
"}"
] |
update session ID, but not ofter than 60 seconds
|
[
"update",
"session",
"ID",
"but",
"not",
"ofter",
"than",
"60",
"seconds"
] |
40d46b71d7341e00b796e85aa80a02941cd7f93f
|
https://github.com/ioBroker/ioBroker.socketio/blob/40d46b71d7341e00b796e85aa80a02941cd7f93f/lib/socket.js#L470-L494
|
17,068
|
rtfeldman/node-test-runner
|
lib/runner.js
|
verifyModules
|
function verifyModules(filePaths) {
return Promise.all(
_.map(filePaths, function(filePath) {
return firstline(filePath).then(function(line) {
var matches = line.match(/^(?:(?:port|effect)\s+)?module\s+(\S+)\s*/);
if (matches) {
var moduleName = matches[1];
var testModulePaths = moduleFromTestName(moduleName);
var modulePath = moduleFromFilePath(filePath);
// A module path matches if it lines up completely with a known one.
if (
!testModulePaths.every(function(testModulePath, index) {
return testModulePath === modulePath[index];
})
) {
return Promise.reject(
filePath +
' has a module declaration of "' +
moduleName +
'" - which does not match its filename!'
);
}
} else {
return Promise.reject(
filePath +
' has an invalid module declaration. Check the first line of the file and make sure it has a valid module declaration there!'
);
}
});
})
);
}
|
javascript
|
function verifyModules(filePaths) {
return Promise.all(
_.map(filePaths, function(filePath) {
return firstline(filePath).then(function(line) {
var matches = line.match(/^(?:(?:port|effect)\s+)?module\s+(\S+)\s*/);
if (matches) {
var moduleName = matches[1];
var testModulePaths = moduleFromTestName(moduleName);
var modulePath = moduleFromFilePath(filePath);
// A module path matches if it lines up completely with a known one.
if (
!testModulePaths.every(function(testModulePath, index) {
return testModulePath === modulePath[index];
})
) {
return Promise.reject(
filePath +
' has a module declaration of "' +
moduleName +
'" - which does not match its filename!'
);
}
} else {
return Promise.reject(
filePath +
' has an invalid module declaration. Check the first line of the file and make sure it has a valid module declaration there!'
);
}
});
})
);
}
|
[
"function",
"verifyModules",
"(",
"filePaths",
")",
"{",
"return",
"Promise",
".",
"all",
"(",
"_",
".",
"map",
"(",
"filePaths",
",",
"function",
"(",
"filePath",
")",
"{",
"return",
"firstline",
"(",
"filePath",
")",
".",
"then",
"(",
"function",
"(",
"line",
")",
"{",
"var",
"matches",
"=",
"line",
".",
"match",
"(",
"/",
"^(?:(?:port|effect)\\s+)?module\\s+(\\S+)\\s*",
"/",
")",
";",
"if",
"(",
"matches",
")",
"{",
"var",
"moduleName",
"=",
"matches",
"[",
"1",
"]",
";",
"var",
"testModulePaths",
"=",
"moduleFromTestName",
"(",
"moduleName",
")",
";",
"var",
"modulePath",
"=",
"moduleFromFilePath",
"(",
"filePath",
")",
";",
"// A module path matches if it lines up completely with a known one.",
"if",
"(",
"!",
"testModulePaths",
".",
"every",
"(",
"function",
"(",
"testModulePath",
",",
"index",
")",
"{",
"return",
"testModulePath",
"===",
"modulePath",
"[",
"index",
"]",
";",
"}",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"filePath",
"+",
"' has a module declaration of \"'",
"+",
"moduleName",
"+",
"'\" - which does not match its filename!'",
")",
";",
"}",
"}",
"else",
"{",
"return",
"Promise",
".",
"reject",
"(",
"filePath",
"+",
"' has an invalid module declaration. Check the first line of the file and make sure it has a valid module declaration there!'",
")",
";",
"}",
"}",
")",
";",
"}",
")",
")",
";",
"}"
] |
Check for modules where the name doesn't match the filename. elm-make won't get a chance to detect this; they'll be filtered out first.
|
[
"Check",
"for",
"modules",
"where",
"the",
"name",
"doesn",
"t",
"match",
"the",
"filename",
".",
"elm",
"-",
"make",
"won",
"t",
"get",
"a",
"chance",
"to",
"detect",
"this",
";",
"they",
"ll",
"be",
"filtered",
"out",
"first",
"."
] |
ad469a238e0c686823aebe1c92c61f6c57de3cfe
|
https://github.com/rtfeldman/node-test-runner/blob/ad469a238e0c686823aebe1c92c61f6c57de3cfe/lib/runner.js#L186-L219
|
17,069
|
rtfeldman/node-test-runner
|
fixtures/elm-home/0.19.0/package/elm/virtual-dom/1.0.0/src/Elm/Kernel/VirtualDom.js
|
_VirtualDom_pairwiseRefEqual
|
function _VirtualDom_pairwiseRefEqual(as, bs)
{
for (var i = 0; i < as.length; i++)
{
if (as[i] !== bs[i])
{
return false;
}
}
return true;
}
|
javascript
|
function _VirtualDom_pairwiseRefEqual(as, bs)
{
for (var i = 0; i < as.length; i++)
{
if (as[i] !== bs[i])
{
return false;
}
}
return true;
}
|
[
"function",
"_VirtualDom_pairwiseRefEqual",
"(",
"as",
",",
"bs",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"as",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"as",
"[",
"i",
"]",
"!==",
"bs",
"[",
"i",
"]",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] |
assumes the incoming arrays are the same length
|
[
"assumes",
"the",
"incoming",
"arrays",
"are",
"the",
"same",
"length"
] |
ad469a238e0c686823aebe1c92c61f6c57de3cfe
|
https://github.com/rtfeldman/node-test-runner/blob/ad469a238e0c686823aebe1c92c61f6c57de3cfe/fixtures/elm-home/0.19.0/package/elm/virtual-dom/1.0.0/src/Elm/Kernel/VirtualDom.js#L834-L845
|
17,070
|
krescruz/angular-materialize
|
js/materialize.clockpicker.js
|
mousedown
|
function mousedown(e, space) {
var offset = plate.offset(),
isTouch = /^touch/.test(e.type),
x0 = offset.left + dialRadius,
y0 = offset.top + dialRadius,
dx = (isTouch ? e.originalEvent.touches[0] : e).pageX - x0,
dy = (isTouch ? e.originalEvent.touches[0] : e).pageY - y0,
z = Math.sqrt(dx * dx + dy * dy),
moved = false;
// When clicking on minutes view space, check the mouse position
if (space && (z < outerRadius - tickRadius || z > outerRadius + tickRadius))
return;
e.preventDefault();
// Set cursor style of body after 200ms
var movingTimer = setTimeout(function(){
self.popover.addClass('clockpicker-moving');
}, 200);
// Place the canvas to top
if (svgSupported)
plate.append(self.canvas);
// Clock
self.setHand(dx, dy, !space, true);
// Mousemove on document
$doc.off(mousemoveEvent).on(mousemoveEvent, function(e){
e.preventDefault();
var isTouch = /^touch/.test(e.type),
x = (isTouch ? e.originalEvent.touches[0] : e).pageX - x0,
y = (isTouch ? e.originalEvent.touches[0] : e).pageY - y0;
if (! moved && x === dx && y === dy)
// Clicking in chrome on windows will trigger a mousemove event
return;
moved = true;
self.setHand(x, y, false, true);
});
// Mouseup on document
$doc.off(mouseupEvent).on(mouseupEvent, function(e) {
$doc.off(mouseupEvent);
e.preventDefault();
var isTouch = /^touch/.test(e.type),
x = (isTouch ? e.originalEvent.changedTouches[0] : e).pageX - x0,
y = (isTouch ? e.originalEvent.changedTouches[0] : e).pageY - y0;
if ((space || moved) && x === dx && y === dy)
self.setHand(x, y);
if (self.currentView === 'hours')
self.toggleView('minutes', duration / 2);
else
if (options.autoclose) {
self.minutesView.addClass('clockpicker-dial-out');
setTimeout(function(){
self.done();
}, duration / 2);
}
plate.prepend(canvas);
// Reset cursor style of body
clearTimeout(movingTimer);
self.popover.removeClass('clockpicker-moving');
// Unbind mousemove event
$doc.off(mousemoveEvent);
});
}
|
javascript
|
function mousedown(e, space) {
var offset = plate.offset(),
isTouch = /^touch/.test(e.type),
x0 = offset.left + dialRadius,
y0 = offset.top + dialRadius,
dx = (isTouch ? e.originalEvent.touches[0] : e).pageX - x0,
dy = (isTouch ? e.originalEvent.touches[0] : e).pageY - y0,
z = Math.sqrt(dx * dx + dy * dy),
moved = false;
// When clicking on minutes view space, check the mouse position
if (space && (z < outerRadius - tickRadius || z > outerRadius + tickRadius))
return;
e.preventDefault();
// Set cursor style of body after 200ms
var movingTimer = setTimeout(function(){
self.popover.addClass('clockpicker-moving');
}, 200);
// Place the canvas to top
if (svgSupported)
plate.append(self.canvas);
// Clock
self.setHand(dx, dy, !space, true);
// Mousemove on document
$doc.off(mousemoveEvent).on(mousemoveEvent, function(e){
e.preventDefault();
var isTouch = /^touch/.test(e.type),
x = (isTouch ? e.originalEvent.touches[0] : e).pageX - x0,
y = (isTouch ? e.originalEvent.touches[0] : e).pageY - y0;
if (! moved && x === dx && y === dy)
// Clicking in chrome on windows will trigger a mousemove event
return;
moved = true;
self.setHand(x, y, false, true);
});
// Mouseup on document
$doc.off(mouseupEvent).on(mouseupEvent, function(e) {
$doc.off(mouseupEvent);
e.preventDefault();
var isTouch = /^touch/.test(e.type),
x = (isTouch ? e.originalEvent.changedTouches[0] : e).pageX - x0,
y = (isTouch ? e.originalEvent.changedTouches[0] : e).pageY - y0;
if ((space || moved) && x === dx && y === dy)
self.setHand(x, y);
if (self.currentView === 'hours')
self.toggleView('minutes', duration / 2);
else
if (options.autoclose) {
self.minutesView.addClass('clockpicker-dial-out');
setTimeout(function(){
self.done();
}, duration / 2);
}
plate.prepend(canvas);
// Reset cursor style of body
clearTimeout(movingTimer);
self.popover.removeClass('clockpicker-moving');
// Unbind mousemove event
$doc.off(mousemoveEvent);
});
}
|
[
"function",
"mousedown",
"(",
"e",
",",
"space",
")",
"{",
"var",
"offset",
"=",
"plate",
".",
"offset",
"(",
")",
",",
"isTouch",
"=",
"/",
"^touch",
"/",
".",
"test",
"(",
"e",
".",
"type",
")",
",",
"x0",
"=",
"offset",
".",
"left",
"+",
"dialRadius",
",",
"y0",
"=",
"offset",
".",
"top",
"+",
"dialRadius",
",",
"dx",
"=",
"(",
"isTouch",
"?",
"e",
".",
"originalEvent",
".",
"touches",
"[",
"0",
"]",
":",
"e",
")",
".",
"pageX",
"-",
"x0",
",",
"dy",
"=",
"(",
"isTouch",
"?",
"e",
".",
"originalEvent",
".",
"touches",
"[",
"0",
"]",
":",
"e",
")",
".",
"pageY",
"-",
"y0",
",",
"z",
"=",
"Math",
".",
"sqrt",
"(",
"dx",
"*",
"dx",
"+",
"dy",
"*",
"dy",
")",
",",
"moved",
"=",
"false",
";",
"// When clicking on minutes view space, check the mouse position",
"if",
"(",
"space",
"&&",
"(",
"z",
"<",
"outerRadius",
"-",
"tickRadius",
"||",
"z",
">",
"outerRadius",
"+",
"tickRadius",
")",
")",
"return",
";",
"e",
".",
"preventDefault",
"(",
")",
";",
"// Set cursor style of body after 200ms",
"var",
"movingTimer",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"self",
".",
"popover",
".",
"addClass",
"(",
"'clockpicker-moving'",
")",
";",
"}",
",",
"200",
")",
";",
"// Place the canvas to top",
"if",
"(",
"svgSupported",
")",
"plate",
".",
"append",
"(",
"self",
".",
"canvas",
")",
";",
"// Clock",
"self",
".",
"setHand",
"(",
"dx",
",",
"dy",
",",
"!",
"space",
",",
"true",
")",
";",
"// Mousemove on document",
"$doc",
".",
"off",
"(",
"mousemoveEvent",
")",
".",
"on",
"(",
"mousemoveEvent",
",",
"function",
"(",
"e",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
";",
"var",
"isTouch",
"=",
"/",
"^touch",
"/",
".",
"test",
"(",
"e",
".",
"type",
")",
",",
"x",
"=",
"(",
"isTouch",
"?",
"e",
".",
"originalEvent",
".",
"touches",
"[",
"0",
"]",
":",
"e",
")",
".",
"pageX",
"-",
"x0",
",",
"y",
"=",
"(",
"isTouch",
"?",
"e",
".",
"originalEvent",
".",
"touches",
"[",
"0",
"]",
":",
"e",
")",
".",
"pageY",
"-",
"y0",
";",
"if",
"(",
"!",
"moved",
"&&",
"x",
"===",
"dx",
"&&",
"y",
"===",
"dy",
")",
"// Clicking in chrome on windows will trigger a mousemove event",
"return",
";",
"moved",
"=",
"true",
";",
"self",
".",
"setHand",
"(",
"x",
",",
"y",
",",
"false",
",",
"true",
")",
";",
"}",
")",
";",
"// Mouseup on document",
"$doc",
".",
"off",
"(",
"mouseupEvent",
")",
".",
"on",
"(",
"mouseupEvent",
",",
"function",
"(",
"e",
")",
"{",
"$doc",
".",
"off",
"(",
"mouseupEvent",
")",
";",
"e",
".",
"preventDefault",
"(",
")",
";",
"var",
"isTouch",
"=",
"/",
"^touch",
"/",
".",
"test",
"(",
"e",
".",
"type",
")",
",",
"x",
"=",
"(",
"isTouch",
"?",
"e",
".",
"originalEvent",
".",
"changedTouches",
"[",
"0",
"]",
":",
"e",
")",
".",
"pageX",
"-",
"x0",
",",
"y",
"=",
"(",
"isTouch",
"?",
"e",
".",
"originalEvent",
".",
"changedTouches",
"[",
"0",
"]",
":",
"e",
")",
".",
"pageY",
"-",
"y0",
";",
"if",
"(",
"(",
"space",
"||",
"moved",
")",
"&&",
"x",
"===",
"dx",
"&&",
"y",
"===",
"dy",
")",
"self",
".",
"setHand",
"(",
"x",
",",
"y",
")",
";",
"if",
"(",
"self",
".",
"currentView",
"===",
"'hours'",
")",
"self",
".",
"toggleView",
"(",
"'minutes'",
",",
"duration",
"/",
"2",
")",
";",
"else",
"if",
"(",
"options",
".",
"autoclose",
")",
"{",
"self",
".",
"minutesView",
".",
"addClass",
"(",
"'clockpicker-dial-out'",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"self",
".",
"done",
"(",
")",
";",
"}",
",",
"duration",
"/",
"2",
")",
";",
"}",
"plate",
".",
"prepend",
"(",
"canvas",
")",
";",
"// Reset cursor style of body",
"clearTimeout",
"(",
"movingTimer",
")",
";",
"self",
".",
"popover",
".",
"removeClass",
"(",
"'clockpicker-moving'",
")",
";",
"// Unbind mousemove event",
"$doc",
".",
"off",
"(",
"mousemoveEvent",
")",
";",
"}",
")",
";",
"}"
] |
Mousedown or touchstart
|
[
"Mousedown",
"or",
"touchstart"
] |
121a131b49ee699f43d66a46ed2ae64d50faa3bd
|
https://github.com/krescruz/angular-materialize/blob/121a131b49ee699f43d66a46ed2ae64d50faa3bd/js/materialize.clockpicker.js#L257-L324
|
17,071
|
krescruz/angular-materialize
|
src/angular-materialize.js
|
setScopeValues
|
function setScopeValues(scope, attrs) {
scope.List = [];
scope.Hide = false;
scope.page = parseInt(scope.page) || 1;
scope.total = parseInt(scope.total) || 0;
scope.dots = scope.dots || '...';
scope.ulClass = scope.ulClass || attrs.ulClass || 'pagination';
scope.adjacent = parseInt(scope.adjacent) || 2;
scope.activeClass = 'active';
scope.disabledClass = 'disabled';
scope.scrollTop = scope.$eval(attrs.scrollTop);
scope.hideIfEmpty = scope.$eval(attrs.hideIfEmpty);
scope.showPrevNext = scope.$eval(attrs.showPrevNext);
scope.useSimplePrevNext = scope.$eval(attrs.useSimplePrevNext);
}
|
javascript
|
function setScopeValues(scope, attrs) {
scope.List = [];
scope.Hide = false;
scope.page = parseInt(scope.page) || 1;
scope.total = parseInt(scope.total) || 0;
scope.dots = scope.dots || '...';
scope.ulClass = scope.ulClass || attrs.ulClass || 'pagination';
scope.adjacent = parseInt(scope.adjacent) || 2;
scope.activeClass = 'active';
scope.disabledClass = 'disabled';
scope.scrollTop = scope.$eval(attrs.scrollTop);
scope.hideIfEmpty = scope.$eval(attrs.hideIfEmpty);
scope.showPrevNext = scope.$eval(attrs.showPrevNext);
scope.useSimplePrevNext = scope.$eval(attrs.useSimplePrevNext);
}
|
[
"function",
"setScopeValues",
"(",
"scope",
",",
"attrs",
")",
"{",
"scope",
".",
"List",
"=",
"[",
"]",
";",
"scope",
".",
"Hide",
"=",
"false",
";",
"scope",
".",
"page",
"=",
"parseInt",
"(",
"scope",
".",
"page",
")",
"||",
"1",
";",
"scope",
".",
"total",
"=",
"parseInt",
"(",
"scope",
".",
"total",
")",
"||",
"0",
";",
"scope",
".",
"dots",
"=",
"scope",
".",
"dots",
"||",
"'...'",
";",
"scope",
".",
"ulClass",
"=",
"scope",
".",
"ulClass",
"||",
"attrs",
".",
"ulClass",
"||",
"'pagination'",
";",
"scope",
".",
"adjacent",
"=",
"parseInt",
"(",
"scope",
".",
"adjacent",
")",
"||",
"2",
";",
"scope",
".",
"activeClass",
"=",
"'active'",
";",
"scope",
".",
"disabledClass",
"=",
"'disabled'",
";",
"scope",
".",
"scrollTop",
"=",
"scope",
".",
"$eval",
"(",
"attrs",
".",
"scrollTop",
")",
";",
"scope",
".",
"hideIfEmpty",
"=",
"scope",
".",
"$eval",
"(",
"attrs",
".",
"hideIfEmpty",
")",
";",
"scope",
".",
"showPrevNext",
"=",
"scope",
".",
"$eval",
"(",
"attrs",
".",
"showPrevNext",
")",
";",
"scope",
".",
"useSimplePrevNext",
"=",
"scope",
".",
"$eval",
"(",
"attrs",
".",
"useSimplePrevNext",
")",
";",
"}"
] |
Assign null-able scope values from settings
|
[
"Assign",
"null",
"-",
"able",
"scope",
"values",
"from",
"settings"
] |
121a131b49ee699f43d66a46ed2ae64d50faa3bd
|
https://github.com/krescruz/angular-materialize/blob/121a131b49ee699f43d66a46ed2ae64d50faa3bd/src/angular-materialize.js#L880-L895
|
17,072
|
krescruz/angular-materialize
|
src/angular-materialize.js
|
validateScopeValues
|
function validateScopeValues(scope, pageCount) {
// Block where the page is larger than the pageCount
if (scope.page > pageCount) {
scope.page = pageCount;
}
// Block where the page is less than 0
if (scope.page <= 0) {
scope.page = 1;
}
// Block where adjacent value is 0 or below
if (scope.adjacent <= 0) {
scope.adjacent = 2;
}
// Hide from page if we have 1 or less pages
// if directed to hide empty
if (pageCount <= 1) {
scope.Hide = scope.hideIfEmpty;
}
}
|
javascript
|
function validateScopeValues(scope, pageCount) {
// Block where the page is larger than the pageCount
if (scope.page > pageCount) {
scope.page = pageCount;
}
// Block where the page is less than 0
if (scope.page <= 0) {
scope.page = 1;
}
// Block where adjacent value is 0 or below
if (scope.adjacent <= 0) {
scope.adjacent = 2;
}
// Hide from page if we have 1 or less pages
// if directed to hide empty
if (pageCount <= 1) {
scope.Hide = scope.hideIfEmpty;
}
}
|
[
"function",
"validateScopeValues",
"(",
"scope",
",",
"pageCount",
")",
"{",
"// Block where the page is larger than the pageCount",
"if",
"(",
"scope",
".",
"page",
">",
"pageCount",
")",
"{",
"scope",
".",
"page",
"=",
"pageCount",
";",
"}",
"// Block where the page is less than 0",
"if",
"(",
"scope",
".",
"page",
"<=",
"0",
")",
"{",
"scope",
".",
"page",
"=",
"1",
";",
"}",
"// Block where adjacent value is 0 or below",
"if",
"(",
"scope",
".",
"adjacent",
"<=",
"0",
")",
"{",
"scope",
".",
"adjacent",
"=",
"2",
";",
"}",
"// Hide from page if we have 1 or less pages",
"// if directed to hide empty",
"if",
"(",
"pageCount",
"<=",
"1",
")",
"{",
"scope",
".",
"Hide",
"=",
"scope",
".",
"hideIfEmpty",
";",
"}",
"}"
] |
Validate and clean up any scope values This happens after we have set the scope values
|
[
"Validate",
"and",
"clean",
"up",
"any",
"scope",
"values",
"This",
"happens",
"after",
"we",
"have",
"set",
"the",
"scope",
"values"
] |
121a131b49ee699f43d66a46ed2ae64d50faa3bd
|
https://github.com/krescruz/angular-materialize/blob/121a131b49ee699f43d66a46ed2ae64d50faa3bd/src/angular-materialize.js#L900-L921
|
17,073
|
krescruz/angular-materialize
|
src/angular-materialize.js
|
internalAction
|
function internalAction(scope, page) {
page = page.valueOf();
// Block clicks we try to load the active page
if (scope.page == page) {
return;
}
// Update the page in scope and fire any paging actions
scope.page = page;
scope.paginationAction({
page: page
});
// If allowed scroll up to the top of the page
if (scope.scrollTop) {
scrollTo(0, 0);
}
}
|
javascript
|
function internalAction(scope, page) {
page = page.valueOf();
// Block clicks we try to load the active page
if (scope.page == page) {
return;
}
// Update the page in scope and fire any paging actions
scope.page = page;
scope.paginationAction({
page: page
});
// If allowed scroll up to the top of the page
if (scope.scrollTop) {
scrollTo(0, 0);
}
}
|
[
"function",
"internalAction",
"(",
"scope",
",",
"page",
")",
"{",
"page",
"=",
"page",
".",
"valueOf",
"(",
")",
";",
"// Block clicks we try to load the active page",
"if",
"(",
"scope",
".",
"page",
"==",
"page",
")",
"{",
"return",
";",
"}",
"// Update the page in scope and fire any paging actions",
"scope",
".",
"page",
"=",
"page",
";",
"scope",
".",
"paginationAction",
"(",
"{",
"page",
":",
"page",
"}",
")",
";",
"// If allowed scroll up to the top of the page",
"if",
"(",
"scope",
".",
"scrollTop",
")",
"{",
"scrollTo",
"(",
"0",
",",
"0",
")",
";",
"}",
"}"
] |
Internal Pagination Click Action
|
[
"Internal",
"Pagination",
"Click",
"Action"
] |
121a131b49ee699f43d66a46ed2ae64d50faa3bd
|
https://github.com/krescruz/angular-materialize/blob/121a131b49ee699f43d66a46ed2ae64d50faa3bd/src/angular-materialize.js#L924-L941
|
17,074
|
krescruz/angular-materialize
|
src/angular-materialize.js
|
addRange
|
function addRange(start, finish, scope) {
var i = 0;
for (i = start; i <= finish; i++) {
var item = {
value: $sce.trustAsHtml(i.toString()),
liClass: scope.page == i ? scope.activeClass : 'waves-effect',
action: function() {
internalAction(scope, this.value);
}
};
scope.List.push(item);
}
}
|
javascript
|
function addRange(start, finish, scope) {
var i = 0;
for (i = start; i <= finish; i++) {
var item = {
value: $sce.trustAsHtml(i.toString()),
liClass: scope.page == i ? scope.activeClass : 'waves-effect',
action: function() {
internalAction(scope, this.value);
}
};
scope.List.push(item);
}
}
|
[
"function",
"addRange",
"(",
"start",
",",
"finish",
",",
"scope",
")",
"{",
"var",
"i",
"=",
"0",
";",
"for",
"(",
"i",
"=",
"start",
";",
"i",
"<=",
"finish",
";",
"i",
"++",
")",
"{",
"var",
"item",
"=",
"{",
"value",
":",
"$sce",
".",
"trustAsHtml",
"(",
"i",
".",
"toString",
"(",
")",
")",
",",
"liClass",
":",
"scope",
".",
"page",
"==",
"i",
"?",
"scope",
".",
"activeClass",
":",
"'waves-effect'",
",",
"action",
":",
"function",
"(",
")",
"{",
"internalAction",
"(",
"scope",
",",
"this",
".",
"value",
")",
";",
"}",
"}",
";",
"scope",
".",
"List",
".",
"push",
"(",
"item",
")",
";",
"}",
"}"
] |
Add Range of Numbers
|
[
"Add",
"Range",
"of",
"Numbers"
] |
121a131b49ee699f43d66a46ed2ae64d50faa3bd
|
https://github.com/krescruz/angular-materialize/blob/121a131b49ee699f43d66a46ed2ae64d50faa3bd/src/angular-materialize.js#L944-L957
|
17,075
|
krescruz/angular-materialize
|
src/angular-materialize.js
|
build
|
function build(scope, attrs) {
// Block divide by 0 and empty page size
if (!scope.pageSize || scope.pageSize < 0)
{
return;
}
// Assign scope values
setScopeValues(scope, attrs);
// local variables
var start,
size = scope.adjacent * 2,
pageCount = Math.ceil(scope.total / scope.pageSize);
// Validation Scope
validateScopeValues(scope, pageCount);
// Add the Next and Previous buttons to our list
addPrevNext(scope, pageCount, 'prev');
if (pageCount < (5 + size)) {
start = 1;
addRange(start, pageCount, scope);
} else {
var finish;
if (scope.page <= (1 + size)) {
start = 1;
finish = 2 + size + (scope.adjacent - 1);
addRange(start, finish, scope);
addLast(pageCount, scope, finish);
} else if (pageCount - size > scope.page && scope.page > size) {
start = scope.page - scope.adjacent;
finish = scope.page + scope.adjacent;
addFirst(scope, start);
addRange(start, finish, scope);
addLast(pageCount, scope, finish);
} else {
start = pageCount - (1 + size + (scope.adjacent - 1));
finish = pageCount;
addFirst(scope, start);
addRange(start, finish, scope);
}
}
addPrevNext(scope, pageCount, 'next');
}
|
javascript
|
function build(scope, attrs) {
// Block divide by 0 and empty page size
if (!scope.pageSize || scope.pageSize < 0)
{
return;
}
// Assign scope values
setScopeValues(scope, attrs);
// local variables
var start,
size = scope.adjacent * 2,
pageCount = Math.ceil(scope.total / scope.pageSize);
// Validation Scope
validateScopeValues(scope, pageCount);
// Add the Next and Previous buttons to our list
addPrevNext(scope, pageCount, 'prev');
if (pageCount < (5 + size)) {
start = 1;
addRange(start, pageCount, scope);
} else {
var finish;
if (scope.page <= (1 + size)) {
start = 1;
finish = 2 + size + (scope.adjacent - 1);
addRange(start, finish, scope);
addLast(pageCount, scope, finish);
} else if (pageCount - size > scope.page && scope.page > size) {
start = scope.page - scope.adjacent;
finish = scope.page + scope.adjacent;
addFirst(scope, start);
addRange(start, finish, scope);
addLast(pageCount, scope, finish);
} else {
start = pageCount - (1 + size + (scope.adjacent - 1));
finish = pageCount;
addFirst(scope, start);
addRange(start, finish, scope);
}
}
addPrevNext(scope, pageCount, 'next');
}
|
[
"function",
"build",
"(",
"scope",
",",
"attrs",
")",
"{",
"// Block divide by 0 and empty page size",
"if",
"(",
"!",
"scope",
".",
"pageSize",
"||",
"scope",
".",
"pageSize",
"<",
"0",
")",
"{",
"return",
";",
"}",
"// Assign scope values",
"setScopeValues",
"(",
"scope",
",",
"attrs",
")",
";",
"// local variables",
"var",
"start",
",",
"size",
"=",
"scope",
".",
"adjacent",
"*",
"2",
",",
"pageCount",
"=",
"Math",
".",
"ceil",
"(",
"scope",
".",
"total",
"/",
"scope",
".",
"pageSize",
")",
";",
"// Validation Scope",
"validateScopeValues",
"(",
"scope",
",",
"pageCount",
")",
";",
"// Add the Next and Previous buttons to our list",
"addPrevNext",
"(",
"scope",
",",
"pageCount",
",",
"'prev'",
")",
";",
"if",
"(",
"pageCount",
"<",
"(",
"5",
"+",
"size",
")",
")",
"{",
"start",
"=",
"1",
";",
"addRange",
"(",
"start",
",",
"pageCount",
",",
"scope",
")",
";",
"}",
"else",
"{",
"var",
"finish",
";",
"if",
"(",
"scope",
".",
"page",
"<=",
"(",
"1",
"+",
"size",
")",
")",
"{",
"start",
"=",
"1",
";",
"finish",
"=",
"2",
"+",
"size",
"+",
"(",
"scope",
".",
"adjacent",
"-",
"1",
")",
";",
"addRange",
"(",
"start",
",",
"finish",
",",
"scope",
")",
";",
"addLast",
"(",
"pageCount",
",",
"scope",
",",
"finish",
")",
";",
"}",
"else",
"if",
"(",
"pageCount",
"-",
"size",
">",
"scope",
".",
"page",
"&&",
"scope",
".",
"page",
">",
"size",
")",
"{",
"start",
"=",
"scope",
".",
"page",
"-",
"scope",
".",
"adjacent",
";",
"finish",
"=",
"scope",
".",
"page",
"+",
"scope",
".",
"adjacent",
";",
"addFirst",
"(",
"scope",
",",
"start",
")",
";",
"addRange",
"(",
"start",
",",
"finish",
",",
"scope",
")",
";",
"addLast",
"(",
"pageCount",
",",
"scope",
",",
"finish",
")",
";",
"}",
"else",
"{",
"start",
"=",
"pageCount",
"-",
"(",
"1",
"+",
"size",
"+",
"(",
"scope",
".",
"adjacent",
"-",
"1",
")",
")",
";",
"finish",
"=",
"pageCount",
";",
"addFirst",
"(",
"scope",
",",
"start",
")",
";",
"addRange",
"(",
"start",
",",
"finish",
",",
"scope",
")",
";",
"}",
"}",
"addPrevNext",
"(",
"scope",
",",
"pageCount",
",",
"'next'",
")",
";",
"}"
] |
Main build function
|
[
"Main",
"build",
"function"
] |
121a131b49ee699f43d66a46ed2ae64d50faa3bd
|
https://github.com/krescruz/angular-materialize/blob/121a131b49ee699f43d66a46ed2ae64d50faa3bd/src/angular-materialize.js#L1057-L1116
|
17,076
|
krescruz/angular-materialize
|
src/angular-materialize.js
|
init
|
function init() {
element.addClass("tooltipped");
$compile(element.contents())(scope);
$timeout(function () {
// https://github.com/Dogfalo/materialize/issues/3546
// if element.addClass("tooltipped") would not be executed, then probably this would not be needed
if (element.attr('data-tooltip-id')){
element.tooltip('remove');
}
element.tooltip();
});
rmDestroyListener = scope.$on('$destroy', function () {
element.tooltip("remove");
});
}
|
javascript
|
function init() {
element.addClass("tooltipped");
$compile(element.contents())(scope);
$timeout(function () {
// https://github.com/Dogfalo/materialize/issues/3546
// if element.addClass("tooltipped") would not be executed, then probably this would not be needed
if (element.attr('data-tooltip-id')){
element.tooltip('remove');
}
element.tooltip();
});
rmDestroyListener = scope.$on('$destroy', function () {
element.tooltip("remove");
});
}
|
[
"function",
"init",
"(",
")",
"{",
"element",
".",
"addClass",
"(",
"\"tooltipped\"",
")",
";",
"$compile",
"(",
"element",
".",
"contents",
"(",
")",
")",
"(",
"scope",
")",
";",
"$timeout",
"(",
"function",
"(",
")",
"{",
"// https://github.com/Dogfalo/materialize/issues/3546",
"// if element.addClass(\"tooltipped\") would not be executed, then probably this would not be needed",
"if",
"(",
"element",
".",
"attr",
"(",
"'data-tooltip-id'",
")",
")",
"{",
"element",
".",
"tooltip",
"(",
"'remove'",
")",
";",
"}",
"element",
".",
"tooltip",
"(",
")",
";",
"}",
")",
";",
"rmDestroyListener",
"=",
"scope",
".",
"$on",
"(",
"'$destroy'",
",",
"function",
"(",
")",
"{",
"element",
".",
"tooltip",
"(",
"\"remove\"",
")",
";",
"}",
")",
";",
"}"
] |
assigning to noop
|
[
"assigning",
"to",
"noop"
] |
121a131b49ee699f43d66a46ed2ae64d50faa3bd
|
https://github.com/krescruz/angular-materialize/blob/121a131b49ee699f43d66a46ed2ae64d50faa3bd/src/angular-materialize.js#L1244-L1259
|
17,077
|
simonh1000/angular-http-server
|
lib/get-file-path-from-url.js
|
getFilePathFromUrl
|
function getFilePathFromUrl(url, basePath, { pathLib = path } = {}) {
if (!basePath) {
throw new Error('basePath must be specified');
}
if (!pathLib.isAbsolute(basePath)) {
throw new Error(`${basePath} is invalid - must be absolute`);
}
const relativePath = url.split('?')[0];
if (relativePath.indexOf('../') > -1) {
// any path attempting to traverse up the directory should be rejected
return 'dummy';
}
const absolutePath = pathLib.join(basePath, relativePath);
if (
!absolutePath.startsWith(basePath) || // if the path has broken out of the basePath, it should be rejected
absolutePath.endsWith(pathLib.sep) // only files (not folders) can be served
) {
return 'dummy';
}
return absolutePath;
}
|
javascript
|
function getFilePathFromUrl(url, basePath, { pathLib = path } = {}) {
if (!basePath) {
throw new Error('basePath must be specified');
}
if (!pathLib.isAbsolute(basePath)) {
throw new Error(`${basePath} is invalid - must be absolute`);
}
const relativePath = url.split('?')[0];
if (relativePath.indexOf('../') > -1) {
// any path attempting to traverse up the directory should be rejected
return 'dummy';
}
const absolutePath = pathLib.join(basePath, relativePath);
if (
!absolutePath.startsWith(basePath) || // if the path has broken out of the basePath, it should be rejected
absolutePath.endsWith(pathLib.sep) // only files (not folders) can be served
) {
return 'dummy';
}
return absolutePath;
}
|
[
"function",
"getFilePathFromUrl",
"(",
"url",
",",
"basePath",
",",
"{",
"pathLib",
"=",
"path",
"}",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"!",
"basePath",
")",
"{",
"throw",
"new",
"Error",
"(",
"'basePath must be specified'",
")",
";",
"}",
"if",
"(",
"!",
"pathLib",
".",
"isAbsolute",
"(",
"basePath",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"basePath",
"}",
"`",
")",
";",
"}",
"const",
"relativePath",
"=",
"url",
".",
"split",
"(",
"'?'",
")",
"[",
"0",
"]",
";",
"if",
"(",
"relativePath",
".",
"indexOf",
"(",
"'../'",
")",
">",
"-",
"1",
")",
"{",
"// any path attempting to traverse up the directory should be rejected",
"return",
"'dummy'",
";",
"}",
"const",
"absolutePath",
"=",
"pathLib",
".",
"join",
"(",
"basePath",
",",
"relativePath",
")",
";",
"if",
"(",
"!",
"absolutePath",
".",
"startsWith",
"(",
"basePath",
")",
"||",
"// if the path has broken out of the basePath, it should be rejected",
"absolutePath",
".",
"endsWith",
"(",
"pathLib",
".",
"sep",
")",
"// only files (not folders) can be served",
")",
"{",
"return",
"'dummy'",
";",
"}",
"return",
"absolutePath",
";",
"}"
] |
Safely get the path for a file in the project directory, or reject by returning "dummy"
@param {string} url
@param {string} basePath - absolute path to base directory
@param {object} [pathLib=path] - path library, override for testing
@return {string} - will return 'dummy' if the path is bad
|
[
"Safely",
"get",
"the",
"path",
"for",
"a",
"file",
"in",
"the",
"project",
"directory",
"or",
"reject",
"by",
"returning",
"dummy"
] |
6c86b7a763f4234098d6911f952773aa190cac47
|
https://github.com/simonh1000/angular-http-server/blob/6c86b7a763f4234098d6911f952773aa190cac47/lib/get-file-path-from-url.js#L11-L35
|
17,078
|
wxajs/wxa
|
packages/wxa-core/src/utils/decorators.js
|
Lock
|
function Lock(target, name, descriptor) {
let fn = descriptor.value;
let $$LockIsDoing = false;
let reset = ()=>$$LockIsDoing=false;
descriptor.value = function(...args) {
if ($$LockIsDoing) return;
$$LockIsDoing = true;
let ret = fn.apply(this, args);
if (ret && ret.then) {
// is promise
return ret.then((succ)=>{
reset();
return Promise.resolve(succ);
}, (fail)=>{
reset();
return Promise.reject(fail);
});
} else {
reset();
return ret;
}
};
return descriptor;
}
|
javascript
|
function Lock(target, name, descriptor) {
let fn = descriptor.value;
let $$LockIsDoing = false;
let reset = ()=>$$LockIsDoing=false;
descriptor.value = function(...args) {
if ($$LockIsDoing) return;
$$LockIsDoing = true;
let ret = fn.apply(this, args);
if (ret && ret.then) {
// is promise
return ret.then((succ)=>{
reset();
return Promise.resolve(succ);
}, (fail)=>{
reset();
return Promise.reject(fail);
});
} else {
reset();
return ret;
}
};
return descriptor;
}
|
[
"function",
"Lock",
"(",
"target",
",",
"name",
",",
"descriptor",
")",
"{",
"let",
"fn",
"=",
"descriptor",
".",
"value",
";",
"let",
"$$LockIsDoing",
"=",
"false",
";",
"let",
"reset",
"=",
"(",
")",
"=>",
"$$LockIsDoing",
"=",
"false",
";",
"descriptor",
".",
"value",
"=",
"function",
"(",
"...",
"args",
")",
"{",
"if",
"(",
"$$LockIsDoing",
")",
"return",
";",
"$$LockIsDoing",
"=",
"true",
";",
"let",
"ret",
"=",
"fn",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"if",
"(",
"ret",
"&&",
"ret",
".",
"then",
")",
"{",
"// is promise",
"return",
"ret",
".",
"then",
"(",
"(",
"succ",
")",
"=>",
"{",
"reset",
"(",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
"succ",
")",
";",
"}",
",",
"(",
"fail",
")",
"=>",
"{",
"reset",
"(",
")",
";",
"return",
"Promise",
".",
"reject",
"(",
"fail",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"reset",
"(",
")",
";",
"return",
"ret",
";",
"}",
"}",
";",
"return",
"descriptor",
";",
"}"
] |
Lock function util fn finish process
@param {any} target
@param {any} name
@param {any} descriptor
@return {any}
|
[
"Lock",
"function",
"util",
"fn",
"finish",
"process"
] |
f957458cb4a08d3d9cd1aa166666c36961682c90
|
https://github.com/wxajs/wxa/blob/f957458cb4a08d3d9cd1aa166666c36961682c90/packages/wxa-core/src/utils/decorators.js#L229-L256
|
17,079
|
wxajs/wxa
|
packages/wxa-core/src/decorators/methods.decorators.js
|
Deprecate
|
function Deprecate(methodDescriptor) {
let {descriptor, key} = methodDescriptor;
let fn = descriptor.value;
descriptor.value = function(...args) {
console.warn(`DEPRECATE: [${key}] This function will be removed in future versions.`);
return fn.apply(this, args);
};
return {
...methodDescriptor,
descriptor,
};
}
|
javascript
|
function Deprecate(methodDescriptor) {
let {descriptor, key} = methodDescriptor;
let fn = descriptor.value;
descriptor.value = function(...args) {
console.warn(`DEPRECATE: [${key}] This function will be removed in future versions.`);
return fn.apply(this, args);
};
return {
...methodDescriptor,
descriptor,
};
}
|
[
"function",
"Deprecate",
"(",
"methodDescriptor",
")",
"{",
"let",
"{",
"descriptor",
",",
"key",
"}",
"=",
"methodDescriptor",
";",
"let",
"fn",
"=",
"descriptor",
".",
"value",
";",
"descriptor",
".",
"value",
"=",
"function",
"(",
"...",
"args",
")",
"{",
"console",
".",
"warn",
"(",
"`",
"${",
"key",
"}",
"`",
")",
";",
"return",
"fn",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
";",
"return",
"{",
"...",
"methodDescriptor",
",",
"descriptor",
",",
"}",
";",
"}"
] |
mark methods to deprecate. while developer call it, print a warning text to console
@param {any} methodDescriptor
@return {any}
|
[
"mark",
"methods",
"to",
"deprecate",
".",
"while",
"developer",
"call",
"it",
"print",
"a",
"warning",
"text",
"to",
"console"
] |
f957458cb4a08d3d9cd1aa166666c36961682c90
|
https://github.com/wxajs/wxa/blob/f957458cb4a08d3d9cd1aa166666c36961682c90/packages/wxa-core/src/decorators/methods.decorators.js#L13-L27
|
17,080
|
tbranyen/backbone.layoutmanager
|
node/index.js
|
function(template) {
// Automatically add the `.html` extension.
template = template + ".html";
// Put this fetch into `async` mode to work better in the Node environment.
var done = this.async();
// By default read in the file from the filesystem relative to the code
// being executed.
fs.readFile(template, function(err, contents) {
// Ensure the contents are a String.
contents = String(contents);
// Any errors should be reported.
if (err) {
console.error("Unable to load file " + template + " : " + err);
return done(null);
}
// Pass the template contents back up.
done(_.template(contents));
});
}
|
javascript
|
function(template) {
// Automatically add the `.html` extension.
template = template + ".html";
// Put this fetch into `async` mode to work better in the Node environment.
var done = this.async();
// By default read in the file from the filesystem relative to the code
// being executed.
fs.readFile(template, function(err, contents) {
// Ensure the contents are a String.
contents = String(contents);
// Any errors should be reported.
if (err) {
console.error("Unable to load file " + template + " : " + err);
return done(null);
}
// Pass the template contents back up.
done(_.template(contents));
});
}
|
[
"function",
"(",
"template",
")",
"{",
"// Automatically add the `.html` extension.",
"template",
"=",
"template",
"+",
"\".html\"",
";",
"// Put this fetch into `async` mode to work better in the Node environment.",
"var",
"done",
"=",
"this",
".",
"async",
"(",
")",
";",
"// By default read in the file from the filesystem relative to the code",
"// being executed.",
"fs",
".",
"readFile",
"(",
"template",
",",
"function",
"(",
"err",
",",
"contents",
")",
"{",
"// Ensure the contents are a String.",
"contents",
"=",
"String",
"(",
"contents",
")",
";",
"// Any errors should be reported.",
"if",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"\"Unable to load file \"",
"+",
"template",
"+",
"\" : \"",
"+",
"err",
")",
";",
"return",
"done",
"(",
"null",
")",
";",
"}",
"// Pass the template contents back up.",
"done",
"(",
"_",
".",
"template",
"(",
"contents",
")",
")",
";",
"}",
")",
";",
"}"
] |
Sensible default for Node.js is to load templates from the filesystem. This is similar to how we default to script tags in browser-land.
|
[
"Sensible",
"default",
"for",
"Node",
".",
"js",
"is",
"to",
"load",
"templates",
"from",
"the",
"filesystem",
".",
"This",
"is",
"similar",
"to",
"how",
"we",
"default",
"to",
"script",
"tags",
"in",
"browser",
"-",
"land",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/node/index.js#L43-L66
|
|
17,081
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
function(rendered, manager, def) {
// Actually put the rendered contents into the element.
if (_.isString(rendered)) {
// If no container is specified, we must replace the content.
if (manager.noel) {
rendered = $.parseHTML(rendered, true);
// Remove extra root elements.
this.$el.slice(1).remove();
// Swap out the View on the first top level element to avoid
// duplication.
this.$el.replaceWith(rendered);
// Don't delegate events here - we'll do that in resolve()
this.setElement(rendered, false);
} else {
this.html(this.$el, rendered);
}
}
// Resolve only after fetch and render have succeeded.
def.resolveWith(this, [this]);
}
|
javascript
|
function(rendered, manager, def) {
// Actually put the rendered contents into the element.
if (_.isString(rendered)) {
// If no container is specified, we must replace the content.
if (manager.noel) {
rendered = $.parseHTML(rendered, true);
// Remove extra root elements.
this.$el.slice(1).remove();
// Swap out the View on the first top level element to avoid
// duplication.
this.$el.replaceWith(rendered);
// Don't delegate events here - we'll do that in resolve()
this.setElement(rendered, false);
} else {
this.html(this.$el, rendered);
}
}
// Resolve only after fetch and render have succeeded.
def.resolveWith(this, [this]);
}
|
[
"function",
"(",
"rendered",
",",
"manager",
",",
"def",
")",
"{",
"// Actually put the rendered contents into the element.",
"if",
"(",
"_",
".",
"isString",
"(",
"rendered",
")",
")",
"{",
"// If no container is specified, we must replace the content.",
"if",
"(",
"manager",
".",
"noel",
")",
"{",
"rendered",
"=",
"$",
".",
"parseHTML",
"(",
"rendered",
",",
"true",
")",
";",
"// Remove extra root elements.",
"this",
".",
"$el",
".",
"slice",
"(",
"1",
")",
".",
"remove",
"(",
")",
";",
"// Swap out the View on the first top level element to avoid",
"// duplication.",
"this",
".",
"$el",
".",
"replaceWith",
"(",
"rendered",
")",
";",
"// Don't delegate events here - we'll do that in resolve()",
"this",
".",
"setElement",
"(",
"rendered",
",",
"false",
")",
";",
"}",
"else",
"{",
"this",
".",
"html",
"(",
"this",
".",
"$el",
",",
"rendered",
")",
";",
"}",
"}",
"// Resolve only after fetch and render have succeeded.",
"def",
".",
"resolveWith",
"(",
"this",
",",
"[",
"this",
"]",
")",
";",
"}"
] |
This function is responsible for pairing the rendered template into the DOM element.
|
[
"This",
"function",
"is",
"responsible",
"for",
"pairing",
"the",
"rendered",
"template",
"into",
"the",
"DOM",
"element",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L113-L136
|
|
17,082
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
done
|
function done(context, template) {
// Store the rendered template someplace so it can be re-assignable.
var rendered;
// Trigger this once the render method has completed.
manager.callback = function(rendered) {
// Clean up asynchronous manager properties.
delete manager.isAsync;
delete manager.callback;
root._applyTemplate(rendered, manager, def);
};
// Ensure the cache is up-to-date.
LayoutManager.cache(url, template);
// Render the View into the el property.
if (template) {
rendered = root.renderTemplate.call(root, template, context);
}
// If the function was synchronous, continue execution.
if (!manager.isAsync) {
root._applyTemplate(rendered, manager, def);
}
}
|
javascript
|
function done(context, template) {
// Store the rendered template someplace so it can be re-assignable.
var rendered;
// Trigger this once the render method has completed.
manager.callback = function(rendered) {
// Clean up asynchronous manager properties.
delete manager.isAsync;
delete manager.callback;
root._applyTemplate(rendered, manager, def);
};
// Ensure the cache is up-to-date.
LayoutManager.cache(url, template);
// Render the View into the el property.
if (template) {
rendered = root.renderTemplate.call(root, template, context);
}
// If the function was synchronous, continue execution.
if (!manager.isAsync) {
root._applyTemplate(rendered, manager, def);
}
}
|
[
"function",
"done",
"(",
"context",
",",
"template",
")",
"{",
"// Store the rendered template someplace so it can be re-assignable.",
"var",
"rendered",
";",
"// Trigger this once the render method has completed.",
"manager",
".",
"callback",
"=",
"function",
"(",
"rendered",
")",
"{",
"// Clean up asynchronous manager properties.",
"delete",
"manager",
".",
"isAsync",
";",
"delete",
"manager",
".",
"callback",
";",
"root",
".",
"_applyTemplate",
"(",
"rendered",
",",
"manager",
",",
"def",
")",
";",
"}",
";",
"// Ensure the cache is up-to-date.",
"LayoutManager",
".",
"cache",
"(",
"url",
",",
"template",
")",
";",
"// Render the View into the el property.",
"if",
"(",
"template",
")",
"{",
"rendered",
"=",
"root",
".",
"renderTemplate",
".",
"call",
"(",
"root",
",",
"template",
",",
"context",
")",
";",
"}",
"// If the function was synchronous, continue execution.",
"if",
"(",
"!",
"manager",
".",
"isAsync",
")",
"{",
"root",
".",
"_applyTemplate",
"(",
"rendered",
",",
"manager",
",",
"def",
")",
";",
"}",
"}"
] |
Once the template is successfully fetched, use its contents to proceed. Context argument is first, since it is bound for partial application reasons.
|
[
"Once",
"the",
"template",
"is",
"successfully",
"fetched",
"use",
"its",
"contents",
"to",
"proceed",
".",
"Context",
"argument",
"is",
"first",
"since",
"it",
"is",
"bound",
"for",
"partial",
"application",
"reasons",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L148-L173
|
17,083
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
Layout
|
function Layout(options) {
// Grant this View superpowers.
this.manage = true;
// Give this View access to all passed options as instance properties.
_.extend(this, options);
// Have Backbone set up the rest of this View.
Backbone.View.apply(this, arguments);
}
|
javascript
|
function Layout(options) {
// Grant this View superpowers.
this.manage = true;
// Give this View access to all passed options as instance properties.
_.extend(this, options);
// Have Backbone set up the rest of this View.
Backbone.View.apply(this, arguments);
}
|
[
"function",
"Layout",
"(",
"options",
")",
"{",
"// Grant this View superpowers.",
"this",
".",
"manage",
"=",
"true",
";",
"// Give this View access to all passed options as instance properties.",
"_",
".",
"extend",
"(",
"this",
",",
"options",
")",
";",
"// Have Backbone set up the rest of this View.",
"Backbone",
".",
"View",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}"
] |
This named function allows for significantly easier debugging.
|
[
"This",
"named",
"function",
"allows",
"for",
"significantly",
"easier",
"debugging",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L237-L246
|
17,084
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
function(selector, view) {
// If the `view` argument exists, then a selector was passed in. This code
// path will forward the selector on to `setView`.
if (view) {
return this.setView(selector, view, true);
}
// If no `view` argument is defined, then assume the first argument is the
// View, somewhat now confusingly named `selector`.
return this.setView(selector, true);
}
|
javascript
|
function(selector, view) {
// If the `view` argument exists, then a selector was passed in. This code
// path will forward the selector on to `setView`.
if (view) {
return this.setView(selector, view, true);
}
// If no `view` argument is defined, then assume the first argument is the
// View, somewhat now confusingly named `selector`.
return this.setView(selector, true);
}
|
[
"function",
"(",
"selector",
",",
"view",
")",
"{",
"// If the `view` argument exists, then a selector was passed in. This code",
"// path will forward the selector on to `setView`.",
"if",
"(",
"view",
")",
"{",
"return",
"this",
".",
"setView",
"(",
"selector",
",",
"view",
",",
"true",
")",
";",
"}",
"// If no `view` argument is defined, then assume the first argument is the",
"// View, somewhat now confusingly named `selector`.",
"return",
"this",
".",
"setView",
"(",
"selector",
",",
"true",
")",
";",
"}"
] |
Shorthand to `setView` function with the `insert` flag set.
|
[
"Shorthand",
"to",
"setView",
"function",
"with",
"the",
"insert",
"flag",
"set",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L304-L314
|
|
17,085
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
function(views) {
// If an array of views was passed it should be inserted into the
// root view. Much like calling insertView without a selector.
if (_.isArray(views)) {
return this.setViews({ "": views });
}
_.each(views, function(view, selector) {
views[selector] = _.isArray(view) ? view : [view];
});
return this.setViews(views);
}
|
javascript
|
function(views) {
// If an array of views was passed it should be inserted into the
// root view. Much like calling insertView without a selector.
if (_.isArray(views)) {
return this.setViews({ "": views });
}
_.each(views, function(view, selector) {
views[selector] = _.isArray(view) ? view : [view];
});
return this.setViews(views);
}
|
[
"function",
"(",
"views",
")",
"{",
"// If an array of views was passed it should be inserted into the",
"// root view. Much like calling insertView without a selector.",
"if",
"(",
"_",
".",
"isArray",
"(",
"views",
")",
")",
"{",
"return",
"this",
".",
"setViews",
"(",
"{",
"\"\"",
":",
"views",
"}",
")",
";",
"}",
"_",
".",
"each",
"(",
"views",
",",
"function",
"(",
"view",
",",
"selector",
")",
"{",
"views",
"[",
"selector",
"]",
"=",
"_",
".",
"isArray",
"(",
"view",
")",
"?",
"view",
":",
"[",
"view",
"]",
";",
"}",
")",
";",
"return",
"this",
".",
"setViews",
"(",
"views",
")",
";",
"}"
] |
Iterate over an object and ensure every value is wrapped in an array to ensure they will be inserted, then pass that object to `setViews`.
|
[
"Iterate",
"over",
"an",
"object",
"and",
"ensure",
"every",
"value",
"is",
"wrapped",
"in",
"an",
"array",
"to",
"ensure",
"they",
"will",
"be",
"inserted",
"then",
"pass",
"that",
"object",
"to",
"setViews",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L318-L330
|
|
17,086
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
function(fn) {
var views;
// If the filter argument is a String, then return a chained Version of the
// elements. The value at the specified filter may be undefined, a single
// view, or an array of views; in all cases, chain on a flat array.
if (typeof fn === "string") {
fn = this.sections[fn] || fn;
views = this.views[fn] || [];
// If Views is undefined you are concatenating an `undefined` to an array
// resulting in a value being returned. Defaulting to an array prevents
// this.
//return _.chain([].concat(views || []));
return _.chain([].concat(views));
}
// Generate an array of all top level (no deeply nested) Views flattened.
views = _.chain(this.views).map(function(view) {
return _.isArray(view) ? view : [view];
}, this).flatten();
// If the argument passed is an Object, then pass it to `_.where`.
if (typeof fn === "object") {
return views.where(fn);
}
// If a filter function is provided, run it on all Views and return a
// wrapped chain. Otherwise, simply return a wrapped chain of all Views.
return typeof fn === "function" ? views.filter(fn) : views;
}
|
javascript
|
function(fn) {
var views;
// If the filter argument is a String, then return a chained Version of the
// elements. The value at the specified filter may be undefined, a single
// view, or an array of views; in all cases, chain on a flat array.
if (typeof fn === "string") {
fn = this.sections[fn] || fn;
views = this.views[fn] || [];
// If Views is undefined you are concatenating an `undefined` to an array
// resulting in a value being returned. Defaulting to an array prevents
// this.
//return _.chain([].concat(views || []));
return _.chain([].concat(views));
}
// Generate an array of all top level (no deeply nested) Views flattened.
views = _.chain(this.views).map(function(view) {
return _.isArray(view) ? view : [view];
}, this).flatten();
// If the argument passed is an Object, then pass it to `_.where`.
if (typeof fn === "object") {
return views.where(fn);
}
// If a filter function is provided, run it on all Views and return a
// wrapped chain. Otherwise, simply return a wrapped chain of all Views.
return typeof fn === "function" ? views.filter(fn) : views;
}
|
[
"function",
"(",
"fn",
")",
"{",
"var",
"views",
";",
"// If the filter argument is a String, then return a chained Version of the",
"// elements. The value at the specified filter may be undefined, a single",
"// view, or an array of views; in all cases, chain on a flat array.",
"if",
"(",
"typeof",
"fn",
"===",
"\"string\"",
")",
"{",
"fn",
"=",
"this",
".",
"sections",
"[",
"fn",
"]",
"||",
"fn",
";",
"views",
"=",
"this",
".",
"views",
"[",
"fn",
"]",
"||",
"[",
"]",
";",
"// If Views is undefined you are concatenating an `undefined` to an array",
"// resulting in a value being returned. Defaulting to an array prevents",
"// this.",
"//return _.chain([].concat(views || []));",
"return",
"_",
".",
"chain",
"(",
"[",
"]",
".",
"concat",
"(",
"views",
")",
")",
";",
"}",
"// Generate an array of all top level (no deeply nested) Views flattened.",
"views",
"=",
"_",
".",
"chain",
"(",
"this",
".",
"views",
")",
".",
"map",
"(",
"function",
"(",
"view",
")",
"{",
"return",
"_",
".",
"isArray",
"(",
"view",
")",
"?",
"view",
":",
"[",
"view",
"]",
";",
"}",
",",
"this",
")",
".",
"flatten",
"(",
")",
";",
"// If the argument passed is an Object, then pass it to `_.where`.",
"if",
"(",
"typeof",
"fn",
"===",
"\"object\"",
")",
"{",
"return",
"views",
".",
"where",
"(",
"fn",
")",
";",
"}",
"// If a filter function is provided, run it on all Views and return a",
"// wrapped chain. Otherwise, simply return a wrapped chain of all Views.",
"return",
"typeof",
"fn",
"===",
"\"function\"",
"?",
"views",
".",
"filter",
"(",
"fn",
")",
":",
"views",
";",
"}"
] |
Provide a filter function to get a flattened array of all the subviews. If the filter function is omitted it will return all subviews. If a String is passed instead, it will return the Views for that selector.
|
[
"Provide",
"a",
"filter",
"function",
"to",
"get",
"a",
"flattened",
"array",
"of",
"all",
"the",
"subviews",
".",
"If",
"the",
"filter",
"function",
"is",
"omitted",
"it",
"will",
"return",
"all",
"subviews",
".",
"If",
"a",
"String",
"is",
"passed",
"instead",
"it",
"will",
"return",
"the",
"Views",
"for",
"that",
"selector",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L348-L378
|
|
17,087
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
function(fn) {
var views;
// Allow an optional selector or function to find the right model and
// remove nested Views based off the results of the selector or filter.
views = this.getViews(fn).each(function(nestedView) {
nestedView.remove();
});
// call value incase the chain is evaluated lazily to ensure the views get
// removed
views.value();
return views;
}
|
javascript
|
function(fn) {
var views;
// Allow an optional selector or function to find the right model and
// remove nested Views based off the results of the selector or filter.
views = this.getViews(fn).each(function(nestedView) {
nestedView.remove();
});
// call value incase the chain is evaluated lazily to ensure the views get
// removed
views.value();
return views;
}
|
[
"function",
"(",
"fn",
")",
"{",
"var",
"views",
";",
"// Allow an optional selector or function to find the right model and",
"// remove nested Views based off the results of the selector or filter.",
"views",
"=",
"this",
".",
"getViews",
"(",
"fn",
")",
".",
"each",
"(",
"function",
"(",
"nestedView",
")",
"{",
"nestedView",
".",
"remove",
"(",
")",
";",
"}",
")",
";",
"// call value incase the chain is evaluated lazily to ensure the views get",
"// removed",
"views",
".",
"value",
"(",
")",
";",
"return",
"views",
";",
"}"
] |
Use this to remove Views, internally uses `getViews` so you can pass the same argument here as you would to that method.
|
[
"Use",
"this",
"to",
"remove",
"Views",
"internally",
"uses",
"getViews",
"so",
"you",
"can",
"pass",
"the",
"same",
"argument",
"here",
"as",
"you",
"would",
"to",
"that",
"method",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L382-L396
|
|
17,088
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
function(views) {
// Iterate over all the views and use the View's view method to assign.
_.each(views, function(view, name) {
// If the view is an array put all views into insert mode.
if (_.isArray(view)) {
return _.each(view, function(view) {
this.insertView(name, view);
}, this);
}
// Assign each view using the view function.
this.setView(name, view);
}, this);
// Allow for chaining
return this;
}
|
javascript
|
function(views) {
// Iterate over all the views and use the View's view method to assign.
_.each(views, function(view, name) {
// If the view is an array put all views into insert mode.
if (_.isArray(view)) {
return _.each(view, function(view) {
this.insertView(name, view);
}, this);
}
// Assign each view using the view function.
this.setView(name, view);
}, this);
// Allow for chaining
return this;
}
|
[
"function",
"(",
"views",
")",
"{",
"// Iterate over all the views and use the View's view method to assign.",
"_",
".",
"each",
"(",
"views",
",",
"function",
"(",
"view",
",",
"name",
")",
"{",
"// If the view is an array put all views into insert mode.",
"if",
"(",
"_",
".",
"isArray",
"(",
"view",
")",
")",
"{",
"return",
"_",
".",
"each",
"(",
"view",
",",
"function",
"(",
"view",
")",
"{",
"this",
".",
"insertView",
"(",
"name",
",",
"view",
")",
";",
"}",
",",
"this",
")",
";",
"}",
"// Assign each view using the view function.",
"this",
".",
"setView",
"(",
"name",
",",
"view",
")",
";",
"}",
",",
"this",
")",
";",
"// Allow for chaining",
"return",
"this",
";",
"}"
] |
Allows the setting of multiple views instead of a single view.
|
[
"Allows",
"the",
"setting",
"of",
"multiple",
"views",
"instead",
"of",
"a",
"single",
"view",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L458-L474
|
|
17,089
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
resolve
|
function resolve() {
// Insert all subViews into the parent at once.
_.each(root.views, function(views, selector) {
// Fragments aren't used on arrays of subviews.
if (_.isArray(views)) {
root.htmlBatch(root, views, selector);
}
});
// If there is a parent and we weren't attached to it via the previous
// method (single view), attach.
if (parent && !manager.insertedViaFragment) {
if (!root.contains(parent.el, root.el)) {
// Apply the partial using parent's html() method.
parent.partial(parent.$el, root.$el, rentManager, manager);
}
}
// Ensure events are always correctly bound after rendering.
root.delegateEvents();
// Set this View as successfully rendered.
root.hasRendered = true;
manager.renderInProgress = false;
// Clear triggeredByRAF flag.
delete manager.triggeredByRAF;
// Only process the queue if it exists.
if (manager.queue && manager.queue.length) {
// Ensure that the next render is only called after all other
// `done` handlers have completed. This will prevent `render`
// callbacks from firing out of order.
(manager.queue.shift())();
} else {
// Once the queue is depleted, remove it, the render process has
// completed.
delete manager.queue;
}
// Reusable function for triggering the afterRender callback and event.
function completeRender() {
var console = window.console;
var afterRender = root.afterRender;
if (afterRender) {
afterRender.call(root, root);
}
// Always emit an afterRender event.
root.trigger("afterRender", root);
// If there are multiple top level elements and `el: false` is used,
// display a warning message and a stack trace.
if (manager.noel && root.$el.length > 1) {
// Do not display a warning while testing or if warning suppression
// is enabled.
if (_.isFunction(console.warn) && !root.suppressWarnings) {
console.warn("`el: false` with multiple top level elements is " +
"not supported.");
// Provide a stack trace if available to aid with debugging.
if (_.isFunction(console.trace)) {
console.trace();
}
}
}
}
// If the parent is currently rendering, wait until it has completed
// until calling the nested View's `afterRender`.
if (rentManager && (rentManager.renderInProgress || rentManager.queue)) {
// Wait until the parent View has finished rendering, which could be
// asynchronous, and trigger afterRender on this View once it has
// completed.
parent.once("afterRender", completeRender);
} else {
// This View and its parent have both rendered.
completeRender();
}
return def.resolveWith(root, [root]);
}
|
javascript
|
function resolve() {
// Insert all subViews into the parent at once.
_.each(root.views, function(views, selector) {
// Fragments aren't used on arrays of subviews.
if (_.isArray(views)) {
root.htmlBatch(root, views, selector);
}
});
// If there is a parent and we weren't attached to it via the previous
// method (single view), attach.
if (parent && !manager.insertedViaFragment) {
if (!root.contains(parent.el, root.el)) {
// Apply the partial using parent's html() method.
parent.partial(parent.$el, root.$el, rentManager, manager);
}
}
// Ensure events are always correctly bound after rendering.
root.delegateEvents();
// Set this View as successfully rendered.
root.hasRendered = true;
manager.renderInProgress = false;
// Clear triggeredByRAF flag.
delete manager.triggeredByRAF;
// Only process the queue if it exists.
if (manager.queue && manager.queue.length) {
// Ensure that the next render is only called after all other
// `done` handlers have completed. This will prevent `render`
// callbacks from firing out of order.
(manager.queue.shift())();
} else {
// Once the queue is depleted, remove it, the render process has
// completed.
delete manager.queue;
}
// Reusable function for triggering the afterRender callback and event.
function completeRender() {
var console = window.console;
var afterRender = root.afterRender;
if (afterRender) {
afterRender.call(root, root);
}
// Always emit an afterRender event.
root.trigger("afterRender", root);
// If there are multiple top level elements and `el: false` is used,
// display a warning message and a stack trace.
if (manager.noel && root.$el.length > 1) {
// Do not display a warning while testing or if warning suppression
// is enabled.
if (_.isFunction(console.warn) && !root.suppressWarnings) {
console.warn("`el: false` with multiple top level elements is " +
"not supported.");
// Provide a stack trace if available to aid with debugging.
if (_.isFunction(console.trace)) {
console.trace();
}
}
}
}
// If the parent is currently rendering, wait until it has completed
// until calling the nested View's `afterRender`.
if (rentManager && (rentManager.renderInProgress || rentManager.queue)) {
// Wait until the parent View has finished rendering, which could be
// asynchronous, and trigger afterRender on this View once it has
// completed.
parent.once("afterRender", completeRender);
} else {
// This View and its parent have both rendered.
completeRender();
}
return def.resolveWith(root, [root]);
}
|
[
"function",
"resolve",
"(",
")",
"{",
"// Insert all subViews into the parent at once.",
"_",
".",
"each",
"(",
"root",
".",
"views",
",",
"function",
"(",
"views",
",",
"selector",
")",
"{",
"// Fragments aren't used on arrays of subviews.",
"if",
"(",
"_",
".",
"isArray",
"(",
"views",
")",
")",
"{",
"root",
".",
"htmlBatch",
"(",
"root",
",",
"views",
",",
"selector",
")",
";",
"}",
"}",
")",
";",
"// If there is a parent and we weren't attached to it via the previous",
"// method (single view), attach.",
"if",
"(",
"parent",
"&&",
"!",
"manager",
".",
"insertedViaFragment",
")",
"{",
"if",
"(",
"!",
"root",
".",
"contains",
"(",
"parent",
".",
"el",
",",
"root",
".",
"el",
")",
")",
"{",
"// Apply the partial using parent's html() method.",
"parent",
".",
"partial",
"(",
"parent",
".",
"$el",
",",
"root",
".",
"$el",
",",
"rentManager",
",",
"manager",
")",
";",
"}",
"}",
"// Ensure events are always correctly bound after rendering.",
"root",
".",
"delegateEvents",
"(",
")",
";",
"// Set this View as successfully rendered.",
"root",
".",
"hasRendered",
"=",
"true",
";",
"manager",
".",
"renderInProgress",
"=",
"false",
";",
"// Clear triggeredByRAF flag.",
"delete",
"manager",
".",
"triggeredByRAF",
";",
"// Only process the queue if it exists.",
"if",
"(",
"manager",
".",
"queue",
"&&",
"manager",
".",
"queue",
".",
"length",
")",
"{",
"// Ensure that the next render is only called after all other",
"// `done` handlers have completed. This will prevent `render`",
"// callbacks from firing out of order.",
"(",
"manager",
".",
"queue",
".",
"shift",
"(",
")",
")",
"(",
")",
";",
"}",
"else",
"{",
"// Once the queue is depleted, remove it, the render process has",
"// completed.",
"delete",
"manager",
".",
"queue",
";",
"}",
"// Reusable function for triggering the afterRender callback and event.",
"function",
"completeRender",
"(",
")",
"{",
"var",
"console",
"=",
"window",
".",
"console",
";",
"var",
"afterRender",
"=",
"root",
".",
"afterRender",
";",
"if",
"(",
"afterRender",
")",
"{",
"afterRender",
".",
"call",
"(",
"root",
",",
"root",
")",
";",
"}",
"// Always emit an afterRender event.",
"root",
".",
"trigger",
"(",
"\"afterRender\"",
",",
"root",
")",
";",
"// If there are multiple top level elements and `el: false` is used,",
"// display a warning message and a stack trace.",
"if",
"(",
"manager",
".",
"noel",
"&&",
"root",
".",
"$el",
".",
"length",
">",
"1",
")",
"{",
"// Do not display a warning while testing or if warning suppression",
"// is enabled.",
"if",
"(",
"_",
".",
"isFunction",
"(",
"console",
".",
"warn",
")",
"&&",
"!",
"root",
".",
"suppressWarnings",
")",
"{",
"console",
".",
"warn",
"(",
"\"`el: false` with multiple top level elements is \"",
"+",
"\"not supported.\"",
")",
";",
"// Provide a stack trace if available to aid with debugging.",
"if",
"(",
"_",
".",
"isFunction",
"(",
"console",
".",
"trace",
")",
")",
"{",
"console",
".",
"trace",
"(",
")",
";",
"}",
"}",
"}",
"}",
"// If the parent is currently rendering, wait until it has completed",
"// until calling the nested View's `afterRender`.",
"if",
"(",
"rentManager",
"&&",
"(",
"rentManager",
".",
"renderInProgress",
"||",
"rentManager",
".",
"queue",
")",
")",
"{",
"// Wait until the parent View has finished rendering, which could be",
"// asynchronous, and trigger afterRender on this View once it has",
"// completed.",
"parent",
".",
"once",
"(",
"\"afterRender\"",
",",
"completeRender",
")",
";",
"}",
"else",
"{",
"// This View and its parent have both rendered.",
"completeRender",
"(",
")",
";",
"}",
"return",
"def",
".",
"resolveWith",
"(",
"root",
",",
"[",
"root",
"]",
")",
";",
"}"
] |
Triggered once the render has succeeded.
|
[
"Triggered",
"once",
"the",
"render",
"has",
"succeeded",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L490-L573
|
17,090
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
completeRender
|
function completeRender() {
var console = window.console;
var afterRender = root.afterRender;
if (afterRender) {
afterRender.call(root, root);
}
// Always emit an afterRender event.
root.trigger("afterRender", root);
// If there are multiple top level elements and `el: false` is used,
// display a warning message and a stack trace.
if (manager.noel && root.$el.length > 1) {
// Do not display a warning while testing or if warning suppression
// is enabled.
if (_.isFunction(console.warn) && !root.suppressWarnings) {
console.warn("`el: false` with multiple top level elements is " +
"not supported.");
// Provide a stack trace if available to aid with debugging.
if (_.isFunction(console.trace)) {
console.trace();
}
}
}
}
|
javascript
|
function completeRender() {
var console = window.console;
var afterRender = root.afterRender;
if (afterRender) {
afterRender.call(root, root);
}
// Always emit an afterRender event.
root.trigger("afterRender", root);
// If there are multiple top level elements and `el: false` is used,
// display a warning message and a stack trace.
if (manager.noel && root.$el.length > 1) {
// Do not display a warning while testing or if warning suppression
// is enabled.
if (_.isFunction(console.warn) && !root.suppressWarnings) {
console.warn("`el: false` with multiple top level elements is " +
"not supported.");
// Provide a stack trace if available to aid with debugging.
if (_.isFunction(console.trace)) {
console.trace();
}
}
}
}
|
[
"function",
"completeRender",
"(",
")",
"{",
"var",
"console",
"=",
"window",
".",
"console",
";",
"var",
"afterRender",
"=",
"root",
".",
"afterRender",
";",
"if",
"(",
"afterRender",
")",
"{",
"afterRender",
".",
"call",
"(",
"root",
",",
"root",
")",
";",
"}",
"// Always emit an afterRender event.",
"root",
".",
"trigger",
"(",
"\"afterRender\"",
",",
"root",
")",
";",
"// If there are multiple top level elements and `el: false` is used,",
"// display a warning message and a stack trace.",
"if",
"(",
"manager",
".",
"noel",
"&&",
"root",
".",
"$el",
".",
"length",
">",
"1",
")",
"{",
"// Do not display a warning while testing or if warning suppression",
"// is enabled.",
"if",
"(",
"_",
".",
"isFunction",
"(",
"console",
".",
"warn",
")",
"&&",
"!",
"root",
".",
"suppressWarnings",
")",
"{",
"console",
".",
"warn",
"(",
"\"`el: false` with multiple top level elements is \"",
"+",
"\"not supported.\"",
")",
";",
"// Provide a stack trace if available to aid with debugging.",
"if",
"(",
"_",
".",
"isFunction",
"(",
"console",
".",
"trace",
")",
")",
"{",
"console",
".",
"trace",
"(",
")",
";",
"}",
"}",
"}",
"}"
] |
Reusable function for triggering the afterRender callback and event.
|
[
"Reusable",
"function",
"for",
"triggering",
"the",
"afterRender",
"callback",
"and",
"event",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L532-L558
|
17,091
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
function(callback, deferred) {
var root = this;
var manager = root.__manager__;
var rentManager = manager.parent && manager.parent.__manager__;
// Allow RAF processing to be shut off using `useRAF`:false.
if (this.useRAF === false) {
if (manager.queue) {
aPush.call(manager.queue, callback);
} else {
manager.queue = [];
callback();
}
return;
}
// Keep track of all deferreds so we can resolve them.
manager.deferreds = manager.deferreds || [];
manager.deferreds.push(deferred);
// Schedule resolving all deferreds that are waiting.
deferred.done(resolveDeferreds);
// Cancel any other renders on this view that are queued to execute.
this._cancelQueuedRAFRender();
// Trigger immediately if the parent was triggered by RAF.
// The flag propagates downward so this view's children are also
// rendered immediately.
if (rentManager && rentManager.triggeredByRAF) {
return finish();
}
// Register this request with requestAnimationFrame.
manager.rafID = root.requestAnimationFrame(finish);
function finish() {
// Remove this ID as it is no longer valid.
manager.rafID = null;
// Set flag (will propagate to children) so they render
// without waiting for RAF.
manager.triggeredByRAF = true;
// Call original cb.
callback();
}
// Resolve all deferreds that were cancelled previously, if any.
// This allows the user to bind callbacks to any render callback,
// even if it was cancelled above.
function resolveDeferreds() {
for (var i = 0; i < manager.deferreds.length; i++){
manager.deferreds[i].resolveWith(root, [root]);
}
manager.deferreds = [];
}
}
|
javascript
|
function(callback, deferred) {
var root = this;
var manager = root.__manager__;
var rentManager = manager.parent && manager.parent.__manager__;
// Allow RAF processing to be shut off using `useRAF`:false.
if (this.useRAF === false) {
if (manager.queue) {
aPush.call(manager.queue, callback);
} else {
manager.queue = [];
callback();
}
return;
}
// Keep track of all deferreds so we can resolve them.
manager.deferreds = manager.deferreds || [];
manager.deferreds.push(deferred);
// Schedule resolving all deferreds that are waiting.
deferred.done(resolveDeferreds);
// Cancel any other renders on this view that are queued to execute.
this._cancelQueuedRAFRender();
// Trigger immediately if the parent was triggered by RAF.
// The flag propagates downward so this view's children are also
// rendered immediately.
if (rentManager && rentManager.triggeredByRAF) {
return finish();
}
// Register this request with requestAnimationFrame.
manager.rafID = root.requestAnimationFrame(finish);
function finish() {
// Remove this ID as it is no longer valid.
manager.rafID = null;
// Set flag (will propagate to children) so they render
// without waiting for RAF.
manager.triggeredByRAF = true;
// Call original cb.
callback();
}
// Resolve all deferreds that were cancelled previously, if any.
// This allows the user to bind callbacks to any render callback,
// even if it was cancelled above.
function resolveDeferreds() {
for (var i = 0; i < manager.deferreds.length; i++){
manager.deferreds[i].resolveWith(root, [root]);
}
manager.deferreds = [];
}
}
|
[
"function",
"(",
"callback",
",",
"deferred",
")",
"{",
"var",
"root",
"=",
"this",
";",
"var",
"manager",
"=",
"root",
".",
"__manager__",
";",
"var",
"rentManager",
"=",
"manager",
".",
"parent",
"&&",
"manager",
".",
"parent",
".",
"__manager__",
";",
"// Allow RAF processing to be shut off using `useRAF`:false.",
"if",
"(",
"this",
".",
"useRAF",
"===",
"false",
")",
"{",
"if",
"(",
"manager",
".",
"queue",
")",
"{",
"aPush",
".",
"call",
"(",
"manager",
".",
"queue",
",",
"callback",
")",
";",
"}",
"else",
"{",
"manager",
".",
"queue",
"=",
"[",
"]",
";",
"callback",
"(",
")",
";",
"}",
"return",
";",
"}",
"// Keep track of all deferreds so we can resolve them.",
"manager",
".",
"deferreds",
"=",
"manager",
".",
"deferreds",
"||",
"[",
"]",
";",
"manager",
".",
"deferreds",
".",
"push",
"(",
"deferred",
")",
";",
"// Schedule resolving all deferreds that are waiting.",
"deferred",
".",
"done",
"(",
"resolveDeferreds",
")",
";",
"// Cancel any other renders on this view that are queued to execute.",
"this",
".",
"_cancelQueuedRAFRender",
"(",
")",
";",
"// Trigger immediately if the parent was triggered by RAF.",
"// The flag propagates downward so this view's children are also",
"// rendered immediately.",
"if",
"(",
"rentManager",
"&&",
"rentManager",
".",
"triggeredByRAF",
")",
"{",
"return",
"finish",
"(",
")",
";",
"}",
"// Register this request with requestAnimationFrame.",
"manager",
".",
"rafID",
"=",
"root",
".",
"requestAnimationFrame",
"(",
"finish",
")",
";",
"function",
"finish",
"(",
")",
"{",
"// Remove this ID as it is no longer valid.",
"manager",
".",
"rafID",
"=",
"null",
";",
"// Set flag (will propagate to children) so they render",
"// without waiting for RAF.",
"manager",
".",
"triggeredByRAF",
"=",
"true",
";",
"// Call original cb.",
"callback",
"(",
")",
";",
"}",
"// Resolve all deferreds that were cancelled previously, if any.",
"// This allows the user to bind callbacks to any render callback,",
"// even if it was cancelled above.",
"function",
"resolveDeferreds",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"manager",
".",
"deferreds",
".",
"length",
";",
"i",
"++",
")",
"{",
"manager",
".",
"deferreds",
"[",
"i",
"]",
".",
"resolveWith",
"(",
"root",
",",
"[",
"root",
"]",
")",
";",
"}",
"manager",
".",
"deferreds",
"=",
"[",
"]",
";",
"}",
"}"
] |
Register a view render with RAF.
|
[
"Register",
"a",
"view",
"render",
"with",
"RAF",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L646-L703
|
|
17,092
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
resolveDeferreds
|
function resolveDeferreds() {
for (var i = 0; i < manager.deferreds.length; i++){
manager.deferreds[i].resolveWith(root, [root]);
}
manager.deferreds = [];
}
|
javascript
|
function resolveDeferreds() {
for (var i = 0; i < manager.deferreds.length; i++){
manager.deferreds[i].resolveWith(root, [root]);
}
manager.deferreds = [];
}
|
[
"function",
"resolveDeferreds",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"manager",
".",
"deferreds",
".",
"length",
";",
"i",
"++",
")",
"{",
"manager",
".",
"deferreds",
"[",
"i",
"]",
".",
"resolveWith",
"(",
"root",
",",
"[",
"root",
"]",
")",
";",
"}",
"manager",
".",
"deferreds",
"=",
"[",
"]",
";",
"}"
] |
Resolve all deferreds that were cancelled previously, if any. This allows the user to bind callbacks to any render callback, even if it was cancelled above.
|
[
"Resolve",
"all",
"deferreds",
"that",
"were",
"cancelled",
"previously",
"if",
"any",
".",
"This",
"allows",
"the",
"user",
"to",
"bind",
"callbacks",
"to",
"any",
"render",
"callback",
"even",
"if",
"it",
"was",
"cancelled",
"above",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L697-L702
|
17,093
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
function() {
var root = this;
var manager = root.__manager__;
if (manager.rafID != null) {
root.cancelAnimationFrame(manager.rafID);
}
}
|
javascript
|
function() {
var root = this;
var manager = root.__manager__;
if (manager.rafID != null) {
root.cancelAnimationFrame(manager.rafID);
}
}
|
[
"function",
"(",
")",
"{",
"var",
"root",
"=",
"this",
";",
"var",
"manager",
"=",
"root",
".",
"__manager__",
";",
"if",
"(",
"manager",
".",
"rafID",
"!=",
"null",
")",
"{",
"root",
".",
"cancelAnimationFrame",
"(",
"manager",
".",
"rafID",
")",
";",
"}",
"}"
] |
Cancel any queued render requests.
|
[
"Cancel",
"any",
"queued",
"render",
"requests",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L706-L712
|
|
17,094
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
function(root, force) {
// Shift arguments around.
if (typeof root === "boolean") {
force = root;
root = this;
}
// Allow removeView to be called on instances.
root = root || this;
// Iterate over all of the nested View's and remove.
root.getViews().each(function(view) {
// Force doesn't care about if a View has rendered or not.
if (view.hasRendered || force) {
LayoutManager._removeView(view, force);
}
// call value() in case this chain is evaluated lazily
}).value();
}
|
javascript
|
function(root, force) {
// Shift arguments around.
if (typeof root === "boolean") {
force = root;
root = this;
}
// Allow removeView to be called on instances.
root = root || this;
// Iterate over all of the nested View's and remove.
root.getViews().each(function(view) {
// Force doesn't care about if a View has rendered or not.
if (view.hasRendered || force) {
LayoutManager._removeView(view, force);
}
// call value() in case this chain is evaluated lazily
}).value();
}
|
[
"function",
"(",
"root",
",",
"force",
")",
"{",
"// Shift arguments around.",
"if",
"(",
"typeof",
"root",
"===",
"\"boolean\"",
")",
"{",
"force",
"=",
"root",
";",
"root",
"=",
"this",
";",
"}",
"// Allow removeView to be called on instances.",
"root",
"=",
"root",
"||",
"this",
";",
"// Iterate over all of the nested View's and remove.",
"root",
".",
"getViews",
"(",
")",
".",
"each",
"(",
"function",
"(",
"view",
")",
"{",
"// Force doesn't care about if a View has rendered or not.",
"if",
"(",
"view",
".",
"hasRendered",
"||",
"force",
")",
"{",
"LayoutManager",
".",
"_removeView",
"(",
"view",
",",
"force",
")",
";",
"}",
"// call value() in case this chain is evaluated lazily",
"}",
")",
".",
"value",
"(",
")",
";",
"}"
] |
Remove all nested Views.
|
[
"Remove",
"all",
"nested",
"Views",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L721-L740
|
|
17,095
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
function(view, force) {
var parentViews;
// Shorthand the managers for easier access.
var manager = view.__manager__;
var rentManager = manager.parent && manager.parent.__manager__;
// Test for keep.
var keep = typeof view.keep === "boolean" ? view.keep : view.options.keep;
// In insert mode, remove views that do not have `keep` attribute set,
// unless the force flag is set.
if ((!keep && rentManager && rentManager.insert === true) || force) {
// Clean out the events.
LayoutManager.cleanViews(view);
// Since we are removing this view, force subviews to remove
view._removeViews(true);
// Remove the View completely.
view.$el.remove();
// Cancel any pending renders, if present.
view._cancelQueuedRAFRender();
// Bail out early if no parent exists.
if (!manager.parent) { return; }
// Assign (if they exist) the sibling Views to a property.
parentViews = manager.parent.views[manager.selector];
// If this is an array of items remove items that are not marked to
// keep.
if (_.isArray(parentViews)) {
// Remove duplicate Views.
_.each(_.clone(parentViews), function(view, i) {
// If the managers match, splice off this View.
if (view && view.__manager__ === manager) {
aSplice.call(parentViews, i, 1);
}
});
if (_.isEmpty(parentViews)) {
manager.parent.trigger("empty", manager.selector);
}
return;
}
// Otherwise delete the parent selector.
delete manager.parent.views[manager.selector];
manager.parent.trigger("empty", manager.selector);
}
}
|
javascript
|
function(view, force) {
var parentViews;
// Shorthand the managers for easier access.
var manager = view.__manager__;
var rentManager = manager.parent && manager.parent.__manager__;
// Test for keep.
var keep = typeof view.keep === "boolean" ? view.keep : view.options.keep;
// In insert mode, remove views that do not have `keep` attribute set,
// unless the force flag is set.
if ((!keep && rentManager && rentManager.insert === true) || force) {
// Clean out the events.
LayoutManager.cleanViews(view);
// Since we are removing this view, force subviews to remove
view._removeViews(true);
// Remove the View completely.
view.$el.remove();
// Cancel any pending renders, if present.
view._cancelQueuedRAFRender();
// Bail out early if no parent exists.
if (!manager.parent) { return; }
// Assign (if they exist) the sibling Views to a property.
parentViews = manager.parent.views[manager.selector];
// If this is an array of items remove items that are not marked to
// keep.
if (_.isArray(parentViews)) {
// Remove duplicate Views.
_.each(_.clone(parentViews), function(view, i) {
// If the managers match, splice off this View.
if (view && view.__manager__ === manager) {
aSplice.call(parentViews, i, 1);
}
});
if (_.isEmpty(parentViews)) {
manager.parent.trigger("empty", manager.selector);
}
return;
}
// Otherwise delete the parent selector.
delete manager.parent.views[manager.selector];
manager.parent.trigger("empty", manager.selector);
}
}
|
[
"function",
"(",
"view",
",",
"force",
")",
"{",
"var",
"parentViews",
";",
"// Shorthand the managers for easier access.",
"var",
"manager",
"=",
"view",
".",
"__manager__",
";",
"var",
"rentManager",
"=",
"manager",
".",
"parent",
"&&",
"manager",
".",
"parent",
".",
"__manager__",
";",
"// Test for keep.",
"var",
"keep",
"=",
"typeof",
"view",
".",
"keep",
"===",
"\"boolean\"",
"?",
"view",
".",
"keep",
":",
"view",
".",
"options",
".",
"keep",
";",
"// In insert mode, remove views that do not have `keep` attribute set,",
"// unless the force flag is set.",
"if",
"(",
"(",
"!",
"keep",
"&&",
"rentManager",
"&&",
"rentManager",
".",
"insert",
"===",
"true",
")",
"||",
"force",
")",
"{",
"// Clean out the events.",
"LayoutManager",
".",
"cleanViews",
"(",
"view",
")",
";",
"// Since we are removing this view, force subviews to remove",
"view",
".",
"_removeViews",
"(",
"true",
")",
";",
"// Remove the View completely.",
"view",
".",
"$el",
".",
"remove",
"(",
")",
";",
"// Cancel any pending renders, if present.",
"view",
".",
"_cancelQueuedRAFRender",
"(",
")",
";",
"// Bail out early if no parent exists.",
"if",
"(",
"!",
"manager",
".",
"parent",
")",
"{",
"return",
";",
"}",
"// Assign (if they exist) the sibling Views to a property.",
"parentViews",
"=",
"manager",
".",
"parent",
".",
"views",
"[",
"manager",
".",
"selector",
"]",
";",
"// If this is an array of items remove items that are not marked to",
"// keep.",
"if",
"(",
"_",
".",
"isArray",
"(",
"parentViews",
")",
")",
"{",
"// Remove duplicate Views.",
"_",
".",
"each",
"(",
"_",
".",
"clone",
"(",
"parentViews",
")",
",",
"function",
"(",
"view",
",",
"i",
")",
"{",
"// If the managers match, splice off this View.",
"if",
"(",
"view",
"&&",
"view",
".",
"__manager__",
"===",
"manager",
")",
"{",
"aSplice",
".",
"call",
"(",
"parentViews",
",",
"i",
",",
"1",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"parentViews",
")",
")",
"{",
"manager",
".",
"parent",
".",
"trigger",
"(",
"\"empty\"",
",",
"manager",
".",
"selector",
")",
";",
"}",
"return",
";",
"}",
"// Otherwise delete the parent selector.",
"delete",
"manager",
".",
"parent",
".",
"views",
"[",
"manager",
".",
"selector",
"]",
";",
"manager",
".",
"parent",
".",
"trigger",
"(",
"\"empty\"",
",",
"manager",
".",
"selector",
")",
";",
"}",
"}"
] |
Remove a single nested View.
|
[
"Remove",
"a",
"single",
"nested",
"View",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L743-L792
|
|
17,096
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
function(path, contents) {
// If template path is found in the cache, return the contents.
if (path in this._cache && contents == null) {
return this._cache[path];
// Ensure path and contents aren't undefined.
} else if (path != null && contents != null) {
return this._cache[path] = contents;
}
// If the template is not in the cache, return undefined.
}
|
javascript
|
function(path, contents) {
// If template path is found in the cache, return the contents.
if (path in this._cache && contents == null) {
return this._cache[path];
// Ensure path and contents aren't undefined.
} else if (path != null && contents != null) {
return this._cache[path] = contents;
}
// If the template is not in the cache, return undefined.
}
|
[
"function",
"(",
"path",
",",
"contents",
")",
"{",
"// If template path is found in the cache, return the contents.",
"if",
"(",
"path",
"in",
"this",
".",
"_cache",
"&&",
"contents",
"==",
"null",
")",
"{",
"return",
"this",
".",
"_cache",
"[",
"path",
"]",
";",
"// Ensure path and contents aren't undefined.",
"}",
"else",
"if",
"(",
"path",
"!=",
"null",
"&&",
"contents",
"!=",
"null",
")",
"{",
"return",
"this",
".",
"_cache",
"[",
"path",
"]",
"=",
"contents",
";",
"}",
"// If the template is not in the cache, return undefined.",
"}"
] |
Cache templates into LayoutManager._cache.
|
[
"Cache",
"templates",
"into",
"LayoutManager",
".",
"_cache",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L795-L805
|
|
17,097
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
function(views) {
// Clear out all existing views.
_.each(aConcat.call([], views), function(view) {
// fire cleanup event to the attached handlers
view.trigger("cleanup", view);
// Remove all custom events attached to this View.
view.unbind();
// Automatically unbind `model`.
if (view.model instanceof Backbone.Model) {
view.model.off(null, null, view);
}
// Automatically unbind `collection`.
if (view.collection instanceof Backbone.Collection) {
view.collection.off(null, null, view);
}
// Automatically unbind events bound to this View.
view.stopListening();
// If a custom cleanup method was provided on the view, call it after
// the initial cleanup is done
if (_.isFunction(view.cleanup)) {
view.cleanup();
}
});
}
|
javascript
|
function(views) {
// Clear out all existing views.
_.each(aConcat.call([], views), function(view) {
// fire cleanup event to the attached handlers
view.trigger("cleanup", view);
// Remove all custom events attached to this View.
view.unbind();
// Automatically unbind `model`.
if (view.model instanceof Backbone.Model) {
view.model.off(null, null, view);
}
// Automatically unbind `collection`.
if (view.collection instanceof Backbone.Collection) {
view.collection.off(null, null, view);
}
// Automatically unbind events bound to this View.
view.stopListening();
// If a custom cleanup method was provided on the view, call it after
// the initial cleanup is done
if (_.isFunction(view.cleanup)) {
view.cleanup();
}
});
}
|
[
"function",
"(",
"views",
")",
"{",
"// Clear out all existing views.",
"_",
".",
"each",
"(",
"aConcat",
".",
"call",
"(",
"[",
"]",
",",
"views",
")",
",",
"function",
"(",
"view",
")",
"{",
"// fire cleanup event to the attached handlers",
"view",
".",
"trigger",
"(",
"\"cleanup\"",
",",
"view",
")",
";",
"// Remove all custom events attached to this View.",
"view",
".",
"unbind",
"(",
")",
";",
"// Automatically unbind `model`.",
"if",
"(",
"view",
".",
"model",
"instanceof",
"Backbone",
".",
"Model",
")",
"{",
"view",
".",
"model",
".",
"off",
"(",
"null",
",",
"null",
",",
"view",
")",
";",
"}",
"// Automatically unbind `collection`.",
"if",
"(",
"view",
".",
"collection",
"instanceof",
"Backbone",
".",
"Collection",
")",
"{",
"view",
".",
"collection",
".",
"off",
"(",
"null",
",",
"null",
",",
"view",
")",
";",
"}",
"// Automatically unbind events bound to this View.",
"view",
".",
"stopListening",
"(",
")",
";",
"// If a custom cleanup method was provided on the view, call it after",
"// the initial cleanup is done",
"if",
"(",
"_",
".",
"isFunction",
"(",
"view",
".",
"cleanup",
")",
")",
"{",
"view",
".",
"cleanup",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Accept either a single view or an array of views to clean of all DOM events internal model and collection references and all Backbone.Events.
|
[
"Accept",
"either",
"a",
"single",
"view",
"or",
"an",
"array",
"of",
"views",
"to",
"clean",
"of",
"all",
"DOM",
"events",
"internal",
"model",
"and",
"collection",
"references",
"and",
"all",
"Backbone",
".",
"Events",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L809-L837
|
|
17,098
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
function(options) {
_.extend(LayoutManager.prototype, options);
// Allow LayoutManager to manage Backbone.View.prototype.
if (options.manage) {
Backbone.View.prototype.manage = true;
}
// Disable the element globally.
if (options.el === false) {
Backbone.View.prototype.el = false;
}
// Allow global configuration of `suppressWarnings`.
if (options.suppressWarnings === true) {
Backbone.View.prototype.suppressWarnings = true;
}
// Allow global configuration of `useRAF`.
if (options.useRAF === false) {
Backbone.View.prototype.useRAF = false;
}
// Allow underscore to be swapped out
if (options._) {
_ = options._;
}
}
|
javascript
|
function(options) {
_.extend(LayoutManager.prototype, options);
// Allow LayoutManager to manage Backbone.View.prototype.
if (options.manage) {
Backbone.View.prototype.manage = true;
}
// Disable the element globally.
if (options.el === false) {
Backbone.View.prototype.el = false;
}
// Allow global configuration of `suppressWarnings`.
if (options.suppressWarnings === true) {
Backbone.View.prototype.suppressWarnings = true;
}
// Allow global configuration of `useRAF`.
if (options.useRAF === false) {
Backbone.View.prototype.useRAF = false;
}
// Allow underscore to be swapped out
if (options._) {
_ = options._;
}
}
|
[
"function",
"(",
"options",
")",
"{",
"_",
".",
"extend",
"(",
"LayoutManager",
".",
"prototype",
",",
"options",
")",
";",
"// Allow LayoutManager to manage Backbone.View.prototype.",
"if",
"(",
"options",
".",
"manage",
")",
"{",
"Backbone",
".",
"View",
".",
"prototype",
".",
"manage",
"=",
"true",
";",
"}",
"// Disable the element globally.",
"if",
"(",
"options",
".",
"el",
"===",
"false",
")",
"{",
"Backbone",
".",
"View",
".",
"prototype",
".",
"el",
"=",
"false",
";",
"}",
"// Allow global configuration of `suppressWarnings`.",
"if",
"(",
"options",
".",
"suppressWarnings",
"===",
"true",
")",
"{",
"Backbone",
".",
"View",
".",
"prototype",
".",
"suppressWarnings",
"=",
"true",
";",
"}",
"// Allow global configuration of `useRAF`.",
"if",
"(",
"options",
".",
"useRAF",
"===",
"false",
")",
"{",
"Backbone",
".",
"View",
".",
"prototype",
".",
"useRAF",
"=",
"false",
";",
"}",
"// Allow underscore to be swapped out",
"if",
"(",
"options",
".",
"_",
")",
"{",
"_",
"=",
"options",
".",
"_",
";",
"}",
"}"
] |
This static method allows for global configuration of LayoutManager.
|
[
"This",
"static",
"method",
"allows",
"for",
"global",
"configuration",
"of",
"LayoutManager",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L840-L867
|
|
17,099
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
function(views, options) {
// Ensure that options is always an object, and clone it so that
// changes to the original object don't screw up this view.
options = _.extend({}, options);
// Set up all Views passed.
_.each(aConcat.call([], views), function(view) {
// If the View has already been setup, no need to do it again.
if (view.__manager__) {
return;
}
var views, declaredViews;
var proto = LayoutManager.prototype;
// Ensure necessary properties are set.
_.defaults(view, {
// Ensure a view always has a views object.
views: {},
// Ensure a view always has a sections object.
sections: {},
// Internal state object used to store whether or not a View has been
// taken over by layout manager and if it has been rendered into the
// DOM.
__manager__: {},
// Add the ability to remove all Views.
_removeViews: LayoutManager._removeViews,
// Add the ability to remove itself.
_removeView: LayoutManager._removeView
// Mix in all LayoutManager prototype properties as well.
}, LayoutManager.prototype);
// Assign passed options.
view.options = options;
// Merge the View options into the View.
_.extend(view, options);
// By default the original Remove function is the Backbone.View one.
view._remove = Backbone.View.prototype.remove;
// Ensure the render is always set correctly.
view.render = LayoutManager.prototype.render;
// If the user provided their own remove override, use that instead of
// the default.
if (view.remove !== proto.remove) {
view._remove = view.remove;
view.remove = proto.remove;
}
// Normalize views to exist on either instance or options, default to
// options.
views = options.views || view.views;
// Set the internal views, only if selectors have been provided.
if (_.keys(views).length) {
// Keep original object declared containing Views.
declaredViews = views;
// Reset the property to avoid duplication or overwritting.
view.views = {};
// If any declared view is wrapped in a function, invoke it.
_.each(declaredViews, function(declaredView, key) {
if (typeof declaredView === "function") {
declaredViews[key] = declaredView.call(view, view);
}
});
// Set the declared Views.
view.setViews(declaredViews);
}
});
}
|
javascript
|
function(views, options) {
// Ensure that options is always an object, and clone it so that
// changes to the original object don't screw up this view.
options = _.extend({}, options);
// Set up all Views passed.
_.each(aConcat.call([], views), function(view) {
// If the View has already been setup, no need to do it again.
if (view.__manager__) {
return;
}
var views, declaredViews;
var proto = LayoutManager.prototype;
// Ensure necessary properties are set.
_.defaults(view, {
// Ensure a view always has a views object.
views: {},
// Ensure a view always has a sections object.
sections: {},
// Internal state object used to store whether or not a View has been
// taken over by layout manager and if it has been rendered into the
// DOM.
__manager__: {},
// Add the ability to remove all Views.
_removeViews: LayoutManager._removeViews,
// Add the ability to remove itself.
_removeView: LayoutManager._removeView
// Mix in all LayoutManager prototype properties as well.
}, LayoutManager.prototype);
// Assign passed options.
view.options = options;
// Merge the View options into the View.
_.extend(view, options);
// By default the original Remove function is the Backbone.View one.
view._remove = Backbone.View.prototype.remove;
// Ensure the render is always set correctly.
view.render = LayoutManager.prototype.render;
// If the user provided their own remove override, use that instead of
// the default.
if (view.remove !== proto.remove) {
view._remove = view.remove;
view.remove = proto.remove;
}
// Normalize views to exist on either instance or options, default to
// options.
views = options.views || view.views;
// Set the internal views, only if selectors have been provided.
if (_.keys(views).length) {
// Keep original object declared containing Views.
declaredViews = views;
// Reset the property to avoid duplication or overwritting.
view.views = {};
// If any declared view is wrapped in a function, invoke it.
_.each(declaredViews, function(declaredView, key) {
if (typeof declaredView === "function") {
declaredViews[key] = declaredView.call(view, view);
}
});
// Set the declared Views.
view.setViews(declaredViews);
}
});
}
|
[
"function",
"(",
"views",
",",
"options",
")",
"{",
"// Ensure that options is always an object, and clone it so that",
"// changes to the original object don't screw up this view.",
"options",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"options",
")",
";",
"// Set up all Views passed.",
"_",
".",
"each",
"(",
"aConcat",
".",
"call",
"(",
"[",
"]",
",",
"views",
")",
",",
"function",
"(",
"view",
")",
"{",
"// If the View has already been setup, no need to do it again.",
"if",
"(",
"view",
".",
"__manager__",
")",
"{",
"return",
";",
"}",
"var",
"views",
",",
"declaredViews",
";",
"var",
"proto",
"=",
"LayoutManager",
".",
"prototype",
";",
"// Ensure necessary properties are set.",
"_",
".",
"defaults",
"(",
"view",
",",
"{",
"// Ensure a view always has a views object.",
"views",
":",
"{",
"}",
",",
"// Ensure a view always has a sections object.",
"sections",
":",
"{",
"}",
",",
"// Internal state object used to store whether or not a View has been",
"// taken over by layout manager and if it has been rendered into the",
"// DOM.",
"__manager__",
":",
"{",
"}",
",",
"// Add the ability to remove all Views.",
"_removeViews",
":",
"LayoutManager",
".",
"_removeViews",
",",
"// Add the ability to remove itself.",
"_removeView",
":",
"LayoutManager",
".",
"_removeView",
"// Mix in all LayoutManager prototype properties as well.",
"}",
",",
"LayoutManager",
".",
"prototype",
")",
";",
"// Assign passed options.",
"view",
".",
"options",
"=",
"options",
";",
"// Merge the View options into the View.",
"_",
".",
"extend",
"(",
"view",
",",
"options",
")",
";",
"// By default the original Remove function is the Backbone.View one.",
"view",
".",
"_remove",
"=",
"Backbone",
".",
"View",
".",
"prototype",
".",
"remove",
";",
"// Ensure the render is always set correctly.",
"view",
".",
"render",
"=",
"LayoutManager",
".",
"prototype",
".",
"render",
";",
"// If the user provided their own remove override, use that instead of",
"// the default.",
"if",
"(",
"view",
".",
"remove",
"!==",
"proto",
".",
"remove",
")",
"{",
"view",
".",
"_remove",
"=",
"view",
".",
"remove",
";",
"view",
".",
"remove",
"=",
"proto",
".",
"remove",
";",
"}",
"// Normalize views to exist on either instance or options, default to",
"// options.",
"views",
"=",
"options",
".",
"views",
"||",
"view",
".",
"views",
";",
"// Set the internal views, only if selectors have been provided.",
"if",
"(",
"_",
".",
"keys",
"(",
"views",
")",
".",
"length",
")",
"{",
"// Keep original object declared containing Views.",
"declaredViews",
"=",
"views",
";",
"// Reset the property to avoid duplication or overwritting.",
"view",
".",
"views",
"=",
"{",
"}",
";",
"// If any declared view is wrapped in a function, invoke it.",
"_",
".",
"each",
"(",
"declaredViews",
",",
"function",
"(",
"declaredView",
",",
"key",
")",
"{",
"if",
"(",
"typeof",
"declaredView",
"===",
"\"function\"",
")",
"{",
"declaredViews",
"[",
"key",
"]",
"=",
"declaredView",
".",
"call",
"(",
"view",
",",
"view",
")",
";",
"}",
"}",
")",
";",
"// Set the declared Views.",
"view",
".",
"setViews",
"(",
"declaredViews",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Configure a View to work with the LayoutManager plugin.
|
[
"Configure",
"a",
"View",
"to",
"work",
"with",
"the",
"LayoutManager",
"plugin",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L870-L949
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.