repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | compareDaySegments | function compareDaySegments(a, b) {
return (b.rightCol - b.leftCol) - (a.rightCol - a.leftCol) || // put wider events first
b.event.allDay - a.event.allDay || // if tie, put all-day events first (booleans cast to 0/1)
a.event.start - b.event.start || // if a tie, sort by event start date
(a.event.title || '').localeCompare(b.event.title) // if a tie, sort by event title
} | javascript | function compareDaySegments(a, b) {
return (b.rightCol - b.leftCol) - (a.rightCol - a.leftCol) || // put wider events first
b.event.allDay - a.event.allDay || // if tie, put all-day events first (booleans cast to 0/1)
a.event.start - b.event.start || // if a tie, sort by event start date
(a.event.title || '').localeCompare(b.event.title) // if a tie, sort by event title
} | [
"function",
"compareDaySegments",
"(",
"a",
",",
"b",
")",
"{",
"return",
"(",
"b",
".",
"rightCol",
"-",
"b",
".",
"leftCol",
")",
"-",
"(",
"a",
".",
"rightCol",
"-",
"a",
".",
"leftCol",
")",
"||",
"b",
".",
"event",
".",
"allDay",
"-",
"a",
".",
"event",
".",
"allDay",
"||",
"a",
".",
"event",
".",
"start",
"-",
"b",
".",
"event",
".",
"start",
"||",
"(",
"a",
".",
"event",
".",
"title",
"||",
"''",
")",
".",
"localeCompare",
"(",
"b",
".",
"event",
".",
"title",
")",
"}"
] | A cmp function for determining which segments should appear higher up | [
"A",
"cmp",
"function",
"for",
"determining",
"which",
"segments",
"should",
"appear",
"higher",
"up"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5824-L5829 | train |
carsdotcom/windshieldjs | lib/buildTemplateData.composer.js | composer | function composer(componentMap) {
return buildTemplateData;
/**
* Accepts a Hapi request object (containing Windshield config information) and
* resolves everything Hapi/Vision needs to render an HTML page.
*
* @callback {buildTemplateData}
* @param {Request} request - Hapi request object
* @returns {Promise.<TemplateData>}
*/
async function buildTemplateData(request) {
const filterFn = composePageFilter(request);
const pageContext = await resolvePageContext(request);
const renderer = componentMap.composeFactory(pageContext, request);
const renderedComponentCollection = await renderComponentSchema(pageContext.associations, renderer);
// we only need the data to be in this intermediary format to support
// the filtering logic. We should streamline this out but that would
// be a breaking change.
const rawPageObject = {
attributes: pageContext.attributes,
assoc: renderedComponentCollection,
layout: pageContext.layout,
exported: renderedComponentCollection.exportedData
};
if (process.env.WINDSHIELD_DEBUG) {
request.server.log('info', JSON.stringify(rawPageObject, null, 4));
}
const {assoc, attributes, layout} = await filterFn(rawPageObject);
const template = path.join('layouts', layout);
return {
template,
data: {
attributes,
assoc: assoc.markup,
exported: assoc.exported
}
};
}
} | javascript | function composer(componentMap) {
return buildTemplateData;
/**
* Accepts a Hapi request object (containing Windshield config information) and
* resolves everything Hapi/Vision needs to render an HTML page.
*
* @callback {buildTemplateData}
* @param {Request} request - Hapi request object
* @returns {Promise.<TemplateData>}
*/
async function buildTemplateData(request) {
const filterFn = composePageFilter(request);
const pageContext = await resolvePageContext(request);
const renderer = componentMap.composeFactory(pageContext, request);
const renderedComponentCollection = await renderComponentSchema(pageContext.associations, renderer);
// we only need the data to be in this intermediary format to support
// the filtering logic. We should streamline this out but that would
// be a breaking change.
const rawPageObject = {
attributes: pageContext.attributes,
assoc: renderedComponentCollection,
layout: pageContext.layout,
exported: renderedComponentCollection.exportedData
};
if (process.env.WINDSHIELD_DEBUG) {
request.server.log('info', JSON.stringify(rawPageObject, null, 4));
}
const {assoc, attributes, layout} = await filterFn(rawPageObject);
const template = path.join('layouts', layout);
return {
template,
data: {
attributes,
assoc: assoc.markup,
exported: assoc.exported
}
};
}
} | [
"function",
"composer",
"(",
"componentMap",
")",
"{",
"return",
"buildTemplateData",
";",
"async",
"function",
"buildTemplateData",
"(",
"request",
")",
"{",
"const",
"filterFn",
"=",
"composePageFilter",
"(",
"request",
")",
";",
"const",
"pageContext",
"=",
"await",
"resolvePageContext",
"(",
"request",
")",
";",
"const",
"renderer",
"=",
"componentMap",
".",
"composeFactory",
"(",
"pageContext",
",",
"request",
")",
";",
"const",
"renderedComponentCollection",
"=",
"await",
"renderComponentSchema",
"(",
"pageContext",
".",
"associations",
",",
"renderer",
")",
";",
"const",
"rawPageObject",
"=",
"{",
"attributes",
":",
"pageContext",
".",
"attributes",
",",
"assoc",
":",
"renderedComponentCollection",
",",
"layout",
":",
"pageContext",
".",
"layout",
",",
"exported",
":",
"renderedComponentCollection",
".",
"exportedData",
"}",
";",
"if",
"(",
"process",
".",
"env",
".",
"WINDSHIELD_DEBUG",
")",
"{",
"request",
".",
"server",
".",
"log",
"(",
"'info'",
",",
"JSON",
".",
"stringify",
"(",
"rawPageObject",
",",
"null",
",",
"4",
")",
")",
";",
"}",
"const",
"{",
"assoc",
",",
"attributes",
",",
"layout",
"}",
"=",
"await",
"filterFn",
"(",
"rawPageObject",
")",
";",
"const",
"template",
"=",
"path",
".",
"join",
"(",
"'layouts'",
",",
"layout",
")",
";",
"return",
"{",
"template",
",",
"data",
":",
"{",
"attributes",
",",
"assoc",
":",
"assoc",
".",
"markup",
",",
"exported",
":",
"assoc",
".",
"exported",
"}",
"}",
";",
"}",
"}"
] | An object describing a template file and data that can be used to compile the template
@typedef {Object} TemplateData
@property {string} template - The path to a Handlebars template file
@property {object} data - The data that will be used to compile the template into HTML
@property {object} data.attributes
@property {object} data.exported
@property {Object.<string, string>} data.assoc - Hashmap of association names and HTML markup
Composes a function that processes a Hapi request using Windshield adapters and context.
We can't define the function we need at run-time, so this function will build it for
us when we're ready.
@param {ComponentMap} componentMap - Description of all available Windshield components
@returns {buildTemplateData} | [
"An",
"object",
"describing",
"a",
"template",
"file",
"and",
"data",
"that",
"can",
"be",
"used",
"to",
"compile",
"the",
"template"
] | fddd841c5d9e09251437c9a30cc39700e5e4a1f6 | https://github.com/carsdotcom/windshieldjs/blob/fddd841c5d9e09251437c9a30cc39700e5e4a1f6/lib/buildTemplateData.composer.js#L33-L77 | train |
carsdotcom/windshieldjs | lib/associationProcessorService.js | renderComponentSchema | async function renderComponentSchema(definitionMap, renderComponent) {
/**
* Renders a single Windshield component definition into a rendered
* component object
*
* @param {string} definitionGroupName - Name of the association that contains the component
* @param {ComponentDefinition} definition - Config for a Windshield Component
*
* @return {Promise.<RenderedComponent>}
*/
async function renderOneComponent(definitionGroupName, definition) {
const childDefinitionMap = definition.associations;
// replacing child definitions with rendered child components
definition.associations = await renderAssociationMap(childDefinitionMap);
// we can try to use the group name as a layout
definition.layout = definition.layout || definitionGroupName;
return renderComponent(definition);
}
/**
* Renders an array of component definitions by aggregating them
* into a single rendered component object
*
* @param {string} definitionGroupName - They key where the definitions are found in their parent component's associations
* @param {ComponentDefinition[]} definitionGroup - Array of configs for Windshield Components
* @returns {Promise.<RenderedComponent>}
*/
async function renderComponentFromArray(definitionGroupName, definitionGroup) {
const promises = definitionGroup.map((definintion) => renderOneComponent(definitionGroupName, definintion));
const renderedComponents = await Promise.all(promises);
const markup = [];
const exported = {};
renderedComponents.forEach(function (component) {
merge(exported, component.exported || {});
markup.push(component.markup);
});
const renderedComponentData = { markup: {}, exported};
renderedComponentData.markup[definitionGroupName] = markup.join("\n");
return renderedComponentData;
}
/**
* Iterates through the associations to produce a rendered component collection object
*
* @param {Object.<string, ComponentDefinition[]>} definitionMap - hashmap of arrays of component definitions
* @returns {Promise.<RenderedComponentCollection>}
*/
async function renderAssociationMap(definitionMap) {
if (!definitionMap) {
return {};
}
const definitionEntries = Object.entries(definitionMap);
const promises = definitionEntries.map(([groupName, definitionGroup]) => {
return renderComponentFromArray(groupName, definitionGroup);
});
const results = await Promise.all(promises);
const associationResults = {exported: {}, markup: {}};
return results.reduce(merge, associationResults);
}
return renderAssociationMap(definitionMap);
} | javascript | async function renderComponentSchema(definitionMap, renderComponent) {
/**
* Renders a single Windshield component definition into a rendered
* component object
*
* @param {string} definitionGroupName - Name of the association that contains the component
* @param {ComponentDefinition} definition - Config for a Windshield Component
*
* @return {Promise.<RenderedComponent>}
*/
async function renderOneComponent(definitionGroupName, definition) {
const childDefinitionMap = definition.associations;
// replacing child definitions with rendered child components
definition.associations = await renderAssociationMap(childDefinitionMap);
// we can try to use the group name as a layout
definition.layout = definition.layout || definitionGroupName;
return renderComponent(definition);
}
/**
* Renders an array of component definitions by aggregating them
* into a single rendered component object
*
* @param {string} definitionGroupName - They key where the definitions are found in their parent component's associations
* @param {ComponentDefinition[]} definitionGroup - Array of configs for Windshield Components
* @returns {Promise.<RenderedComponent>}
*/
async function renderComponentFromArray(definitionGroupName, definitionGroup) {
const promises = definitionGroup.map((definintion) => renderOneComponent(definitionGroupName, definintion));
const renderedComponents = await Promise.all(promises);
const markup = [];
const exported = {};
renderedComponents.forEach(function (component) {
merge(exported, component.exported || {});
markup.push(component.markup);
});
const renderedComponentData = { markup: {}, exported};
renderedComponentData.markup[definitionGroupName] = markup.join("\n");
return renderedComponentData;
}
/**
* Iterates through the associations to produce a rendered component collection object
*
* @param {Object.<string, ComponentDefinition[]>} definitionMap - hashmap of arrays of component definitions
* @returns {Promise.<RenderedComponentCollection>}
*/
async function renderAssociationMap(definitionMap) {
if (!definitionMap) {
return {};
}
const definitionEntries = Object.entries(definitionMap);
const promises = definitionEntries.map(([groupName, definitionGroup]) => {
return renderComponentFromArray(groupName, definitionGroup);
});
const results = await Promise.all(promises);
const associationResults = {exported: {}, markup: {}};
return results.reduce(merge, associationResults);
}
return renderAssociationMap(definitionMap);
} | [
"async",
"function",
"renderComponentSchema",
"(",
"definitionMap",
",",
"renderComponent",
")",
"{",
"async",
"function",
"renderOneComponent",
"(",
"definitionGroupName",
",",
"definition",
")",
"{",
"const",
"childDefinitionMap",
"=",
"definition",
".",
"associations",
";",
"definition",
".",
"associations",
"=",
"await",
"renderAssociationMap",
"(",
"childDefinitionMap",
")",
";",
"definition",
".",
"layout",
"=",
"definition",
".",
"layout",
"||",
"definitionGroupName",
";",
"return",
"renderComponent",
"(",
"definition",
")",
";",
"}",
"async",
"function",
"renderComponentFromArray",
"(",
"definitionGroupName",
",",
"definitionGroup",
")",
"{",
"const",
"promises",
"=",
"definitionGroup",
".",
"map",
"(",
"(",
"definintion",
")",
"=>",
"renderOneComponent",
"(",
"definitionGroupName",
",",
"definintion",
")",
")",
";",
"const",
"renderedComponents",
"=",
"await",
"Promise",
".",
"all",
"(",
"promises",
")",
";",
"const",
"markup",
"=",
"[",
"]",
";",
"const",
"exported",
"=",
"{",
"}",
";",
"renderedComponents",
".",
"forEach",
"(",
"function",
"(",
"component",
")",
"{",
"merge",
"(",
"exported",
",",
"component",
".",
"exported",
"||",
"{",
"}",
")",
";",
"markup",
".",
"push",
"(",
"component",
".",
"markup",
")",
";",
"}",
")",
";",
"const",
"renderedComponentData",
"=",
"{",
"markup",
":",
"{",
"}",
",",
"exported",
"}",
";",
"renderedComponentData",
".",
"markup",
"[",
"definitionGroupName",
"]",
"=",
"markup",
".",
"join",
"(",
"\"\\n\"",
")",
";",
"\\n",
"}",
"return",
"renderedComponentData",
";",
"async",
"function",
"renderAssociationMap",
"(",
"definitionMap",
")",
"{",
"if",
"(",
"!",
"definitionMap",
")",
"{",
"return",
"{",
"}",
";",
"}",
"const",
"definitionEntries",
"=",
"Object",
".",
"entries",
"(",
"definitionMap",
")",
";",
"const",
"promises",
"=",
"definitionEntries",
".",
"map",
"(",
"(",
"[",
"groupName",
",",
"definitionGroup",
"]",
")",
"=>",
"{",
"return",
"renderComponentFromArray",
"(",
"groupName",
",",
"definitionGroup",
")",
";",
"}",
")",
";",
"const",
"results",
"=",
"await",
"Promise",
".",
"all",
"(",
"promises",
")",
";",
"const",
"associationResults",
"=",
"{",
"exported",
":",
"{",
"}",
",",
"markup",
":",
"{",
"}",
"}",
";",
"return",
"results",
".",
"reduce",
"(",
"merge",
",",
"associationResults",
")",
";",
"}",
"}"
] | Renders a schema of Windshield component definitions into a schema of
rendered Windshield components.
This method traverses the scheme, processing each component definition using
the same rendering method. A component definition may contain an associations
property, whose value is a hashmap containing arrays of child definitions.
@param {Object.<string, ComponentDefinition[]>} definitionMap - hashmap of arrays of component definitions
@param {componentFactory} renderComponent - The renderer function that will be used to render every component.
@returns {Promise.<RenderedComponentCollection>} | [
"Renders",
"a",
"schema",
"of",
"Windshield",
"component",
"definitions",
"into",
"a",
"schema",
"of",
"rendered",
"Windshield",
"components",
"."
] | fddd841c5d9e09251437c9a30cc39700e5e4a1f6 | https://github.com/carsdotcom/windshieldjs/blob/fddd841c5d9e09251437c9a30cc39700e5e4a1f6/lib/associationProcessorService.js#L17-L90 | train |
carsdotcom/windshieldjs | lib/associationProcessorService.js | renderOneComponent | async function renderOneComponent(definitionGroupName, definition) {
const childDefinitionMap = definition.associations;
// replacing child definitions with rendered child components
definition.associations = await renderAssociationMap(childDefinitionMap);
// we can try to use the group name as a layout
definition.layout = definition.layout || definitionGroupName;
return renderComponent(definition);
} | javascript | async function renderOneComponent(definitionGroupName, definition) {
const childDefinitionMap = definition.associations;
// replacing child definitions with rendered child components
definition.associations = await renderAssociationMap(childDefinitionMap);
// we can try to use the group name as a layout
definition.layout = definition.layout || definitionGroupName;
return renderComponent(definition);
} | [
"async",
"function",
"renderOneComponent",
"(",
"definitionGroupName",
",",
"definition",
")",
"{",
"const",
"childDefinitionMap",
"=",
"definition",
".",
"associations",
";",
"definition",
".",
"associations",
"=",
"await",
"renderAssociationMap",
"(",
"childDefinitionMap",
")",
";",
"definition",
".",
"layout",
"=",
"definition",
".",
"layout",
"||",
"definitionGroupName",
";",
"return",
"renderComponent",
"(",
"definition",
")",
";",
"}"
] | Renders a single Windshield component definition into a rendered
component object
@param {string} definitionGroupName - Name of the association that contains the component
@param {ComponentDefinition} definition - Config for a Windshield Component
@return {Promise.<RenderedComponent>} | [
"Renders",
"a",
"single",
"Windshield",
"component",
"definition",
"into",
"a",
"rendered",
"component",
"object"
] | fddd841c5d9e09251437c9a30cc39700e5e4a1f6 | https://github.com/carsdotcom/windshieldjs/blob/fddd841c5d9e09251437c9a30cc39700e5e4a1f6/lib/associationProcessorService.js#L27-L37 | train |
carsdotcom/windshieldjs | lib/associationProcessorService.js | renderComponentFromArray | async function renderComponentFromArray(definitionGroupName, definitionGroup) {
const promises = definitionGroup.map((definintion) => renderOneComponent(definitionGroupName, definintion));
const renderedComponents = await Promise.all(promises);
const markup = [];
const exported = {};
renderedComponents.forEach(function (component) {
merge(exported, component.exported || {});
markup.push(component.markup);
});
const renderedComponentData = { markup: {}, exported};
renderedComponentData.markup[definitionGroupName] = markup.join("\n");
return renderedComponentData;
} | javascript | async function renderComponentFromArray(definitionGroupName, definitionGroup) {
const promises = definitionGroup.map((definintion) => renderOneComponent(definitionGroupName, definintion));
const renderedComponents = await Promise.all(promises);
const markup = [];
const exported = {};
renderedComponents.forEach(function (component) {
merge(exported, component.exported || {});
markup.push(component.markup);
});
const renderedComponentData = { markup: {}, exported};
renderedComponentData.markup[definitionGroupName] = markup.join("\n");
return renderedComponentData;
} | [
"async",
"function",
"renderComponentFromArray",
"(",
"definitionGroupName",
",",
"definitionGroup",
")",
"{",
"const",
"promises",
"=",
"definitionGroup",
".",
"map",
"(",
"(",
"definintion",
")",
"=>",
"renderOneComponent",
"(",
"definitionGroupName",
",",
"definintion",
")",
")",
";",
"const",
"renderedComponents",
"=",
"await",
"Promise",
".",
"all",
"(",
"promises",
")",
";",
"const",
"markup",
"=",
"[",
"]",
";",
"const",
"exported",
"=",
"{",
"}",
";",
"renderedComponents",
".",
"forEach",
"(",
"function",
"(",
"component",
")",
"{",
"merge",
"(",
"exported",
",",
"component",
".",
"exported",
"||",
"{",
"}",
")",
";",
"markup",
".",
"push",
"(",
"component",
".",
"markup",
")",
";",
"}",
")",
";",
"const",
"renderedComponentData",
"=",
"{",
"markup",
":",
"{",
"}",
",",
"exported",
"}",
";",
"renderedComponentData",
".",
"markup",
"[",
"definitionGroupName",
"]",
"=",
"markup",
".",
"join",
"(",
"\"\\n\"",
")",
";",
"\\n",
"}"
] | Renders an array of component definitions by aggregating them
into a single rendered component object
@param {string} definitionGroupName - They key where the definitions are found in their parent component's associations
@param {ComponentDefinition[]} definitionGroup - Array of configs for Windshield Components
@returns {Promise.<RenderedComponent>} | [
"Renders",
"an",
"array",
"of",
"component",
"definitions",
"by",
"aggregating",
"them",
"into",
"a",
"single",
"rendered",
"component",
"object"
] | fddd841c5d9e09251437c9a30cc39700e5e4a1f6 | https://github.com/carsdotcom/windshieldjs/blob/fddd841c5d9e09251437c9a30cc39700e5e4a1f6/lib/associationProcessorService.js#L47-L64 | train |
carsdotcom/windshieldjs | lib/associationProcessorService.js | renderAssociationMap | async function renderAssociationMap(definitionMap) {
if (!definitionMap) {
return {};
}
const definitionEntries = Object.entries(definitionMap);
const promises = definitionEntries.map(([groupName, definitionGroup]) => {
return renderComponentFromArray(groupName, definitionGroup);
});
const results = await Promise.all(promises);
const associationResults = {exported: {}, markup: {}};
return results.reduce(merge, associationResults);
} | javascript | async function renderAssociationMap(definitionMap) {
if (!definitionMap) {
return {};
}
const definitionEntries = Object.entries(definitionMap);
const promises = definitionEntries.map(([groupName, definitionGroup]) => {
return renderComponentFromArray(groupName, definitionGroup);
});
const results = await Promise.all(promises);
const associationResults = {exported: {}, markup: {}};
return results.reduce(merge, associationResults);
} | [
"async",
"function",
"renderAssociationMap",
"(",
"definitionMap",
")",
"{",
"if",
"(",
"!",
"definitionMap",
")",
"{",
"return",
"{",
"}",
";",
"}",
"const",
"definitionEntries",
"=",
"Object",
".",
"entries",
"(",
"definitionMap",
")",
";",
"const",
"promises",
"=",
"definitionEntries",
".",
"map",
"(",
"(",
"[",
"groupName",
",",
"definitionGroup",
"]",
")",
"=>",
"{",
"return",
"renderComponentFromArray",
"(",
"groupName",
",",
"definitionGroup",
")",
";",
"}",
")",
";",
"const",
"results",
"=",
"await",
"Promise",
".",
"all",
"(",
"promises",
")",
";",
"const",
"associationResults",
"=",
"{",
"exported",
":",
"{",
"}",
",",
"markup",
":",
"{",
"}",
"}",
";",
"return",
"results",
".",
"reduce",
"(",
"merge",
",",
"associationResults",
")",
";",
"}"
] | Iterates through the associations to produce a rendered component collection object
@param {Object.<string, ComponentDefinition[]>} definitionMap - hashmap of arrays of component definitions
@returns {Promise.<RenderedComponentCollection>} | [
"Iterates",
"through",
"the",
"associations",
"to",
"produce",
"a",
"rendered",
"component",
"collection",
"object"
] | fddd841c5d9e09251437c9a30cc39700e5e4a1f6 | https://github.com/carsdotcom/windshieldjs/blob/fddd841c5d9e09251437c9a30cc39700e5e4a1f6/lib/associationProcessorService.js#L72-L86 | train |
BohemiaInteractive/bi-service | lib/moduleLoader.js | fileIterator | function fileIterator(paths, options, callback) {
var filePacks = [];
if (typeof options === 'function') {
callback = options;
options = {};
}
if (typeof paths === 'string') {
paths = [paths];
} else if (paths instanceof Array) {
paths = [].concat(paths);
} else {
throw new Error('Invalid first argument `paths`. Expected type of string or array');
}
options = options || {};
var except = [];
//normalize paths
(options.except || []).forEach(function(p) {
except.push(path.resolve(p));
});
paths.forEach(function(p, index) {
if (fs.lstatSync(p).isDirectory()) {
filePacks.push(fs.readdirSync(p));
} else {
//explicit file paths are already complete,
filePacks.push([path.basename(p)]);
paths.splice(index, 1, path.dirname(p));
}
});
filePacks.forEach(function(files, index) {
files.forEach(function(file) {
var pth = path.join(paths[index], file);
var isDir = fs.lstatSync(pth).isDirectory();
//skip paths defined in options.except array
if (except.indexOf(pth) !== -1) {
return;
}
if (isDir) {
fileIterator([pth], options, callback);
} else {
callback(file, paths[index]);
}
});
});
} | javascript | function fileIterator(paths, options, callback) {
var filePacks = [];
if (typeof options === 'function') {
callback = options;
options = {};
}
if (typeof paths === 'string') {
paths = [paths];
} else if (paths instanceof Array) {
paths = [].concat(paths);
} else {
throw new Error('Invalid first argument `paths`. Expected type of string or array');
}
options = options || {};
var except = [];
//normalize paths
(options.except || []).forEach(function(p) {
except.push(path.resolve(p));
});
paths.forEach(function(p, index) {
if (fs.lstatSync(p).isDirectory()) {
filePacks.push(fs.readdirSync(p));
} else {
//explicit file paths are already complete,
filePacks.push([path.basename(p)]);
paths.splice(index, 1, path.dirname(p));
}
});
filePacks.forEach(function(files, index) {
files.forEach(function(file) {
var pth = path.join(paths[index], file);
var isDir = fs.lstatSync(pth).isDirectory();
//skip paths defined in options.except array
if (except.indexOf(pth) !== -1) {
return;
}
if (isDir) {
fileIterator([pth], options, callback);
} else {
callback(file, paths[index]);
}
});
});
} | [
"function",
"fileIterator",
"(",
"paths",
",",
"options",
",",
"callback",
")",
"{",
"var",
"filePacks",
"=",
"[",
"]",
";",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"callback",
"=",
"options",
";",
"options",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"typeof",
"paths",
"===",
"'string'",
")",
"{",
"paths",
"=",
"[",
"paths",
"]",
";",
"}",
"else",
"if",
"(",
"paths",
"instanceof",
"Array",
")",
"{",
"paths",
"=",
"[",
"]",
".",
"concat",
"(",
"paths",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid first argument `paths`. Expected type of string or array'",
")",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"except",
"=",
"[",
"]",
";",
"(",
"options",
".",
"except",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"p",
")",
"{",
"except",
".",
"push",
"(",
"path",
".",
"resolve",
"(",
"p",
")",
")",
";",
"}",
")",
";",
"paths",
".",
"forEach",
"(",
"function",
"(",
"p",
",",
"index",
")",
"{",
"if",
"(",
"fs",
".",
"lstatSync",
"(",
"p",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"filePacks",
".",
"push",
"(",
"fs",
".",
"readdirSync",
"(",
"p",
")",
")",
";",
"}",
"else",
"{",
"filePacks",
".",
"push",
"(",
"[",
"path",
".",
"basename",
"(",
"p",
")",
"]",
")",
";",
"paths",
".",
"splice",
"(",
"index",
",",
"1",
",",
"path",
".",
"dirname",
"(",
"p",
")",
")",
";",
"}",
"}",
")",
";",
"filePacks",
".",
"forEach",
"(",
"function",
"(",
"files",
",",
"index",
")",
"{",
"files",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"pth",
"=",
"path",
".",
"join",
"(",
"paths",
"[",
"index",
"]",
",",
"file",
")",
";",
"var",
"isDir",
"=",
"fs",
".",
"lstatSync",
"(",
"pth",
")",
".",
"isDirectory",
"(",
")",
";",
"if",
"(",
"except",
".",
"indexOf",
"(",
"pth",
")",
"!==",
"-",
"1",
")",
"{",
"return",
";",
"}",
"if",
"(",
"isDir",
")",
"{",
"fileIterator",
"(",
"[",
"pth",
"]",
",",
"options",
",",
"callback",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"file",
",",
"paths",
"[",
"index",
"]",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] | synchronous helper function
@function fileIterator
@memberof ModuleLoader
@static
@example
require('bi-service').moduleLoader.fileIterator
@param {Array|String} paths - file as well as directory paths
@param {Object} [options]
@param {Array} [options.except] - collection of files/directories that should be excluded
@param {Function} callback is provided with file (string), dirPath (string) arguments
@return {undefined} | [
"synchronous",
"helper",
"function"
] | 89e76f2e93714a3150ce7f59f16f646e4bdbbce1 | https://github.com/BohemiaInteractive/bi-service/blob/89e76f2e93714a3150ce7f59f16f646e4bdbbce1/lib/moduleLoader.js#L70-L120 | train |
JsCommunity/hashy | index.js | getInfo | function getInfo(hash) {
const info = getHashInfo(hash);
const algo = getAlgorithmFromId(info.id);
info.algorithm = algo.name;
info.options = algo.getOptions(hash, info);
return info;
} | javascript | function getInfo(hash) {
const info = getHashInfo(hash);
const algo = getAlgorithmFromId(info.id);
info.algorithm = algo.name;
info.options = algo.getOptions(hash, info);
return info;
} | [
"function",
"getInfo",
"(",
"hash",
")",
"{",
"const",
"info",
"=",
"getHashInfo",
"(",
"hash",
")",
";",
"const",
"algo",
"=",
"getAlgorithmFromId",
"(",
"info",
".",
"id",
")",
";",
"info",
".",
"algorithm",
"=",
"algo",
".",
"name",
";",
"info",
".",
"options",
"=",
"algo",
".",
"getOptions",
"(",
"hash",
",",
"info",
")",
";",
"return",
"info",
";",
"}"
] | Returns information about a hash.
@param {string} hash The hash you want to get information from.
@return {object} Object containing information about the given
hash: “algorithm”: the algorithm used, “options” the options
used. | [
"Returns",
"information",
"about",
"a",
"hash",
"."
] | 971c662e8ed11dcdaef3a176510552ec1e618a8b | https://github.com/JsCommunity/hashy/blob/971c662e8ed11dcdaef3a176510552ec1e618a8b/index.js#L232-L239 | train |
JsCommunity/hashy | index.js | needsRehash | function needsRehash(hash, algo, options) {
const info = getInfo(hash);
if (info.algorithm !== (algo || DEFAULT_ALGO)) {
return true;
}
const algoNeedsRehash = getAlgorithmFromId(info.id).needsRehash;
const result = algoNeedsRehash && algoNeedsRehash(hash, info);
if (typeof result === "boolean") {
return result;
}
const expected = Object.assign(
Object.create(null),
globalOptions[info.algorithm],
options
);
const actual = info.options;
for (const prop in actual) {
const value = actual[prop];
if (typeof value === "number" && value < expected[prop]) {
return true;
}
}
return false;
} | javascript | function needsRehash(hash, algo, options) {
const info = getInfo(hash);
if (info.algorithm !== (algo || DEFAULT_ALGO)) {
return true;
}
const algoNeedsRehash = getAlgorithmFromId(info.id).needsRehash;
const result = algoNeedsRehash && algoNeedsRehash(hash, info);
if (typeof result === "boolean") {
return result;
}
const expected = Object.assign(
Object.create(null),
globalOptions[info.algorithm],
options
);
const actual = info.options;
for (const prop in actual) {
const value = actual[prop];
if (typeof value === "number" && value < expected[prop]) {
return true;
}
}
return false;
} | [
"function",
"needsRehash",
"(",
"hash",
",",
"algo",
",",
"options",
")",
"{",
"const",
"info",
"=",
"getInfo",
"(",
"hash",
")",
";",
"if",
"(",
"info",
".",
"algorithm",
"!==",
"(",
"algo",
"||",
"DEFAULT_ALGO",
")",
")",
"{",
"return",
"true",
";",
"}",
"const",
"algoNeedsRehash",
"=",
"getAlgorithmFromId",
"(",
"info",
".",
"id",
")",
".",
"needsRehash",
";",
"const",
"result",
"=",
"algoNeedsRehash",
"&&",
"algoNeedsRehash",
"(",
"hash",
",",
"info",
")",
";",
"if",
"(",
"typeof",
"result",
"===",
"\"boolean\"",
")",
"{",
"return",
"result",
";",
"}",
"const",
"expected",
"=",
"Object",
".",
"assign",
"(",
"Object",
".",
"create",
"(",
"null",
")",
",",
"globalOptions",
"[",
"info",
".",
"algorithm",
"]",
",",
"options",
")",
";",
"const",
"actual",
"=",
"info",
".",
"options",
";",
"for",
"(",
"const",
"prop",
"in",
"actual",
")",
"{",
"const",
"value",
"=",
"actual",
"[",
"prop",
"]",
";",
"if",
"(",
"typeof",
"value",
"===",
"\"number\"",
"&&",
"value",
"<",
"expected",
"[",
"prop",
"]",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Checks whether the hash needs to be recomputed.
The hash should be recomputed if it does not use the given
algorithm and options.
@param {string} hash The hash to analyse.
@param {integer} algo The algorithm to use.
@param {options} options The options to use.
@return {boolean} Whether the hash needs to be recomputed. | [
"Checks",
"whether",
"the",
"hash",
"needs",
"to",
"be",
"recomputed",
"."
] | 971c662e8ed11dcdaef3a176510552ec1e618a8b | https://github.com/JsCommunity/hashy/blob/971c662e8ed11dcdaef3a176510552ec1e618a8b/index.js#L254-L282 | train |
youpinyao/angular-datepicker | app/scripts/datePickerUtils.js | function (targetIDs, pickerID) {
function matches(id) {
if (id instanceof RegExp) {
return id.test(pickerID);
}
return id === pickerID;
}
if (angular.isArray(targetIDs)) {
return targetIDs.some(matches);
}
return matches(targetIDs);
} | javascript | function (targetIDs, pickerID) {
function matches(id) {
if (id instanceof RegExp) {
return id.test(pickerID);
}
return id === pickerID;
}
if (angular.isArray(targetIDs)) {
return targetIDs.some(matches);
}
return matches(targetIDs);
} | [
"function",
"(",
"targetIDs",
",",
"pickerID",
")",
"{",
"function",
"matches",
"(",
"id",
")",
"{",
"if",
"(",
"id",
"instanceof",
"RegExp",
")",
"{",
"return",
"id",
".",
"test",
"(",
"pickerID",
")",
";",
"}",
"return",
"id",
"===",
"pickerID",
";",
"}",
"if",
"(",
"angular",
".",
"isArray",
"(",
"targetIDs",
")",
")",
"{",
"return",
"targetIDs",
".",
"some",
"(",
"matches",
")",
";",
"}",
"return",
"matches",
"(",
"targetIDs",
")",
";",
"}"
] | Checks if an event targeted at a specific picker, via either a string name, or an array of strings. | [
"Checks",
"if",
"an",
"event",
"targeted",
"at",
"a",
"specific",
"picker",
"via",
"either",
"a",
"string",
"name",
"or",
"an",
"array",
"of",
"strings",
"."
] | 440489d5ecf6f64b6bc14fce78979206755e84fc | https://github.com/youpinyao/angular-datepicker/blob/440489d5ecf6f64b6bc14fce78979206755e84fc/app/scripts/datePickerUtils.js#L225-L237 | train |
|
joshfire/woodman | lib/filters/regexloggernamefilter.js | function (config) {
Filter.call(this);
config = config || {};
this.regex = config.regex || '';
if (utils.isString(this.regex)) {
this.regex = new RegExp(this.regex);
}
this.onMatch = config.match || config.onMatch || 'neutral';
this.onMismatch = config.mismatch || config.onMismatch || 'deny';
} | javascript | function (config) {
Filter.call(this);
config = config || {};
this.regex = config.regex || '';
if (utils.isString(this.regex)) {
this.regex = new RegExp(this.regex);
}
this.onMatch = config.match || config.onMatch || 'neutral';
this.onMismatch = config.mismatch || config.onMismatch || 'deny';
} | [
"function",
"(",
"config",
")",
"{",
"Filter",
".",
"call",
"(",
"this",
")",
";",
"config",
"=",
"config",
"||",
"{",
"}",
";",
"this",
".",
"regex",
"=",
"config",
".",
"regex",
"||",
"''",
";",
"if",
"(",
"utils",
".",
"isString",
"(",
"this",
".",
"regex",
")",
")",
"{",
"this",
".",
"regex",
"=",
"new",
"RegExp",
"(",
"this",
".",
"regex",
")",
";",
"}",
"this",
".",
"onMatch",
"=",
"config",
".",
"match",
"||",
"config",
".",
"onMatch",
"||",
"'neutral'",
";",
"this",
".",
"onMismatch",
"=",
"config",
".",
"mismatch",
"||",
"config",
".",
"onMismatch",
"||",
"'deny'",
";",
"}"
] | Definition of the RegexFilter class.
@constructor
@param {Object} config Filter configuration. Possible configuration keys:
- regex: The regular expression to use. String or RegExp. Required.
- match: Decision to take when the event matches the regexp. String.
Default value is "accept".
- mismatch: Decision to take when the event does not match the regexp.
String. Default value is "neutral". | [
"Definition",
"of",
"the",
"RegexFilter",
"class",
"."
] | fdc05de2124388780924980e6f27bf4483056d18 | https://github.com/joshfire/woodman/blob/fdc05de2124388780924980e6f27bf4483056d18/lib/filters/regexloggernamefilter.js#L35-L46 | train |
|
neurosnap/gen-readlines | index.js | _concat | function _concat(buffOne, buffTwo) {
if (!buffOne) return buffTwo;
if (!buffTwo) return buffOne;
let newLength = buffOne.length + buffTwo.length;
return Buffer.concat([buffOne, buffTwo], newLength);
} | javascript | function _concat(buffOne, buffTwo) {
if (!buffOne) return buffTwo;
if (!buffTwo) return buffOne;
let newLength = buffOne.length + buffTwo.length;
return Buffer.concat([buffOne, buffTwo], newLength);
} | [
"function",
"_concat",
"(",
"buffOne",
",",
"buffTwo",
")",
"{",
"if",
"(",
"!",
"buffOne",
")",
"return",
"buffTwo",
";",
"if",
"(",
"!",
"buffTwo",
")",
"return",
"buffOne",
";",
"let",
"newLength",
"=",
"buffOne",
".",
"length",
"+",
"buffTwo",
".",
"length",
";",
"return",
"Buffer",
".",
"concat",
"(",
"[",
"buffOne",
",",
"buffTwo",
"]",
",",
"newLength",
")",
";",
"}"
] | Combines two buffers
@param {Object} [buffOne] First buffer object
@param {Object} [buffTwo] Second buffer object
@return {Object} Combined buffer object | [
"Combines",
"two",
"buffers"
] | 2229978004eea584d0a5cdb7986ad642956c0960 | https://github.com/neurosnap/gen-readlines/blob/2229978004eea584d0a5cdb7986ad642956c0960/index.js#L71-L77 | train |
atomantic/undermore | gulp/utils.js | function () {
var pkg = require(process.cwd() + '/package.json');
var licenses = [];
pkg.licenses.forEach(function (license) {
licenses.push(license.type);
});
return '/*! ' + pkg.name + ' - v' + pkg.version + ' - ' + gutil.date("yyyy-mm-dd") + "\n" +
(pkg.homepage ? "* " + pkg.homepage + "\n" : "") +
'* Copyright (c) ' + gutil.date("yyyy") + ' ' + pkg.author.name +
'; Licensed ' + licenses.join(', ') + ' */\n';
} | javascript | function () {
var pkg = require(process.cwd() + '/package.json');
var licenses = [];
pkg.licenses.forEach(function (license) {
licenses.push(license.type);
});
return '/*! ' + pkg.name + ' - v' + pkg.version + ' - ' + gutil.date("yyyy-mm-dd") + "\n" +
(pkg.homepage ? "* " + pkg.homepage + "\n" : "") +
'* Copyright (c) ' + gutil.date("yyyy") + ' ' + pkg.author.name +
'; Licensed ' + licenses.join(', ') + ' */\n';
} | [
"function",
"(",
")",
"{",
"var",
"pkg",
"=",
"require",
"(",
"process",
".",
"cwd",
"(",
")",
"+",
"'/package.json'",
")",
";",
"var",
"licenses",
"=",
"[",
"]",
";",
"pkg",
".",
"licenses",
".",
"forEach",
"(",
"function",
"(",
"license",
")",
"{",
"licenses",
".",
"push",
"(",
"license",
".",
"type",
")",
";",
"}",
")",
";",
"return",
"'/*! '",
"+",
"pkg",
".",
"name",
"+",
"' - v'",
"+",
"pkg",
".",
"version",
"+",
"' - '",
"+",
"gutil",
".",
"date",
"(",
"\"yyyy-mm-dd\"",
")",
"+",
"\"\\n\"",
"+",
"\\n",
"+",
"(",
"pkg",
".",
"homepage",
"?",
"\"* \"",
"+",
"pkg",
".",
"homepage",
"+",
"\"\\n\"",
":",
"\\n",
")",
"+",
"\"\"",
"+",
"'* Copyright (c) '",
"+",
"gutil",
".",
"date",
"(",
"\"yyyy\"",
")",
"+",
"' '",
"+",
"pkg",
".",
"author",
".",
"name",
"+",
"'; Licensed '",
";",
"}"
] | This method builds our license string for embedding into the compiled file | [
"This",
"method",
"builds",
"our",
"license",
"string",
"for",
"embedding",
"into",
"the",
"compiled",
"file"
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/gulp/utils.js#L8-L19 | train |
|
bigcompany/big | apps/voice-recognition/public/speech.js | function(commands, resetCommands) {
// resetCommands defaults to true
if (resetCommands === undefined) {
resetCommands = true;
} else {
resetCommands = !!resetCommands;
}
// Abort previous instances of recognition already running
if (recognition && recognition.abort) {
recognition.abort();
}
// initiate SpeechRecognition
recognition = new SpeechRecognition();
// Set the max number of alternative transcripts to try and match with a command
recognition.maxAlternatives = 5;
// In HTTPS, turn off continuous mode for faster results.
// In HTTP, turn on continuous mode for much slower results, but no repeating security notices
recognition.continuous = root.location.protocol === 'http:';
// Sets the language to the default 'en-US'. This can be changed with annyang.setLanguage()
recognition.lang = 'en-US';
recognition.onstart = function() { invokeCallbacks(callbacks.start); };
recognition.onerror = function(event) {
invokeCallbacks(callbacks.error);
switch (event.error) {
case 'network':
invokeCallbacks(callbacks.errorNetwork);
break;
case 'not-allowed':
case 'service-not-allowed':
// if permission to use the mic is denied, turn off auto-restart
autoRestart = false;
// determine if permission was denied by user or automatically.
if (new Date().getTime()-lastStartedAt < 200) {
invokeCallbacks(callbacks.errorPermissionBlocked);
} else {
invokeCallbacks(callbacks.errorPermissionDenied);
}
break;
}
};
recognition.onend = function() {
invokeCallbacks(callbacks.end);
// annyang will auto restart if it is closed automatically and not by user action.
if (autoRestart) {
// play nicely with the browser, and never restart annyang automatically more than once per second
var timeSinceLastStart = new Date().getTime()-lastStartedAt;
if (timeSinceLastStart < 1000) {
setTimeout(root.annyang.start, 1000-timeSinceLastStart);
} else {
root.annyang.start();
}
}
};
recognition.onresult = function(event) {
invokeCallbacks(callbacks.result);
var results = event.results[event.resultIndex];
var commandText;
// go over each of the 5 results and alternative results received (we've set maxAlternatives to 5 above)
for (var i = 0; i<results.length; i++) {
// the text recognized
commandText = results[i].transcript.trim();
// do stuff
$('#speechActivity').html('<h2>Last voice command: ' + commandText + '</h2>');
if (debugState) {
// document.getElementById('speechActivity').innerHTML = commandText;
root.console.log('Speech recognized: %c'+commandText, debugStyle);
}
// try and match recognized text to one of the commands on the list
for (var j = 0, l = commandsList.length; j < l; j++) {
var result = commandsList[j].command.exec(commandText);
if (result) {
var parameters = result.slice(1);
if (debugState) {
root.console.log('command matched: %c'+commandsList[j].originalPhrase, debugStyle);
if (parameters.length) {
root.console.log('with parameters', parameters);
}
}
// execute the matched command
commandsList[j].callback.apply(this, parameters);
invokeCallbacks(callbacks.resultMatch);
return true;
}
}
}
invokeCallbacks(callbacks.resultNoMatch);
return false;
};
// build commands list
if (resetCommands) {
commandsList = [];
}
if (commands.length) {
this.addCommands(commands);
}
} | javascript | function(commands, resetCommands) {
// resetCommands defaults to true
if (resetCommands === undefined) {
resetCommands = true;
} else {
resetCommands = !!resetCommands;
}
// Abort previous instances of recognition already running
if (recognition && recognition.abort) {
recognition.abort();
}
// initiate SpeechRecognition
recognition = new SpeechRecognition();
// Set the max number of alternative transcripts to try and match with a command
recognition.maxAlternatives = 5;
// In HTTPS, turn off continuous mode for faster results.
// In HTTP, turn on continuous mode for much slower results, but no repeating security notices
recognition.continuous = root.location.protocol === 'http:';
// Sets the language to the default 'en-US'. This can be changed with annyang.setLanguage()
recognition.lang = 'en-US';
recognition.onstart = function() { invokeCallbacks(callbacks.start); };
recognition.onerror = function(event) {
invokeCallbacks(callbacks.error);
switch (event.error) {
case 'network':
invokeCallbacks(callbacks.errorNetwork);
break;
case 'not-allowed':
case 'service-not-allowed':
// if permission to use the mic is denied, turn off auto-restart
autoRestart = false;
// determine if permission was denied by user or automatically.
if (new Date().getTime()-lastStartedAt < 200) {
invokeCallbacks(callbacks.errorPermissionBlocked);
} else {
invokeCallbacks(callbacks.errorPermissionDenied);
}
break;
}
};
recognition.onend = function() {
invokeCallbacks(callbacks.end);
// annyang will auto restart if it is closed automatically and not by user action.
if (autoRestart) {
// play nicely with the browser, and never restart annyang automatically more than once per second
var timeSinceLastStart = new Date().getTime()-lastStartedAt;
if (timeSinceLastStart < 1000) {
setTimeout(root.annyang.start, 1000-timeSinceLastStart);
} else {
root.annyang.start();
}
}
};
recognition.onresult = function(event) {
invokeCallbacks(callbacks.result);
var results = event.results[event.resultIndex];
var commandText;
// go over each of the 5 results and alternative results received (we've set maxAlternatives to 5 above)
for (var i = 0; i<results.length; i++) {
// the text recognized
commandText = results[i].transcript.trim();
// do stuff
$('#speechActivity').html('<h2>Last voice command: ' + commandText + '</h2>');
if (debugState) {
// document.getElementById('speechActivity').innerHTML = commandText;
root.console.log('Speech recognized: %c'+commandText, debugStyle);
}
// try and match recognized text to one of the commands on the list
for (var j = 0, l = commandsList.length; j < l; j++) {
var result = commandsList[j].command.exec(commandText);
if (result) {
var parameters = result.slice(1);
if (debugState) {
root.console.log('command matched: %c'+commandsList[j].originalPhrase, debugStyle);
if (parameters.length) {
root.console.log('with parameters', parameters);
}
}
// execute the matched command
commandsList[j].callback.apply(this, parameters);
invokeCallbacks(callbacks.resultMatch);
return true;
}
}
}
invokeCallbacks(callbacks.resultNoMatch);
return false;
};
// build commands list
if (resetCommands) {
commandsList = [];
}
if (commands.length) {
this.addCommands(commands);
}
} | [
"function",
"(",
"commands",
",",
"resetCommands",
")",
"{",
"if",
"(",
"resetCommands",
"===",
"undefined",
")",
"{",
"resetCommands",
"=",
"true",
";",
"}",
"else",
"{",
"resetCommands",
"=",
"!",
"!",
"resetCommands",
";",
"}",
"if",
"(",
"recognition",
"&&",
"recognition",
".",
"abort",
")",
"{",
"recognition",
".",
"abort",
"(",
")",
";",
"}",
"recognition",
"=",
"new",
"SpeechRecognition",
"(",
")",
";",
"recognition",
".",
"maxAlternatives",
"=",
"5",
";",
"recognition",
".",
"continuous",
"=",
"root",
".",
"location",
".",
"protocol",
"===",
"'http:'",
";",
"recognition",
".",
"lang",
"=",
"'en-US'",
";",
"recognition",
".",
"onstart",
"=",
"function",
"(",
")",
"{",
"invokeCallbacks",
"(",
"callbacks",
".",
"start",
")",
";",
"}",
";",
"recognition",
".",
"onerror",
"=",
"function",
"(",
"event",
")",
"{",
"invokeCallbacks",
"(",
"callbacks",
".",
"error",
")",
";",
"switch",
"(",
"event",
".",
"error",
")",
"{",
"case",
"'network'",
":",
"invokeCallbacks",
"(",
"callbacks",
".",
"errorNetwork",
")",
";",
"break",
";",
"case",
"'not-allowed'",
":",
"case",
"'service-not-allowed'",
":",
"autoRestart",
"=",
"false",
";",
"if",
"(",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"-",
"lastStartedAt",
"<",
"200",
")",
"{",
"invokeCallbacks",
"(",
"callbacks",
".",
"errorPermissionBlocked",
")",
";",
"}",
"else",
"{",
"invokeCallbacks",
"(",
"callbacks",
".",
"errorPermissionDenied",
")",
";",
"}",
"break",
";",
"}",
"}",
";",
"recognition",
".",
"onend",
"=",
"function",
"(",
")",
"{",
"invokeCallbacks",
"(",
"callbacks",
".",
"end",
")",
";",
"if",
"(",
"autoRestart",
")",
"{",
"var",
"timeSinceLastStart",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"-",
"lastStartedAt",
";",
"if",
"(",
"timeSinceLastStart",
"<",
"1000",
")",
"{",
"setTimeout",
"(",
"root",
".",
"annyang",
".",
"start",
",",
"1000",
"-",
"timeSinceLastStart",
")",
";",
"}",
"else",
"{",
"root",
".",
"annyang",
".",
"start",
"(",
")",
";",
"}",
"}",
"}",
";",
"recognition",
".",
"onresult",
"=",
"function",
"(",
"event",
")",
"{",
"invokeCallbacks",
"(",
"callbacks",
".",
"result",
")",
";",
"var",
"results",
"=",
"event",
".",
"results",
"[",
"event",
".",
"resultIndex",
"]",
";",
"var",
"commandText",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"results",
".",
"length",
";",
"i",
"++",
")",
"{",
"commandText",
"=",
"results",
"[",
"i",
"]",
".",
"transcript",
".",
"trim",
"(",
")",
";",
"$",
"(",
"'#speechActivity'",
")",
".",
"html",
"(",
"'<h2>Last voice command: '",
"+",
"commandText",
"+",
"'</h2>'",
")",
";",
"if",
"(",
"debugState",
")",
"{",
"root",
".",
"console",
".",
"log",
"(",
"'Speech recognized: %c'",
"+",
"commandText",
",",
"debugStyle",
")",
";",
"}",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"l",
"=",
"commandsList",
".",
"length",
";",
"j",
"<",
"l",
";",
"j",
"++",
")",
"{",
"var",
"result",
"=",
"commandsList",
"[",
"j",
"]",
".",
"command",
".",
"exec",
"(",
"commandText",
")",
";",
"if",
"(",
"result",
")",
"{",
"var",
"parameters",
"=",
"result",
".",
"slice",
"(",
"1",
")",
";",
"if",
"(",
"debugState",
")",
"{",
"root",
".",
"console",
".",
"log",
"(",
"'command matched: %c'",
"+",
"commandsList",
"[",
"j",
"]",
".",
"originalPhrase",
",",
"debugStyle",
")",
";",
"if",
"(",
"parameters",
".",
"length",
")",
"{",
"root",
".",
"console",
".",
"log",
"(",
"'with parameters'",
",",
"parameters",
")",
";",
"}",
"}",
"commandsList",
"[",
"j",
"]",
".",
"callback",
".",
"apply",
"(",
"this",
",",
"parameters",
")",
";",
"invokeCallbacks",
"(",
"callbacks",
".",
"resultMatch",
")",
";",
"return",
"true",
";",
"}",
"}",
"}",
"invokeCallbacks",
"(",
"callbacks",
".",
"resultNoMatch",
")",
";",
"return",
"false",
";",
"}",
";",
"if",
"(",
"resetCommands",
")",
"{",
"commandsList",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"commands",
".",
"length",
")",
"{",
"this",
".",
"addCommands",
"(",
"commands",
")",
";",
"}",
"}"
] | Initialize annyang with a list of commands to recognize.
### Examples:
var commands = {'hello :name': helloFunction};
var commands2 = {'hi': helloFunction};
// initialize annyang, overwriting any previously added commands
annyang.init(commands, true);
// adds an additional command without removing the previous commands
annyang.init(commands2, false);
As of v1.1.0 it is no longer required to call init(). Just start() listening whenever you want, and addCommands() whenever, and as often as you like.
@param {Object} commands - Commands that annyang should listen to
@param {Boolean} [resetCommands=true] - Remove all commands before initializing?
@method init
@deprecated
@see [Commands Object](#commands-object) | [
"Initialize",
"annyang",
"with",
"a",
"list",
"of",
"commands",
"to",
"recognize",
"."
] | 7ab6649dbef2d79722d3b4d538c26db6a200229c | https://github.com/bigcompany/big/blob/7ab6649dbef2d79722d3b4d538c26db6a200229c/apps/voice-recognition/public/speech.js#L102-L211 | train |
|
bigcompany/big | apps/voice-recognition/public/speech.js | function(options) {
initIfNeeded();
options = options || {};
if (options.autoRestart !== undefined) {
autoRestart = !!options.autoRestart;
} else {
autoRestart = true;
}
lastStartedAt = new Date().getTime();
recognition.start();
} | javascript | function(options) {
initIfNeeded();
options = options || {};
if (options.autoRestart !== undefined) {
autoRestart = !!options.autoRestart;
} else {
autoRestart = true;
}
lastStartedAt = new Date().getTime();
recognition.start();
} | [
"function",
"(",
"options",
")",
"{",
"initIfNeeded",
"(",
")",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"options",
".",
"autoRestart",
"!==",
"undefined",
")",
"{",
"autoRestart",
"=",
"!",
"!",
"options",
".",
"autoRestart",
";",
"}",
"else",
"{",
"autoRestart",
"=",
"true",
";",
"}",
"lastStartedAt",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"recognition",
".",
"start",
"(",
")",
";",
"}"
] | Start listening.
It's a good idea to call this after adding some commands first, but not mandatory.
Receives an optional options object which currently only supports one option:
- `autoRestart` (Boolean, default: true) Should annyang restart itself if it is closed indirectly, because of silence or window conflicts?
### Examples:
// Start listening, but don't restart automatically
annyang.start({ autoRestart: false });
@param {Object} [options] - Optional options.
@method start | [
"Start",
"listening",
".",
"It",
"s",
"a",
"good",
"idea",
"to",
"call",
"this",
"after",
"adding",
"some",
"commands",
"first",
"but",
"not",
"mandatory",
"."
] | 7ab6649dbef2d79722d3b4d538c26db6a200229c | https://github.com/bigcompany/big/blob/7ab6649dbef2d79722d3b4d538c26db6a200229c/apps/voice-recognition/public/speech.js#L227-L237 | train |
|
bigcompany/big | apps/voice-recognition/public/speech.js | function(commandsToRemove) {
if (commandsToRemove === undefined) {
commandsList = [];
return;
}
commandsToRemove = Array.isArray(commandsToRemove) ? commandsToRemove : [commandsToRemove];
commandsList = commandsList.filter(function(command) {
for (var i = 0; i<commandsToRemove.length; i++) {
if (commandsToRemove[i] === command.originalPhrase) {
return false;
}
}
return true;
});
} | javascript | function(commandsToRemove) {
if (commandsToRemove === undefined) {
commandsList = [];
return;
}
commandsToRemove = Array.isArray(commandsToRemove) ? commandsToRemove : [commandsToRemove];
commandsList = commandsList.filter(function(command) {
for (var i = 0; i<commandsToRemove.length; i++) {
if (commandsToRemove[i] === command.originalPhrase) {
return false;
}
}
return true;
});
} | [
"function",
"(",
"commandsToRemove",
")",
"{",
"if",
"(",
"commandsToRemove",
"===",
"undefined",
")",
"{",
"commandsList",
"=",
"[",
"]",
";",
"return",
";",
"}",
"commandsToRemove",
"=",
"Array",
".",
"isArray",
"(",
"commandsToRemove",
")",
"?",
"commandsToRemove",
":",
"[",
"commandsToRemove",
"]",
";",
"commandsList",
"=",
"commandsList",
".",
"filter",
"(",
"function",
"(",
"command",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"commandsToRemove",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"commandsToRemove",
"[",
"i",
"]",
"===",
"command",
".",
"originalPhrase",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}",
")",
";",
"}"
] | Remove existing commands. Called with a single phrase, array of phrases, or methodically. Pass no params to remove all commands.
### Examples:
var commands = {'hello': helloFunction, 'howdy': helloFunction, 'hi': helloFunction};
// Remove all existing commands
annyang.removeCommands();
// Add some commands
annyang.addCommands(commands);
// Don't respond to hello
annyang.removeCommands('hello');
// Don't respond to howdy or hi
annyang.removeCommands(['howdy', 'hi']);
@param {String|Array|Undefined} [commandsToRemove] - Commands to remove
@method removeCommands | [
"Remove",
"existing",
"commands",
".",
"Called",
"with",
"a",
"single",
"phrase",
"array",
"of",
"phrases",
"or",
"methodically",
".",
"Pass",
"no",
"params",
"to",
"remove",
"all",
"commands",
"."
] | 7ab6649dbef2d79722d3b4d538c26db6a200229c | https://github.com/bigcompany/big/blob/7ab6649dbef2d79722d3b4d538c26db6a200229c/apps/voice-recognition/public/speech.js#L339-L353 | train |
|
magemello/license-check | index.js | start | function start(config) {
if (!isConfigurationParametersDefinedCorrectly(config)) {
throw new Error('license-check - Configuration error');
}
var folders = [];
if (config.src) {
folders = getFoldersToCheck(config.src);
}
if (folders.length === 0) {
gutil.log('license-check', gutil.colors.red('{src} not defined or empty, the plugin will run with the default configuration: **/*'));
folders = getDefaultFolders();
}
var src = vfs.src(folders);
src.pipe(license(config));
return src;
} | javascript | function start(config) {
if (!isConfigurationParametersDefinedCorrectly(config)) {
throw new Error('license-check - Configuration error');
}
var folders = [];
if (config.src) {
folders = getFoldersToCheck(config.src);
}
if (folders.length === 0) {
gutil.log('license-check', gutil.colors.red('{src} not defined or empty, the plugin will run with the default configuration: **/*'));
folders = getDefaultFolders();
}
var src = vfs.src(folders);
src.pipe(license(config));
return src;
} | [
"function",
"start",
"(",
"config",
")",
"{",
"if",
"(",
"!",
"isConfigurationParametersDefinedCorrectly",
"(",
"config",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'license-check - Configuration error'",
")",
";",
"}",
"var",
"folders",
"=",
"[",
"]",
";",
"if",
"(",
"config",
".",
"src",
")",
"{",
"folders",
"=",
"getFoldersToCheck",
"(",
"config",
".",
"src",
")",
";",
"}",
"if",
"(",
"folders",
".",
"length",
"===",
"0",
")",
"{",
"gutil",
".",
"log",
"(",
"'license-check'",
",",
"gutil",
".",
"colors",
".",
"red",
"(",
"'{src} not defined or empty, the plugin will run with the default configuration: **/*'",
")",
")",
";",
"folders",
"=",
"getDefaultFolders",
"(",
")",
";",
"}",
"var",
"src",
"=",
"vfs",
".",
"src",
"(",
"folders",
")",
";",
"src",
".",
"pipe",
"(",
"license",
"(",
"config",
")",
")",
";",
"return",
"src",
";",
"}"
] | Main execution function
@returns {object} return the stream to make possible append pipe or listen on channel such on('data') on('error) . | [
"Main",
"execution",
"function"
] | a53ec538e1958ef64923fd3afc9747330e1235b7 | https://github.com/magemello/license-check/blob/a53ec538e1958ef64923fd3afc9747330e1235b7/index.js#L32-L50 | train |
magemello/license-check | index.js | getFoldersToCheck | function getFoldersToCheck(src) {
var folders = [];
src.forEach(function (entry) {
if (entry.charAt(0) === '!') {
folders.push(path.join('!' + mainFolder, entry.substring(1, entry.length)));
} else {
if (entry.charAt(0) === '/') {
folders.push(entry);
} else {
folders.push(path.join(mainFolder, entry));
}
}
});
return folders;
} | javascript | function getFoldersToCheck(src) {
var folders = [];
src.forEach(function (entry) {
if (entry.charAt(0) === '!') {
folders.push(path.join('!' + mainFolder, entry.substring(1, entry.length)));
} else {
if (entry.charAt(0) === '/') {
folders.push(entry);
} else {
folders.push(path.join(mainFolder, entry));
}
}
});
return folders;
} | [
"function",
"getFoldersToCheck",
"(",
"src",
")",
"{",
"var",
"folders",
"=",
"[",
"]",
";",
"src",
".",
"forEach",
"(",
"function",
"(",
"entry",
")",
"{",
"if",
"(",
"entry",
".",
"charAt",
"(",
"0",
")",
"===",
"'!'",
")",
"{",
"folders",
".",
"push",
"(",
"path",
".",
"join",
"(",
"'!'",
"+",
"mainFolder",
",",
"entry",
".",
"substring",
"(",
"1",
",",
"entry",
".",
"length",
")",
")",
")",
";",
"}",
"else",
"{",
"if",
"(",
"entry",
".",
"charAt",
"(",
"0",
")",
"===",
"'/'",
")",
"{",
"folders",
".",
"push",
"(",
"entry",
")",
";",
"}",
"else",
"{",
"folders",
".",
"push",
"(",
"path",
".",
"join",
"(",
"mainFolder",
",",
"entry",
")",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"folders",
";",
"}"
] | Return all the folders that the plugin have to check. Because the plugin is inside the node_modules
folder, we prepended to all the path the absolute path of the main context of execution.
@param {object} src - Path of the files you want to be checked by the plugin.
@returns {string[]} Path of the files you want to be checked by the plugin with the absolute path of the context prepended. | [
"Return",
"all",
"the",
"folders",
"that",
"the",
"plugin",
"have",
"to",
"check",
".",
"Because",
"the",
"plugin",
"is",
"inside",
"the",
"node_modules",
"folder",
"we",
"prepended",
"to",
"all",
"the",
"path",
"the",
"absolute",
"path",
"of",
"the",
"main",
"context",
"of",
"execution",
"."
] | a53ec538e1958ef64923fd3afc9747330e1235b7 | https://github.com/magemello/license-check/blob/a53ec538e1958ef64923fd3afc9747330e1235b7/index.js#L60-L75 | train |
magemello/license-check | index.js | isConfigurationParametersDefinedCorrectly | function isConfigurationParametersDefinedCorrectly(config) {
if (!config) {
gutil.log('license-check', gutil.colors.red('Config must be defined to run the plugin'));
return false;
}
if (!config.path) {
gutil.log('license-check', gutil.colors.red('License header property {path} must be defined to run the plugin'));
return false;
}
return true;
} | javascript | function isConfigurationParametersDefinedCorrectly(config) {
if (!config) {
gutil.log('license-check', gutil.colors.red('Config must be defined to run the plugin'));
return false;
}
if (!config.path) {
gutil.log('license-check', gutil.colors.red('License header property {path} must be defined to run the plugin'));
return false;
}
return true;
} | [
"function",
"isConfigurationParametersDefinedCorrectly",
"(",
"config",
")",
"{",
"if",
"(",
"!",
"config",
")",
"{",
"gutil",
".",
"log",
"(",
"'license-check'",
",",
"gutil",
".",
"colors",
".",
"red",
"(",
"'Config must be defined to run the plugin'",
")",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"config",
".",
"path",
")",
"{",
"gutil",
".",
"log",
"(",
"'license-check'",
",",
"gutil",
".",
"colors",
".",
"red",
"(",
"'License header property {path} must be defined to run the plugin'",
")",
")",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Check that the configuration parameter are setted correctly.
@param {object} config - plugin configurations.
@returns {boolean} return true if the parameters are set correctly. | [
"Check",
"that",
"the",
"configuration",
"parameter",
"are",
"setted",
"correctly",
"."
] | a53ec538e1958ef64923fd3afc9747330e1235b7 | https://github.com/magemello/license-check/blob/a53ec538e1958ef64923fd3afc9747330e1235b7/index.js#L96-L108 | train |
infrabel/themes-gnap | raw/angular-datatables/angular-datatables.js | function (obj) {
this.obj = obj;
/**
* Check if the wrapped object is defined
* @returns true if the wrapped object is defined, false otherwise
*/
this.isPresent = function () {
return angular.isDefined(this.obj) && this.obj !== null;
};
/**
* Return the wrapped object or an empty object
* @returns the wrapped objector an empty object
*/
this.orEmptyObj = function () {
if (this.isPresent()) {
return this.obj;
}
return {};
};
/**
* Return the wrapped object or the given second choice
* @returns the wrapped object or the given second choice
*/
this.or = function (secondChoice) {
if (this.isPresent()) {
return this.obj;
}
return secondChoice;
};
} | javascript | function (obj) {
this.obj = obj;
/**
* Check if the wrapped object is defined
* @returns true if the wrapped object is defined, false otherwise
*/
this.isPresent = function () {
return angular.isDefined(this.obj) && this.obj !== null;
};
/**
* Return the wrapped object or an empty object
* @returns the wrapped objector an empty object
*/
this.orEmptyObj = function () {
if (this.isPresent()) {
return this.obj;
}
return {};
};
/**
* Return the wrapped object or the given second choice
* @returns the wrapped object or the given second choice
*/
this.or = function (secondChoice) {
if (this.isPresent()) {
return this.obj;
}
return secondChoice;
};
} | [
"function",
"(",
"obj",
")",
"{",
"this",
".",
"obj",
"=",
"obj",
";",
"this",
".",
"isPresent",
"=",
"function",
"(",
")",
"{",
"return",
"angular",
".",
"isDefined",
"(",
"this",
".",
"obj",
")",
"&&",
"this",
".",
"obj",
"!==",
"null",
";",
"}",
";",
"this",
".",
"orEmptyObj",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"isPresent",
"(",
")",
")",
"{",
"return",
"this",
".",
"obj",
";",
"}",
"return",
"{",
"}",
";",
"}",
";",
"this",
".",
"or",
"=",
"function",
"(",
"secondChoice",
")",
"{",
"if",
"(",
"this",
".",
"isPresent",
"(",
")",
")",
"{",
"return",
"this",
".",
"obj",
";",
"}",
"return",
"secondChoice",
";",
"}",
";",
"}"
] | Optional class to handle undefined or null
@param obj the object to wrap | [
"Optional",
"class",
"to",
"handle",
"undefined",
"or",
"null"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/angular-datatables/angular-datatables.js#L435-L464 | train |
|
infrabel/themes-gnap | raw/angular-datatables/angular-datatables.js | function (options) {
return {
options: options,
render: function ($scope, $elem) {
var _this = this, expression = $elem.find('tbody').html(),
// Find the resources from the comment <!-- ngRepeat: item in items --> displayed by angular in the DOM
// This regexp is inspired by the one used in the "ngRepeat" directive
match = expression.match(/^\s*.+\s+in\s+(\w*)\s*/), ngRepeatAttr = match[1];
if (!match) {
throw new Error('Expected expression in form of "_item_ in _collection_[ track by _id_]" but got "{0}".', expression);
}
var oTable, firstCall = true, alreadyRendered = false, parentScope = $scope.$parent;
parentScope.$watch(ngRepeatAttr, function () {
if (oTable && alreadyRendered && !_isDTOldVersion(oTable)) {
oTable.ngDestroy();
}
// This condition handles the case the array is empty
if (firstCall) {
firstCall = false;
$timeout(function () {
if (!alreadyRendered) {
oTable = _doRenderDataTable($elem, _this.options, $scope);
alreadyRendered = true;
}
}, 1000, false); // Hack I'm not proud of... Don't know how to do it otherwise...
} else {
$timeout(function () {
oTable = _doRenderDataTable($elem, _this.options, $scope);
alreadyRendered = true;
}, 0, false);
}
}, true);
}
};
} | javascript | function (options) {
return {
options: options,
render: function ($scope, $elem) {
var _this = this, expression = $elem.find('tbody').html(),
// Find the resources from the comment <!-- ngRepeat: item in items --> displayed by angular in the DOM
// This regexp is inspired by the one used in the "ngRepeat" directive
match = expression.match(/^\s*.+\s+in\s+(\w*)\s*/), ngRepeatAttr = match[1];
if (!match) {
throw new Error('Expected expression in form of "_item_ in _collection_[ track by _id_]" but got "{0}".', expression);
}
var oTable, firstCall = true, alreadyRendered = false, parentScope = $scope.$parent;
parentScope.$watch(ngRepeatAttr, function () {
if (oTable && alreadyRendered && !_isDTOldVersion(oTable)) {
oTable.ngDestroy();
}
// This condition handles the case the array is empty
if (firstCall) {
firstCall = false;
$timeout(function () {
if (!alreadyRendered) {
oTable = _doRenderDataTable($elem, _this.options, $scope);
alreadyRendered = true;
}
}, 1000, false); // Hack I'm not proud of... Don't know how to do it otherwise...
} else {
$timeout(function () {
oTable = _doRenderDataTable($elem, _this.options, $scope);
alreadyRendered = true;
}, 0, false);
}
}, true);
}
};
} | [
"function",
"(",
"options",
")",
"{",
"return",
"{",
"options",
":",
"options",
",",
"render",
":",
"function",
"(",
"$scope",
",",
"$elem",
")",
"{",
"var",
"_this",
"=",
"this",
",",
"expression",
"=",
"$elem",
".",
"find",
"(",
"'tbody'",
")",
".",
"html",
"(",
")",
",",
"match",
"=",
"expression",
".",
"match",
"(",
"/",
"^\\s*.+\\s+in\\s+(\\w*)\\s*",
"/",
")",
",",
"ngRepeatAttr",
"=",
"match",
"[",
"1",
"]",
";",
"if",
"(",
"!",
"match",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Expected expression in form of \"_item_ in _collection_[ track by _id_]\" but got \"{0}\".'",
",",
"expression",
")",
";",
"}",
"var",
"oTable",
",",
"firstCall",
"=",
"true",
",",
"alreadyRendered",
"=",
"false",
",",
"parentScope",
"=",
"$scope",
".",
"$parent",
";",
"parentScope",
".",
"$watch",
"(",
"ngRepeatAttr",
",",
"function",
"(",
")",
"{",
"if",
"(",
"oTable",
"&&",
"alreadyRendered",
"&&",
"!",
"_isDTOldVersion",
"(",
"oTable",
")",
")",
"{",
"oTable",
".",
"ngDestroy",
"(",
")",
";",
"}",
"if",
"(",
"firstCall",
")",
"{",
"firstCall",
"=",
"false",
";",
"$timeout",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"alreadyRendered",
")",
"{",
"oTable",
"=",
"_doRenderDataTable",
"(",
"$elem",
",",
"_this",
".",
"options",
",",
"$scope",
")",
";",
"alreadyRendered",
"=",
"true",
";",
"}",
"}",
",",
"1000",
",",
"false",
")",
";",
"}",
"else",
"{",
"$timeout",
"(",
"function",
"(",
")",
"{",
"oTable",
"=",
"_doRenderDataTable",
"(",
"$elem",
",",
"_this",
".",
"options",
",",
"$scope",
")",
";",
"alreadyRendered",
"=",
"true",
";",
"}",
",",
"0",
",",
"false",
")",
";",
"}",
"}",
",",
"true",
")",
";",
"}",
"}",
";",
"}"
] | Renderer for displaying the Angular way
@param options
@returns {{options: *}} the renderer
@constructor | [
"Renderer",
"for",
"displaying",
"the",
"Angular",
"way"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/angular-datatables/angular-datatables.js#L912-L946 | train |
|
infrabel/themes-gnap | raw/angular-datatables/angular-datatables.js | function (options) {
var oTable;
var _render = function (options, $elem, data, $scope) {
options.aaData = data;
// Add $timeout to be sure that angular has finished rendering before calling datatables
$timeout(function () {
_hideLoading($elem);
// Set it to true in order to be able to redraw the dataTable
options.bDestroy = true;
// Condition to refresh the dataTable
if (oTable) {
if (_isDTOldVersion(oTable)) {
oTable.fnClearTable();
oTable.fnDraw();
oTable.fnAddData(options.aaData);
} else {
oTable.clear();
oTable.rows.add(options.aaData).draw();
}
} else {
oTable = _renderDataTableAndEmitEvent($elem, options, $scope);
}
}, 0, false);
};
return {
options: options,
render: function ($scope, $elem) {
var _this = this, _loadedPromise = null, _whenLoaded = function (data) {
_render(_this.options, $elem, data, $scope);
_loadedPromise = null;
}, _startLoading = function (fnPromise) {
if (angular.isFunction(fnPromise)) {
_loadedPromise = fnPromise();
} else {
_loadedPromise = fnPromise;
}
_showLoading($elem);
_loadedPromise.then(_whenLoaded);
}, _reload = function (fnPromise) {
if (_loadedPromise) {
_loadedPromise.then(function () {
_startLoading(fnPromise);
});
} else {
_startLoading(fnPromise);
}
};
$scope.$watch('dtOptions.fnPromise', function (fnPromise) {
if (angular.isDefined(fnPromise)) {
_reload(fnPromise);
} else {
throw new Error('You must provide a promise or a function that returns a promise!');
}
});
$scope.$watch('dtOptions.reload', function (reload) {
if (reload) {
$scope.dtOptions.reload = false;
_reload($scope.dtOptions.fnPromise);
}
});
}
};
} | javascript | function (options) {
var oTable;
var _render = function (options, $elem, data, $scope) {
options.aaData = data;
// Add $timeout to be sure that angular has finished rendering before calling datatables
$timeout(function () {
_hideLoading($elem);
// Set it to true in order to be able to redraw the dataTable
options.bDestroy = true;
// Condition to refresh the dataTable
if (oTable) {
if (_isDTOldVersion(oTable)) {
oTable.fnClearTable();
oTable.fnDraw();
oTable.fnAddData(options.aaData);
} else {
oTable.clear();
oTable.rows.add(options.aaData).draw();
}
} else {
oTable = _renderDataTableAndEmitEvent($elem, options, $scope);
}
}, 0, false);
};
return {
options: options,
render: function ($scope, $elem) {
var _this = this, _loadedPromise = null, _whenLoaded = function (data) {
_render(_this.options, $elem, data, $scope);
_loadedPromise = null;
}, _startLoading = function (fnPromise) {
if (angular.isFunction(fnPromise)) {
_loadedPromise = fnPromise();
} else {
_loadedPromise = fnPromise;
}
_showLoading($elem);
_loadedPromise.then(_whenLoaded);
}, _reload = function (fnPromise) {
if (_loadedPromise) {
_loadedPromise.then(function () {
_startLoading(fnPromise);
});
} else {
_startLoading(fnPromise);
}
};
$scope.$watch('dtOptions.fnPromise', function (fnPromise) {
if (angular.isDefined(fnPromise)) {
_reload(fnPromise);
} else {
throw new Error('You must provide a promise or a function that returns a promise!');
}
});
$scope.$watch('dtOptions.reload', function (reload) {
if (reload) {
$scope.dtOptions.reload = false;
_reload($scope.dtOptions.fnPromise);
}
});
}
};
} | [
"function",
"(",
"options",
")",
"{",
"var",
"oTable",
";",
"var",
"_render",
"=",
"function",
"(",
"options",
",",
"$elem",
",",
"data",
",",
"$scope",
")",
"{",
"options",
".",
"aaData",
"=",
"data",
";",
"$timeout",
"(",
"function",
"(",
")",
"{",
"_hideLoading",
"(",
"$elem",
")",
";",
"options",
".",
"bDestroy",
"=",
"true",
";",
"if",
"(",
"oTable",
")",
"{",
"if",
"(",
"_isDTOldVersion",
"(",
"oTable",
")",
")",
"{",
"oTable",
".",
"fnClearTable",
"(",
")",
";",
"oTable",
".",
"fnDraw",
"(",
")",
";",
"oTable",
".",
"fnAddData",
"(",
"options",
".",
"aaData",
")",
";",
"}",
"else",
"{",
"oTable",
".",
"clear",
"(",
")",
";",
"oTable",
".",
"rows",
".",
"add",
"(",
"options",
".",
"aaData",
")",
".",
"draw",
"(",
")",
";",
"}",
"}",
"else",
"{",
"oTable",
"=",
"_renderDataTableAndEmitEvent",
"(",
"$elem",
",",
"options",
",",
"$scope",
")",
";",
"}",
"}",
",",
"0",
",",
"false",
")",
";",
"}",
";",
"return",
"{",
"options",
":",
"options",
",",
"render",
":",
"function",
"(",
"$scope",
",",
"$elem",
")",
"{",
"var",
"_this",
"=",
"this",
",",
"_loadedPromise",
"=",
"null",
",",
"_whenLoaded",
"=",
"function",
"(",
"data",
")",
"{",
"_render",
"(",
"_this",
".",
"options",
",",
"$elem",
",",
"data",
",",
"$scope",
")",
";",
"_loadedPromise",
"=",
"null",
";",
"}",
",",
"_startLoading",
"=",
"function",
"(",
"fnPromise",
")",
"{",
"if",
"(",
"angular",
".",
"isFunction",
"(",
"fnPromise",
")",
")",
"{",
"_loadedPromise",
"=",
"fnPromise",
"(",
")",
";",
"}",
"else",
"{",
"_loadedPromise",
"=",
"fnPromise",
";",
"}",
"_showLoading",
"(",
"$elem",
")",
";",
"_loadedPromise",
".",
"then",
"(",
"_whenLoaded",
")",
";",
"}",
",",
"_reload",
"=",
"function",
"(",
"fnPromise",
")",
"{",
"if",
"(",
"_loadedPromise",
")",
"{",
"_loadedPromise",
".",
"then",
"(",
"function",
"(",
")",
"{",
"_startLoading",
"(",
"fnPromise",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"_startLoading",
"(",
"fnPromise",
")",
";",
"}",
"}",
";",
"$scope",
".",
"$watch",
"(",
"'dtOptions.fnPromise'",
",",
"function",
"(",
"fnPromise",
")",
"{",
"if",
"(",
"angular",
".",
"isDefined",
"(",
"fnPromise",
")",
")",
"{",
"_reload",
"(",
"fnPromise",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'You must provide a promise or a function that returns a promise!'",
")",
";",
"}",
"}",
")",
";",
"$scope",
".",
"$watch",
"(",
"'dtOptions.reload'",
",",
"function",
"(",
"reload",
")",
"{",
"if",
"(",
"reload",
")",
"{",
"$scope",
".",
"dtOptions",
".",
"reload",
"=",
"false",
";",
"_reload",
"(",
"$scope",
".",
"dtOptions",
".",
"fnPromise",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
";",
"}"
] | Renderer for displaying with a promise
@param options the options
@returns {{options: *}} the renderer
@constructor | [
"Renderer",
"for",
"displaying",
"with",
"a",
"promise"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/angular-datatables/angular-datatables.js#L953-L1015 | train |
|
infrabel/themes-gnap | raw/angular-datatables/angular-datatables.js | function (options) {
var oTable;
var _render = function (options, $elem, $scope) {
// Set it to true in order to be able to redraw the dataTable
options.bDestroy = true;
// Add $timeout to be sure that angular has finished rendering before calling datatables
$timeout(function () {
_hideLoading($elem);
// Condition to refresh the dataTable
if (oTable) {
if (_hasReloadAjaxPlugin(oTable)) {
// Reload Ajax data using the plugin "fnReloadAjax": https://next.datatables.net/plug-ins/api/fnReloadAjax
// For DataTable v1.9.4
oTable.fnReloadAjax(options.sAjaxSource);
} else if (!_isDTOldVersion(oTable)) {
// For DataTable v1.10+, DT provides methods https://datatables.net/reference/api/ajax.url()
var ajaxUrl = options.sAjaxSource || options.ajax.url || options.ajax;
oTable.ajax.url(ajaxUrl).load();
} else {
throw new Error('Reload Ajax not supported. Please use the plugin "fnReloadAjax" (https://next.datatables.net/plug-ins/api/fnReloadAjax) or use a more recent version of DataTables (v1.10+)');
}
} else {
oTable = _renderDataTableAndEmitEvent($elem, options, $scope);
}
}, 0, false);
};
return {
options: options,
render: function ($scope, $elem) {
var _this = this;
// Define default values in case it is an ajax datatables
if (angular.isUndefined(_this.options.sAjaxDataProp)) {
_this.options.sAjaxDataProp = DT_DEFAULT_OPTIONS.sAjaxDataProp;
}
if (angular.isUndefined(_this.options.aoColumns)) {
_this.options.aoColumns = DT_DEFAULT_OPTIONS.aoColumns;
}
$scope.$watch('dtOptions.sAjaxSource', function (sAjaxSource) {
if (angular.isDefined(sAjaxSource)) {
_this.options.sAjaxSource = sAjaxSource;
if (angular.isDefined(_this.options.ajax)) {
if (angular.isObject(_this.options.ajax)) {
_this.options.ajax.url = sAjaxSource;
} else {
_this.options.ajax = { url: sAjaxSource };
}
}
}
_render(options, $elem, $scope);
});
$scope.$watch('dtOptions.reload', function (reload) {
if (reload) {
$scope.dtOptions.reload = false;
_render(options, $elem, $scope);
}
});
}
};
} | javascript | function (options) {
var oTable;
var _render = function (options, $elem, $scope) {
// Set it to true in order to be able to redraw the dataTable
options.bDestroy = true;
// Add $timeout to be sure that angular has finished rendering before calling datatables
$timeout(function () {
_hideLoading($elem);
// Condition to refresh the dataTable
if (oTable) {
if (_hasReloadAjaxPlugin(oTable)) {
// Reload Ajax data using the plugin "fnReloadAjax": https://next.datatables.net/plug-ins/api/fnReloadAjax
// For DataTable v1.9.4
oTable.fnReloadAjax(options.sAjaxSource);
} else if (!_isDTOldVersion(oTable)) {
// For DataTable v1.10+, DT provides methods https://datatables.net/reference/api/ajax.url()
var ajaxUrl = options.sAjaxSource || options.ajax.url || options.ajax;
oTable.ajax.url(ajaxUrl).load();
} else {
throw new Error('Reload Ajax not supported. Please use the plugin "fnReloadAjax" (https://next.datatables.net/plug-ins/api/fnReloadAjax) or use a more recent version of DataTables (v1.10+)');
}
} else {
oTable = _renderDataTableAndEmitEvent($elem, options, $scope);
}
}, 0, false);
};
return {
options: options,
render: function ($scope, $elem) {
var _this = this;
// Define default values in case it is an ajax datatables
if (angular.isUndefined(_this.options.sAjaxDataProp)) {
_this.options.sAjaxDataProp = DT_DEFAULT_OPTIONS.sAjaxDataProp;
}
if (angular.isUndefined(_this.options.aoColumns)) {
_this.options.aoColumns = DT_DEFAULT_OPTIONS.aoColumns;
}
$scope.$watch('dtOptions.sAjaxSource', function (sAjaxSource) {
if (angular.isDefined(sAjaxSource)) {
_this.options.sAjaxSource = sAjaxSource;
if (angular.isDefined(_this.options.ajax)) {
if (angular.isObject(_this.options.ajax)) {
_this.options.ajax.url = sAjaxSource;
} else {
_this.options.ajax = { url: sAjaxSource };
}
}
}
_render(options, $elem, $scope);
});
$scope.$watch('dtOptions.reload', function (reload) {
if (reload) {
$scope.dtOptions.reload = false;
_render(options, $elem, $scope);
}
});
}
};
} | [
"function",
"(",
"options",
")",
"{",
"var",
"oTable",
";",
"var",
"_render",
"=",
"function",
"(",
"options",
",",
"$elem",
",",
"$scope",
")",
"{",
"options",
".",
"bDestroy",
"=",
"true",
";",
"$timeout",
"(",
"function",
"(",
")",
"{",
"_hideLoading",
"(",
"$elem",
")",
";",
"if",
"(",
"oTable",
")",
"{",
"if",
"(",
"_hasReloadAjaxPlugin",
"(",
"oTable",
")",
")",
"{",
"oTable",
".",
"fnReloadAjax",
"(",
"options",
".",
"sAjaxSource",
")",
";",
"}",
"else",
"if",
"(",
"!",
"_isDTOldVersion",
"(",
"oTable",
")",
")",
"{",
"var",
"ajaxUrl",
"=",
"options",
".",
"sAjaxSource",
"||",
"options",
".",
"ajax",
".",
"url",
"||",
"options",
".",
"ajax",
";",
"oTable",
".",
"ajax",
".",
"url",
"(",
"ajaxUrl",
")",
".",
"load",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Reload Ajax not supported. Please use the plugin \"fnReloadAjax\" (https://next.datatables.net/plug-ins/api/fnReloadAjax) or use a more recent version of DataTables (v1.10+)'",
")",
";",
"}",
"}",
"else",
"{",
"oTable",
"=",
"_renderDataTableAndEmitEvent",
"(",
"$elem",
",",
"options",
",",
"$scope",
")",
";",
"}",
"}",
",",
"0",
",",
"false",
")",
";",
"}",
";",
"return",
"{",
"options",
":",
"options",
",",
"render",
":",
"function",
"(",
"$scope",
",",
"$elem",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"if",
"(",
"angular",
".",
"isUndefined",
"(",
"_this",
".",
"options",
".",
"sAjaxDataProp",
")",
")",
"{",
"_this",
".",
"options",
".",
"sAjaxDataProp",
"=",
"DT_DEFAULT_OPTIONS",
".",
"sAjaxDataProp",
";",
"}",
"if",
"(",
"angular",
".",
"isUndefined",
"(",
"_this",
".",
"options",
".",
"aoColumns",
")",
")",
"{",
"_this",
".",
"options",
".",
"aoColumns",
"=",
"DT_DEFAULT_OPTIONS",
".",
"aoColumns",
";",
"}",
"$scope",
".",
"$watch",
"(",
"'dtOptions.sAjaxSource'",
",",
"function",
"(",
"sAjaxSource",
")",
"{",
"if",
"(",
"angular",
".",
"isDefined",
"(",
"sAjaxSource",
")",
")",
"{",
"_this",
".",
"options",
".",
"sAjaxSource",
"=",
"sAjaxSource",
";",
"if",
"(",
"angular",
".",
"isDefined",
"(",
"_this",
".",
"options",
".",
"ajax",
")",
")",
"{",
"if",
"(",
"angular",
".",
"isObject",
"(",
"_this",
".",
"options",
".",
"ajax",
")",
")",
"{",
"_this",
".",
"options",
".",
"ajax",
".",
"url",
"=",
"sAjaxSource",
";",
"}",
"else",
"{",
"_this",
".",
"options",
".",
"ajax",
"=",
"{",
"url",
":",
"sAjaxSource",
"}",
";",
"}",
"}",
"}",
"_render",
"(",
"options",
",",
"$elem",
",",
"$scope",
")",
";",
"}",
")",
";",
"$scope",
".",
"$watch",
"(",
"'dtOptions.reload'",
",",
"function",
"(",
"reload",
")",
"{",
"if",
"(",
"reload",
")",
"{",
"$scope",
".",
"dtOptions",
".",
"reload",
"=",
"false",
";",
"_render",
"(",
"options",
",",
"$elem",
",",
"$scope",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
";",
"}"
] | Renderer for displaying with Ajax
@param options the options
@returns {{options: *}} the renderer
@constructor | [
"Renderer",
"for",
"displaying",
"with",
"Ajax"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/angular-datatables/angular-datatables.js#L1022-L1080 | train |
|
chriszarate/supergenpass-lib | src/lib/hostname.js | removeSubdomains | function removeSubdomains(hostname) {
const hostnameParts = hostname.split('.');
// A hostname with less than three parts is as short as it will get.
if (hostnameParts.length < 2) {
return hostname;
}
// Try to find a match in the list of ccTLDs.
const ccTld = find(tldList, part => endsWith(hostname, `.${part}`));
if (ccTld) {
// Get one extra part from the hostname.
const partCount = ccTld.split('.').length + 1;
return hostnameParts.slice(0 - partCount).join('.');
}
// If no ccTLDs were matched, return the final two parts of the hostname.
return hostnameParts.slice(-2).join('.');
} | javascript | function removeSubdomains(hostname) {
const hostnameParts = hostname.split('.');
// A hostname with less than three parts is as short as it will get.
if (hostnameParts.length < 2) {
return hostname;
}
// Try to find a match in the list of ccTLDs.
const ccTld = find(tldList, part => endsWith(hostname, `.${part}`));
if (ccTld) {
// Get one extra part from the hostname.
const partCount = ccTld.split('.').length + 1;
return hostnameParts.slice(0 - partCount).join('.');
}
// If no ccTLDs were matched, return the final two parts of the hostname.
return hostnameParts.slice(-2).join('.');
} | [
"function",
"removeSubdomains",
"(",
"hostname",
")",
"{",
"const",
"hostnameParts",
"=",
"hostname",
".",
"split",
"(",
"'.'",
")",
";",
"if",
"(",
"hostnameParts",
".",
"length",
"<",
"2",
")",
"{",
"return",
"hostname",
";",
"}",
"const",
"ccTld",
"=",
"find",
"(",
"tldList",
",",
"part",
"=>",
"endsWith",
"(",
"hostname",
",",
"`",
"${",
"part",
"}",
"`",
")",
")",
";",
"if",
"(",
"ccTld",
")",
"{",
"const",
"partCount",
"=",
"ccTld",
".",
"split",
"(",
"'.'",
")",
".",
"length",
"+",
"1",
";",
"return",
"hostnameParts",
".",
"slice",
"(",
"0",
"-",
"partCount",
")",
".",
"join",
"(",
"'.'",
")",
";",
"}",
"return",
"hostnameParts",
".",
"slice",
"(",
"-",
"2",
")",
".",
"join",
"(",
"'.'",
")",
";",
"}"
] | Remove subdomains while respecting a number of secondary ccTLDs. | [
"Remove",
"subdomains",
"while",
"respecting",
"a",
"number",
"of",
"secondary",
"ccTLDs",
"."
] | eb9ee92050813d498229bfe0e6ccbcb87124cf90 | https://github.com/chriszarate/supergenpass-lib/blob/eb9ee92050813d498229bfe0e6ccbcb87124cf90/src/lib/hostname.js#L13-L31 | train |
chriszarate/supergenpass-lib | src/lib/hostname.js | getHostname | function getHostname(url, userOptions = {}) {
const defaults = {
removeSubdomains: true,
};
const options = Object.assign({}, defaults, userOptions);
const domainRegExp = /^(?:[a-z]+:\/\/)?(?:[^/@]+@)?([^/:]+)/i;
const ipAddressRegExp = /^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/;
const domainMatch = url.match(domainRegExp);
if (domainMatch === null) {
throw new Error(`URL is invalid: ${url}`);
}
// If the hostname is an IP address, no further processing can be done.
const hostname = domainMatch[1];
if (ipAddressRegExp.test(hostname)) {
return hostname;
}
// Return the hostname with subdomains removed, if requested.
return (options.removeSubdomains) ? removeSubdomains(hostname) : hostname;
} | javascript | function getHostname(url, userOptions = {}) {
const defaults = {
removeSubdomains: true,
};
const options = Object.assign({}, defaults, userOptions);
const domainRegExp = /^(?:[a-z]+:\/\/)?(?:[^/@]+@)?([^/:]+)/i;
const ipAddressRegExp = /^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/;
const domainMatch = url.match(domainRegExp);
if (domainMatch === null) {
throw new Error(`URL is invalid: ${url}`);
}
// If the hostname is an IP address, no further processing can be done.
const hostname = domainMatch[1];
if (ipAddressRegExp.test(hostname)) {
return hostname;
}
// Return the hostname with subdomains removed, if requested.
return (options.removeSubdomains) ? removeSubdomains(hostname) : hostname;
} | [
"function",
"getHostname",
"(",
"url",
",",
"userOptions",
"=",
"{",
"}",
")",
"{",
"const",
"defaults",
"=",
"{",
"removeSubdomains",
":",
"true",
",",
"}",
";",
"const",
"options",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"defaults",
",",
"userOptions",
")",
";",
"const",
"domainRegExp",
"=",
"/",
"^(?:[a-z]+:\\/\\/)?(?:[^/@]+@)?([^/:]+)",
"/",
"i",
";",
"const",
"ipAddressRegExp",
"=",
"/",
"^\\d{1,3}\\.\\d{1,3}.\\d{1,3}\\.\\d{1,3}$",
"/",
";",
"const",
"domainMatch",
"=",
"url",
".",
"match",
"(",
"domainRegExp",
")",
";",
"if",
"(",
"domainMatch",
"===",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"url",
"}",
"`",
")",
";",
"}",
"const",
"hostname",
"=",
"domainMatch",
"[",
"1",
"]",
";",
"if",
"(",
"ipAddressRegExp",
".",
"test",
"(",
"hostname",
")",
")",
"{",
"return",
"hostname",
";",
"}",
"return",
"(",
"options",
".",
"removeSubdomains",
")",
"?",
"removeSubdomains",
"(",
"hostname",
")",
":",
"hostname",
";",
"}"
] | Isolate the domain name of a URL. | [
"Isolate",
"the",
"domain",
"name",
"of",
"a",
"URL",
"."
] | eb9ee92050813d498229bfe0e6ccbcb87124cf90 | https://github.com/chriszarate/supergenpass-lib/blob/eb9ee92050813d498229bfe0e6ccbcb87124cf90/src/lib/hostname.js#L34-L55 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/x-editable/ace-editable.js | function() {
var self = this;
this.$input = this.$tpl.find('input[type=hidden]:eq(0)');
this.$file = this.$tpl.find('input[type=file]:eq(0)');
this.$file.attr({'name':this.name});
this.$input.attr({'name':this.name+'-hidden'});
this.options.image.before_change = this.options.image.before_change || function(files, dropped) {
var file = files[0];
if(typeof file === "string") {
//files is just a file name here (in browsers that don't support FileReader API)
if(! (/\.(jpe?g|png|gif)$/i).test(file) ) {
if(self.on_error) self.on_error(1);
return false;
}
}
else {//file is a File object
var type = $.trim(file.type);
if( ( type.length > 0 && ! (/^image\/(jpe?g|png|gif)$/i).test(type) )
|| ( type.length == 0 && ! (/\.(jpe?g|png|gif)$/i).test(file.name) )//for android default browser!
)
{
if(self.on_error) self.on_error(1);
return false;
}
if( self.max_size && file.size > self.max_size ) {
if(self.on_error) self.on_error(2);
return false;
}
}
if(self.on_success) self.on_success();
return true;
}
this.options.image.before_remove = this.options.image.before_remove || function() {
self.$input.val(null);
return true;
}
this.$file.ace_file_input(this.options.image).on('change', function(){
var $rand = (self.$file.val() || self.$file.data('ace_input_files')) ? Math.random() + "" + (new Date()).getTime() : null;
self.$input.val($rand)//set a random value, so that selected file is uploaded each time, even if it's the same file, because inline editable plugin does not update if the value is not changed!
}).closest('.ace-file-input').css({'width':'150px'}).closest('.editable-input').addClass('editable-image');
} | javascript | function() {
var self = this;
this.$input = this.$tpl.find('input[type=hidden]:eq(0)');
this.$file = this.$tpl.find('input[type=file]:eq(0)');
this.$file.attr({'name':this.name});
this.$input.attr({'name':this.name+'-hidden'});
this.options.image.before_change = this.options.image.before_change || function(files, dropped) {
var file = files[0];
if(typeof file === "string") {
//files is just a file name here (in browsers that don't support FileReader API)
if(! (/\.(jpe?g|png|gif)$/i).test(file) ) {
if(self.on_error) self.on_error(1);
return false;
}
}
else {//file is a File object
var type = $.trim(file.type);
if( ( type.length > 0 && ! (/^image\/(jpe?g|png|gif)$/i).test(type) )
|| ( type.length == 0 && ! (/\.(jpe?g|png|gif)$/i).test(file.name) )//for android default browser!
)
{
if(self.on_error) self.on_error(1);
return false;
}
if( self.max_size && file.size > self.max_size ) {
if(self.on_error) self.on_error(2);
return false;
}
}
if(self.on_success) self.on_success();
return true;
}
this.options.image.before_remove = this.options.image.before_remove || function() {
self.$input.val(null);
return true;
}
this.$file.ace_file_input(this.options.image).on('change', function(){
var $rand = (self.$file.val() || self.$file.data('ace_input_files')) ? Math.random() + "" + (new Date()).getTime() : null;
self.$input.val($rand)//set a random value, so that selected file is uploaded each time, even if it's the same file, because inline editable plugin does not update if the value is not changed!
}).closest('.ace-file-input').css({'width':'150px'}).closest('.editable-input').addClass('editable-image');
} | [
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"this",
".",
"$input",
"=",
"this",
".",
"$tpl",
".",
"find",
"(",
"'input[type=hidden]:eq(0)'",
")",
";",
"this",
".",
"$file",
"=",
"this",
".",
"$tpl",
".",
"find",
"(",
"'input[type=file]:eq(0)'",
")",
";",
"this",
".",
"$file",
".",
"attr",
"(",
"{",
"'name'",
":",
"this",
".",
"name",
"}",
")",
";",
"this",
".",
"$input",
".",
"attr",
"(",
"{",
"'name'",
":",
"this",
".",
"name",
"+",
"'-hidden'",
"}",
")",
";",
"this",
".",
"options",
".",
"image",
".",
"before_change",
"=",
"this",
".",
"options",
".",
"image",
".",
"before_change",
"||",
"function",
"(",
"files",
",",
"dropped",
")",
"{",
"var",
"file",
"=",
"files",
"[",
"0",
"]",
";",
"if",
"(",
"typeof",
"file",
"===",
"\"string\"",
")",
"{",
"if",
"(",
"!",
"(",
"/",
"\\.(jpe?g|png|gif)$",
"/",
"i",
")",
".",
"test",
"(",
"file",
")",
")",
"{",
"if",
"(",
"self",
".",
"on_error",
")",
"self",
".",
"on_error",
"(",
"1",
")",
";",
"return",
"false",
";",
"}",
"}",
"else",
"{",
"var",
"type",
"=",
"$",
".",
"trim",
"(",
"file",
".",
"type",
")",
";",
"if",
"(",
"(",
"type",
".",
"length",
">",
"0",
"&&",
"!",
"(",
"/",
"^image\\/(jpe?g|png|gif)$",
"/",
"i",
")",
".",
"test",
"(",
"type",
")",
")",
"||",
"(",
"type",
".",
"length",
"==",
"0",
"&&",
"!",
"(",
"/",
"\\.(jpe?g|png|gif)$",
"/",
"i",
")",
".",
"test",
"(",
"file",
".",
"name",
")",
")",
")",
"{",
"if",
"(",
"self",
".",
"on_error",
")",
"self",
".",
"on_error",
"(",
"1",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"self",
".",
"max_size",
"&&",
"file",
".",
"size",
">",
"self",
".",
"max_size",
")",
"{",
"if",
"(",
"self",
".",
"on_error",
")",
"self",
".",
"on_error",
"(",
"2",
")",
";",
"return",
"false",
";",
"}",
"}",
"if",
"(",
"self",
".",
"on_success",
")",
"self",
".",
"on_success",
"(",
")",
";",
"return",
"true",
";",
"}",
"this",
".",
"options",
".",
"image",
".",
"before_remove",
"=",
"this",
".",
"options",
".",
"image",
".",
"before_remove",
"||",
"function",
"(",
")",
"{",
"self",
".",
"$input",
".",
"val",
"(",
"null",
")",
";",
"return",
"true",
";",
"}",
"this",
".",
"$file",
".",
"ace_file_input",
"(",
"this",
".",
"options",
".",
"image",
")",
".",
"on",
"(",
"'change'",
",",
"function",
"(",
")",
"{",
"var",
"$rand",
"=",
"(",
"self",
".",
"$file",
".",
"val",
"(",
")",
"||",
"self",
".",
"$file",
".",
"data",
"(",
"'ace_input_files'",
")",
")",
"?",
"Math",
".",
"random",
"(",
")",
"+",
"\"\"",
"+",
"(",
"new",
"Date",
"(",
")",
")",
".",
"getTime",
"(",
")",
":",
"null",
";",
"self",
".",
"$input",
".",
"val",
"(",
"$rand",
")",
"}",
")",
".",
"closest",
"(",
"'.ace-file-input'",
")",
".",
"css",
"(",
"{",
"'width'",
":",
"'150px'",
"}",
")",
".",
"closest",
"(",
"'.editable-input'",
")",
".",
"addClass",
"(",
"'editable-image'",
")",
";",
"}"
] | Renders input from tpl
@method render() | [
"Renders",
"input",
"from",
"tpl"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/x-editable/ace-editable.js#L40-L85 | train |
|
RoganMurley/hitagi.js | src/components/graphics/graphic.js | function (params) {
this.$id = 'graphic';
this.$deps = []; // Position dependency added later if relative positioning is true.
params = _.extend({
alpha: 1,
anchor: {
x: 0.5,
y: 0.5
},
relative: true,
scale: {
x: 1,
y: 1
},
tint: 0xffffff,
translate: {
x: 0,
y: 0
},
visible: true,
z: 0
}, params);
if (params.relative) {
this.$deps.push('position');
}
this.alpha = params.alpha;
this.anchor = params.anchor;
this.relative = params.relative;
this.scale = params.scale;
this.tint = params.tint;
this.translate = params.translate;
this.visible = params.visible;
this.z = params.z;
} | javascript | function (params) {
this.$id = 'graphic';
this.$deps = []; // Position dependency added later if relative positioning is true.
params = _.extend({
alpha: 1,
anchor: {
x: 0.5,
y: 0.5
},
relative: true,
scale: {
x: 1,
y: 1
},
tint: 0xffffff,
translate: {
x: 0,
y: 0
},
visible: true,
z: 0
}, params);
if (params.relative) {
this.$deps.push('position');
}
this.alpha = params.alpha;
this.anchor = params.anchor;
this.relative = params.relative;
this.scale = params.scale;
this.tint = params.tint;
this.translate = params.translate;
this.visible = params.visible;
this.z = params.z;
} | [
"function",
"(",
"params",
")",
"{",
"this",
".",
"$id",
"=",
"'graphic'",
";",
"this",
".",
"$deps",
"=",
"[",
"]",
";",
"params",
"=",
"_",
".",
"extend",
"(",
"{",
"alpha",
":",
"1",
",",
"anchor",
":",
"{",
"x",
":",
"0.5",
",",
"y",
":",
"0.5",
"}",
",",
"relative",
":",
"true",
",",
"scale",
":",
"{",
"x",
":",
"1",
",",
"y",
":",
"1",
"}",
",",
"tint",
":",
"0xffffff",
",",
"translate",
":",
"{",
"x",
":",
"0",
",",
"y",
":",
"0",
"}",
",",
"visible",
":",
"true",
",",
"z",
":",
"0",
"}",
",",
"params",
")",
";",
"if",
"(",
"params",
".",
"relative",
")",
"{",
"this",
".",
"$deps",
".",
"push",
"(",
"'position'",
")",
";",
"}",
"this",
".",
"alpha",
"=",
"params",
".",
"alpha",
";",
"this",
".",
"anchor",
"=",
"params",
".",
"anchor",
";",
"this",
".",
"relative",
"=",
"params",
".",
"relative",
";",
"this",
".",
"scale",
"=",
"params",
".",
"scale",
";",
"this",
".",
"tint",
"=",
"params",
".",
"tint",
";",
"this",
".",
"translate",
"=",
"params",
".",
"translate",
";",
"this",
".",
"visible",
"=",
"params",
".",
"visible",
";",
"this",
".",
"z",
"=",
"params",
".",
"z",
";",
"}"
] | Represents a graphic to draw. | [
"Represents",
"a",
"graphic",
"to",
"draw",
"."
] | 6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053 | https://github.com/RoganMurley/hitagi.js/blob/6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053/src/components/graphics/graphic.js#L7-L44 | train |
|
joshfire/woodman | lib/layouts/patternlayout.js | function (config, loggerContext) {
Layout.call(this, config, loggerContext);
this.pattern = this.config.pattern ||
PatternLayout.DEFAULT_CONVERSION_PATTERN;
this.compactObjects = this.config.compactObjects || false;
} | javascript | function (config, loggerContext) {
Layout.call(this, config, loggerContext);
this.pattern = this.config.pattern ||
PatternLayout.DEFAULT_CONVERSION_PATTERN;
this.compactObjects = this.config.compactObjects || false;
} | [
"function",
"(",
"config",
",",
"loggerContext",
")",
"{",
"Layout",
".",
"call",
"(",
"this",
",",
"config",
",",
"loggerContext",
")",
";",
"this",
".",
"pattern",
"=",
"this",
".",
"config",
".",
"pattern",
"||",
"PatternLayout",
".",
"DEFAULT_CONVERSION_PATTERN",
";",
"this",
".",
"compactObjects",
"=",
"this",
".",
"config",
".",
"compactObjects",
"||",
"false",
";",
"}"
] | Lays out a log event using a regexp-like format string.
@constructor
@extends {Layout}
@param {Object} config Layout configuration. Structure depends on concrete
layout class being used
@param {LoggerContext} loggerContext Reference to the logger context that
gave birth to this layout. | [
"Lays",
"out",
"a",
"log",
"event",
"using",
"a",
"regexp",
"-",
"like",
"format",
"string",
"."
] | fdc05de2124388780924980e6f27bf4483056d18 | https://github.com/joshfire/woodman/blob/fdc05de2124388780924980e6f27bf4483056d18/lib/layouts/patternlayout.js#L89-L94 | train |
|
SBoudrias/gruntfile-editor | lib/index.js | function (gruntfileContent) {
var defaultGruntfilePath = path.join(__dirname, 'default-gruntfile.js');
gruntfileContent = gruntfileContent || fs.readFileSync(defaultGruntfilePath);
this.gruntfile = new Tree(gruntfileContent.toString());
} | javascript | function (gruntfileContent) {
var defaultGruntfilePath = path.join(__dirname, 'default-gruntfile.js');
gruntfileContent = gruntfileContent || fs.readFileSync(defaultGruntfilePath);
this.gruntfile = new Tree(gruntfileContent.toString());
} | [
"function",
"(",
"gruntfileContent",
")",
"{",
"var",
"defaultGruntfilePath",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"'default-gruntfile.js'",
")",
";",
"gruntfileContent",
"=",
"gruntfileContent",
"||",
"fs",
".",
"readFileSync",
"(",
"defaultGruntfilePath",
")",
";",
"this",
".",
"gruntfile",
"=",
"new",
"Tree",
"(",
"gruntfileContent",
".",
"toString",
"(",
")",
")",
";",
"}"
] | A class managing the edition of the project Gruntfile content. Editing the
Gruntfile using this class allow easier Generator composability as they can
work and add parts to the same Gruntfile without having to parse the
Gruntfile AST themselves.
@constructor
@param {String} gruntfileContent - The actual `Gruntfile.js` content | [
"A",
"class",
"managing",
"the",
"edition",
"of",
"the",
"project",
"Gruntfile",
"content",
".",
"Editing",
"the",
"Gruntfile",
"using",
"this",
"class",
"allow",
"easier",
"Generator",
"composability",
"as",
"they",
"can",
"work",
"and",
"add",
"parts",
"to",
"the",
"same",
"Gruntfile",
"without",
"having",
"to",
"parse",
"the",
"Gruntfile",
"AST",
"themselves",
"."
] | a5e1d849a20c3e2102c0c59926a5c919ca43a2b7 | https://github.com/SBoudrias/gruntfile-editor/blob/a5e1d849a20c3e2102c0c59926a5c919ca43a2b7/lib/index.js#L18-L22 | train |
|
Adezandee/node-cp | cp.js | function(checks, callback) {
fs.lstat(options.source, function(err, stats) {
/* istanbul ignore else */
if (stats.isFile()) {
copyFile(options, callback);
} else if (stats.isDirectory()) {
copyDir(options, callback);
} else if (stats.isSymbolicLink()) {
copySymlink(options, callback);
} else {
callback(new Error('Unsupported file type !'));
}
});
} | javascript | function(checks, callback) {
fs.lstat(options.source, function(err, stats) {
/* istanbul ignore else */
if (stats.isFile()) {
copyFile(options, callback);
} else if (stats.isDirectory()) {
copyDir(options, callback);
} else if (stats.isSymbolicLink()) {
copySymlink(options, callback);
} else {
callback(new Error('Unsupported file type !'));
}
});
} | [
"function",
"(",
"checks",
",",
"callback",
")",
"{",
"fs",
".",
"lstat",
"(",
"options",
".",
"source",
",",
"function",
"(",
"err",
",",
"stats",
")",
"{",
"if",
"(",
"stats",
".",
"isFile",
"(",
")",
")",
"{",
"copyFile",
"(",
"options",
",",
"callback",
")",
";",
"}",
"else",
"if",
"(",
"stats",
".",
"isDirectory",
"(",
")",
")",
"{",
"copyDir",
"(",
"options",
",",
"callback",
")",
";",
"}",
"else",
"if",
"(",
"stats",
".",
"isSymbolicLink",
"(",
")",
")",
"{",
"copySymlink",
"(",
"options",
",",
"callback",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"new",
"Error",
"(",
"'Unsupported file type !'",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] | Read the source and acts accordingly to its type | [
"Read",
"the",
"source",
"and",
"acts",
"accordingly",
"to",
"its",
"type"
] | e053ec042f2084c0d1f9ddab1f3727f1c0d422b6 | https://github.com/Adezandee/node-cp/blob/e053ec042f2084c0d1f9ddab1f3727f1c0d422b6/cp.js#L29-L42 | train |
|
Adezandee/node-cp | cp.js | function(callback) {
fs.exists(options.source, function(exists) {
if(!exists) { callback(new Error('Source file do not exists!')); }
else { callback(null, true); }
});
} | javascript | function(callback) {
fs.exists(options.source, function(exists) {
if(!exists) { callback(new Error('Source file do not exists!')); }
else { callback(null, true); }
});
} | [
"function",
"(",
"callback",
")",
"{",
"fs",
".",
"exists",
"(",
"options",
".",
"source",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"!",
"exists",
")",
"{",
"callback",
"(",
"new",
"Error",
"(",
"'Source file do not exists!'",
")",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"true",
")",
";",
"}",
"}",
")",
";",
"}"
] | Check if source exists | [
"Check",
"if",
"source",
"exists"
] | e053ec042f2084c0d1f9ddab1f3727f1c0d422b6 | https://github.com/Adezandee/node-cp/blob/e053ec042f2084c0d1f9ddab1f3727f1c0d422b6/cp.js#L51-L56 | train |
|
Adezandee/node-cp | cp.js | function(linkString, callback) {
fs.exists(_toFile, function (exists) {
callback(null, exists, linkString);
});
} | javascript | function(linkString, callback) {
fs.exists(_toFile, function (exists) {
callback(null, exists, linkString);
});
} | [
"function",
"(",
"linkString",
",",
"callback",
")",
"{",
"fs",
".",
"exists",
"(",
"_toFile",
",",
"function",
"(",
"exists",
")",
"{",
"callback",
"(",
"null",
",",
"exists",
",",
"linkString",
")",
";",
"}",
")",
";",
"}"
] | Check if the copied symlink already exists in destination folder | [
"Check",
"if",
"the",
"copied",
"symlink",
"already",
"exists",
"in",
"destination",
"folder"
] | e053ec042f2084c0d1f9ddab1f3727f1c0d422b6 | https://github.com/Adezandee/node-cp/blob/e053ec042f2084c0d1f9ddab1f3727f1c0d422b6/cp.js#L92-L96 | train |
|
Adezandee/node-cp | cp.js | function(exists, linkString, callback) {
if (exists) {
return callback(null, symlink);
}
fs.symlink(linkString, _toFile, function(err) {
callback(err, symlink);
});
} | javascript | function(exists, linkString, callback) {
if (exists) {
return callback(null, symlink);
}
fs.symlink(linkString, _toFile, function(err) {
callback(err, symlink);
});
} | [
"function",
"(",
"exists",
",",
"linkString",
",",
"callback",
")",
"{",
"if",
"(",
"exists",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"symlink",
")",
";",
"}",
"fs",
".",
"symlink",
"(",
"linkString",
",",
"_toFile",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
",",
"symlink",
")",
";",
"}",
")",
";",
"}"
] | If link does not already exists, creates it | [
"If",
"link",
"does",
"not",
"already",
"exists",
"creates",
"it"
] | e053ec042f2084c0d1f9ddab1f3727f1c0d422b6 | https://github.com/Adezandee/node-cp/blob/e053ec042f2084c0d1f9ddab1f3727f1c0d422b6/cp.js#L99-L106 | train |
|
Adezandee/node-cp | cp.js | function(stats, callback) {
fs.readFile(file, function(err, data) {
callback(err, data, stats);
});
} | javascript | function(stats, callback) {
fs.readFile(file, function(err, data) {
callback(err, data, stats);
});
} | [
"function",
"(",
"stats",
",",
"callback",
")",
"{",
"fs",
".",
"readFile",
"(",
"file",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"callback",
"(",
"err",
",",
"data",
",",
"stats",
")",
";",
"}",
")",
";",
"}"
] | Read the file | [
"Read",
"the",
"file"
] | e053ec042f2084c0d1f9ddab1f3727f1c0d422b6 | https://github.com/Adezandee/node-cp/blob/e053ec042f2084c0d1f9ddab1f3727f1c0d422b6/cp.js#L123-L127 | train |
|
Adezandee/node-cp | cp.js | function(data, stats, callback) {
fs.writeFile(_toFile, data, stats, function(err) {
callback(err, _toFile);
});
} | javascript | function(data, stats, callback) {
fs.writeFile(_toFile, data, stats, function(err) {
callback(err, _toFile);
});
} | [
"function",
"(",
"data",
",",
"stats",
",",
"callback",
")",
"{",
"fs",
".",
"writeFile",
"(",
"_toFile",
",",
"data",
",",
"stats",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
",",
"_toFile",
")",
";",
"}",
")",
";",
"}"
] | Write the new file in destination folder | [
"Write",
"the",
"new",
"file",
"in",
"destination",
"folder"
] | e053ec042f2084c0d1f9ddab1f3727f1c0d422b6 | https://github.com/Adezandee/node-cp/blob/e053ec042f2084c0d1f9ddab1f3727f1c0d422b6/cp.js#L130-L134 | train |
|
rjrodger/seneca-perm | lib/ACLMicroservicesBuilder.js | processAuthResultForEntity | function processAuthResultForEntity(err, entity) {
if(stopAll) return
if(err && err.code !== ACL_ERROR_CODE) {
stopAll = true
callback(err, undefined)
} else {
if(entity) {
filteredEntities.push(entity)
}
callbackCount ++
if(callbackCount === entities.length) {
callback(undefined, filteredEntities)
}
}
} | javascript | function processAuthResultForEntity(err, entity) {
if(stopAll) return
if(err && err.code !== ACL_ERROR_CODE) {
stopAll = true
callback(err, undefined)
} else {
if(entity) {
filteredEntities.push(entity)
}
callbackCount ++
if(callbackCount === entities.length) {
callback(undefined, filteredEntities)
}
}
} | [
"function",
"processAuthResultForEntity",
"(",
"err",
",",
"entity",
")",
"{",
"if",
"(",
"stopAll",
")",
"return",
"if",
"(",
"err",
"&&",
"err",
".",
"code",
"!==",
"ACL_ERROR_CODE",
")",
"{",
"stopAll",
"=",
"true",
"callback",
"(",
"err",
",",
"undefined",
")",
"}",
"else",
"{",
"if",
"(",
"entity",
")",
"{",
"filteredEntities",
".",
"push",
"(",
"entity",
")",
"}",
"callbackCount",
"++",
"if",
"(",
"callbackCount",
"===",
"entities",
".",
"length",
")",
"{",
"callback",
"(",
"undefined",
",",
"filteredEntities",
")",
"}",
"}",
"}"
] | this closure is evil | [
"this",
"closure",
"is",
"evil"
] | cca9169e0d40d9796e11d30c2c878486ecfdcb4a | https://github.com/rjrodger/seneca-perm/blob/cca9169e0d40d9796e11d30c2c878486ecfdcb4a/lib/ACLMicroservicesBuilder.js#L188-L205 | train |
xinix-technology/xin | core/event.js | _getMatcher | function _getMatcher (element) {
if (_matcher) {
return _matcher;
}
if (element.matches) {
_matcher = element.matches;
return _matcher;
}
if (element.webkitMatchesSelector) {
_matcher = element.webkitMatchesSelector;
return _matcher;
}
if (element.mozMatchesSelector) {
_matcher = element.mozMatchesSelector;
return _matcher;
}
if (element.msMatchesSelector) {
_matcher = element.msMatchesSelector;
return _matcher;
}
if (element.oMatchesSelector) {
_matcher = element.oMatchesSelector;
return _matcher;
}
// if it doesn't match a native browser method
// fall back to the delegator function
_matcher = Delegator.matchesSelector;
return _matcher;
} | javascript | function _getMatcher (element) {
if (_matcher) {
return _matcher;
}
if (element.matches) {
_matcher = element.matches;
return _matcher;
}
if (element.webkitMatchesSelector) {
_matcher = element.webkitMatchesSelector;
return _matcher;
}
if (element.mozMatchesSelector) {
_matcher = element.mozMatchesSelector;
return _matcher;
}
if (element.msMatchesSelector) {
_matcher = element.msMatchesSelector;
return _matcher;
}
if (element.oMatchesSelector) {
_matcher = element.oMatchesSelector;
return _matcher;
}
// if it doesn't match a native browser method
// fall back to the delegator function
_matcher = Delegator.matchesSelector;
return _matcher;
} | [
"function",
"_getMatcher",
"(",
"element",
")",
"{",
"if",
"(",
"_matcher",
")",
"{",
"return",
"_matcher",
";",
"}",
"if",
"(",
"element",
".",
"matches",
")",
"{",
"_matcher",
"=",
"element",
".",
"matches",
";",
"return",
"_matcher",
";",
"}",
"if",
"(",
"element",
".",
"webkitMatchesSelector",
")",
"{",
"_matcher",
"=",
"element",
".",
"webkitMatchesSelector",
";",
"return",
"_matcher",
";",
"}",
"if",
"(",
"element",
".",
"mozMatchesSelector",
")",
"{",
"_matcher",
"=",
"element",
".",
"mozMatchesSelector",
";",
"return",
"_matcher",
";",
"}",
"if",
"(",
"element",
".",
"msMatchesSelector",
")",
"{",
"_matcher",
"=",
"element",
".",
"msMatchesSelector",
";",
"return",
"_matcher",
";",
"}",
"if",
"(",
"element",
".",
"oMatchesSelector",
")",
"{",
"_matcher",
"=",
"element",
".",
"oMatchesSelector",
";",
"return",
"_matcher",
";",
"}",
"_matcher",
"=",
"Delegator",
".",
"matchesSelector",
";",
"return",
"_matcher",
";",
"}"
] | returns function to use for determining if an element
matches a query selector
@returns {Function} | [
"returns",
"function",
"to",
"use",
"for",
"determining",
"if",
"an",
"element",
"matches",
"a",
"query",
"selector"
] | 5e644c82d91e2dd6b3b4242ba00713c52f4f553f | https://github.com/xinix-technology/xin/blob/5e644c82d91e2dd6b3b4242ba00713c52f4f553f/core/event.js#L33-L67 | train |
xinix-technology/xin | core/event.js | _matchesSelector | function _matchesSelector (element, selector, boundElement) {
// no selector means this event was bound directly to this element
if (selector === '_root') {
return boundElement;
}
// if we have moved up to the element you bound the event to
// then we have come too far
if (element === boundElement) {
return;
}
if (_getMatcher(element).call(element, selector)) {
return element;
}
// if this element did not match but has a parent we should try
// going up the tree to see if any of the parent elements match
// for example if you are looking for a click on an <a> tag but there
// is a <span> inside of the a tag that it is the target,
// it should still work
if (element.parentNode) {
_level++;
return _matchesSelector(element.parentNode, selector, boundElement);
}
} | javascript | function _matchesSelector (element, selector, boundElement) {
// no selector means this event was bound directly to this element
if (selector === '_root') {
return boundElement;
}
// if we have moved up to the element you bound the event to
// then we have come too far
if (element === boundElement) {
return;
}
if (_getMatcher(element).call(element, selector)) {
return element;
}
// if this element did not match but has a parent we should try
// going up the tree to see if any of the parent elements match
// for example if you are looking for a click on an <a> tag but there
// is a <span> inside of the a tag that it is the target,
// it should still work
if (element.parentNode) {
_level++;
return _matchesSelector(element.parentNode, selector, boundElement);
}
} | [
"function",
"_matchesSelector",
"(",
"element",
",",
"selector",
",",
"boundElement",
")",
"{",
"if",
"(",
"selector",
"===",
"'_root'",
")",
"{",
"return",
"boundElement",
";",
"}",
"if",
"(",
"element",
"===",
"boundElement",
")",
"{",
"return",
";",
"}",
"if",
"(",
"_getMatcher",
"(",
"element",
")",
".",
"call",
"(",
"element",
",",
"selector",
")",
")",
"{",
"return",
"element",
";",
"}",
"if",
"(",
"element",
".",
"parentNode",
")",
"{",
"_level",
"++",
";",
"return",
"_matchesSelector",
"(",
"element",
".",
"parentNode",
",",
"selector",
",",
"boundElement",
")",
";",
"}",
"}"
] | determines if the specified element matches a given selector
@param {Node} element - the element to compare against the selector
@param {string} selector
@param {Node} boundElement - the element the listener was attached to
@returns {void|Node} | [
"determines",
"if",
"the",
"specified",
"element",
"matches",
"a",
"given",
"selector"
] | 5e644c82d91e2dd6b3b4242ba00713c52f4f553f | https://github.com/xinix-technology/xin/blob/5e644c82d91e2dd6b3b4242ba00713c52f4f553f/core/event.js#L77-L102 | train |
xinix-technology/xin | core/event.js | _bind | function _bind (events, selector, callback, remove) {
// fail silently if you pass null or undefined as an alement
// in the Delegator constructor
if (!this.element) {
return;
}
if (!(events instanceof Array)) {
events = [events];
}
if (!callback && typeof (selector) === 'function') {
callback = selector;
selector = '_root';
}
if (selector instanceof window.Element) {
let id;
if (selector.hasAttribute('bind-event-id')) {
id = selector.getAttribute('bind-event-id');
} else {
id = nextEventId();
selector.setAttribute('bind-event-id', id);
}
selector = `[bind-event-id="${id}"]`;
}
let id = this.id;
let i;
function _getGlobalCallback (type) {
return function (e) {
_handleEvent(id, e, type);
};
}
for (i = 0; i < events.length; i++) {
_aliases(events[i]).forEach(alias => {
if (remove) {
_removeHandler(this, alias, selector, callback);
return;
}
if (!_handlers[id] || !_handlers[id][alias]) {
Delegator.addEvent(this, alias, _getGlobalCallback(alias));
}
_addHandler(this, alias, selector, callback);
});
}
return this;
} | javascript | function _bind (events, selector, callback, remove) {
// fail silently if you pass null or undefined as an alement
// in the Delegator constructor
if (!this.element) {
return;
}
if (!(events instanceof Array)) {
events = [events];
}
if (!callback && typeof (selector) === 'function') {
callback = selector;
selector = '_root';
}
if (selector instanceof window.Element) {
let id;
if (selector.hasAttribute('bind-event-id')) {
id = selector.getAttribute('bind-event-id');
} else {
id = nextEventId();
selector.setAttribute('bind-event-id', id);
}
selector = `[bind-event-id="${id}"]`;
}
let id = this.id;
let i;
function _getGlobalCallback (type) {
return function (e) {
_handleEvent(id, e, type);
};
}
for (i = 0; i < events.length; i++) {
_aliases(events[i]).forEach(alias => {
if (remove) {
_removeHandler(this, alias, selector, callback);
return;
}
if (!_handlers[id] || !_handlers[id][alias]) {
Delegator.addEvent(this, alias, _getGlobalCallback(alias));
}
_addHandler(this, alias, selector, callback);
});
}
return this;
} | [
"function",
"_bind",
"(",
"events",
",",
"selector",
",",
"callback",
",",
"remove",
")",
"{",
"if",
"(",
"!",
"this",
".",
"element",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"(",
"events",
"instanceof",
"Array",
")",
")",
"{",
"events",
"=",
"[",
"events",
"]",
";",
"}",
"if",
"(",
"!",
"callback",
"&&",
"typeof",
"(",
"selector",
")",
"===",
"'function'",
")",
"{",
"callback",
"=",
"selector",
";",
"selector",
"=",
"'_root'",
";",
"}",
"if",
"(",
"selector",
"instanceof",
"window",
".",
"Element",
")",
"{",
"let",
"id",
";",
"if",
"(",
"selector",
".",
"hasAttribute",
"(",
"'bind-event-id'",
")",
")",
"{",
"id",
"=",
"selector",
".",
"getAttribute",
"(",
"'bind-event-id'",
")",
";",
"}",
"else",
"{",
"id",
"=",
"nextEventId",
"(",
")",
";",
"selector",
".",
"setAttribute",
"(",
"'bind-event-id'",
",",
"id",
")",
";",
"}",
"selector",
"=",
"`",
"${",
"id",
"}",
"`",
";",
"}",
"let",
"id",
"=",
"this",
".",
"id",
";",
"let",
"i",
";",
"function",
"_getGlobalCallback",
"(",
"type",
")",
"{",
"return",
"function",
"(",
"e",
")",
"{",
"_handleEvent",
"(",
"id",
",",
"e",
",",
"type",
")",
";",
"}",
";",
"}",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"events",
".",
"length",
";",
"i",
"++",
")",
"{",
"_aliases",
"(",
"events",
"[",
"i",
"]",
")",
".",
"forEach",
"(",
"alias",
"=>",
"{",
"if",
"(",
"remove",
")",
"{",
"_removeHandler",
"(",
"this",
",",
"alias",
",",
"selector",
",",
"callback",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"_handlers",
"[",
"id",
"]",
"||",
"!",
"_handlers",
"[",
"id",
"]",
"[",
"alias",
"]",
")",
"{",
"Delegator",
".",
"addEvent",
"(",
"this",
",",
"alias",
",",
"_getGlobalCallback",
"(",
"alias",
")",
")",
";",
"}",
"_addHandler",
"(",
"this",
",",
"alias",
",",
"selector",
",",
"callback",
")",
";",
"}",
")",
";",
"}",
"return",
"this",
";",
"}"
] | binds the specified events to the element
@param {string|Array} events
@param {string} selector
@param {Function} callback
@param {boolean=} remove
@returns {Object} | [
"binds",
"the",
"specified",
"events",
"to",
"the",
"element"
] | 5e644c82d91e2dd6b3b4242ba00713c52f4f553f | https://github.com/xinix-technology/xin/blob/5e644c82d91e2dd6b3b4242ba00713c52f4f553f/core/event.js#L260-L312 | train |
jimivdw/grunt-mutation-testing | lib/reporting/json/JSONReporter.js | JSONReporter | function JSONReporter(dir, config) {
this._config = config;
var fileName = config.file || DEFAULT_FILE_NAME;
this._filePath = path.join(dir, fileName);
} | javascript | function JSONReporter(dir, config) {
this._config = config;
var fileName = config.file || DEFAULT_FILE_NAME;
this._filePath = path.join(dir, fileName);
} | [
"function",
"JSONReporter",
"(",
"dir",
",",
"config",
")",
"{",
"this",
".",
"_config",
"=",
"config",
";",
"var",
"fileName",
"=",
"config",
".",
"file",
"||",
"DEFAULT_FILE_NAME",
";",
"this",
".",
"_filePath",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"fileName",
")",
";",
"}"
] | JSON report generator.
@param {string} dir - Report directory
@param {object=} config - Reporter configuration
@constructor | [
"JSON",
"report",
"generator",
"."
] | 698b1b20813cd7d46cf44f09cc016f5cd6460f5f | https://github.com/jimivdw/grunt-mutation-testing/blob/698b1b20813cd7d46cf44f09cc016f5cd6460f5f/lib/reporting/json/JSONReporter.js#L22-L27 | train |
jimivdw/grunt-mutation-testing | lib/reporting/json/JSONReporter.js | getMutationScore | function getMutationScore(stats) {
return {
total: (stats.all - stats.survived) / stats.all,
killed: stats.killed / stats.all,
survived: stats.survived / stats.all,
ignored: stats.ignored / stats.all,
untested: stats.untested / stats.all
};
} | javascript | function getMutationScore(stats) {
return {
total: (stats.all - stats.survived) / stats.all,
killed: stats.killed / stats.all,
survived: stats.survived / stats.all,
ignored: stats.ignored / stats.all,
untested: stats.untested / stats.all
};
} | [
"function",
"getMutationScore",
"(",
"stats",
")",
"{",
"return",
"{",
"total",
":",
"(",
"stats",
".",
"all",
"-",
"stats",
".",
"survived",
")",
"/",
"stats",
".",
"all",
",",
"killed",
":",
"stats",
".",
"killed",
"/",
"stats",
".",
"all",
",",
"survived",
":",
"stats",
".",
"survived",
"/",
"stats",
".",
"all",
",",
"ignored",
":",
"stats",
".",
"ignored",
"/",
"stats",
".",
"all",
",",
"untested",
":",
"stats",
".",
"untested",
"/",
"stats",
".",
"all",
"}",
";",
"}"
] | Calculate the mutation score from a stats object.
@param {object} stats - The stats from which to calculate the score
@returns {{total: number, killed: number, survived: number, ignored: number, untested: number}} | [
"Calculate",
"the",
"mutation",
"score",
"from",
"a",
"stats",
"object",
"."
] | 698b1b20813cd7d46cf44f09cc016f5cd6460f5f | https://github.com/jimivdw/grunt-mutation-testing/blob/698b1b20813cd7d46cf44f09cc016f5cd6460f5f/lib/reporting/json/JSONReporter.js#L74-L82 | train |
jimivdw/grunt-mutation-testing | lib/reporting/json/JSONReporter.js | getResultsPerDir | function getResultsPerDir(results) {
/**
* Decorate the results object with the stats for each directory.
*
* @param {object} results - (part of) mutation testing results
* @returns {object} - Mutation test results decorated with stats
*/
function addDirStats(results) {
var dirStats = {
all: 0,
killed: 0,
survived: 0,
ignored: 0,
untested: 0
};
_.forOwn(results, function(result) {
var stats = result.stats || addDirStats(result).stats;
dirStats.all += stats.all;
dirStats.killed += stats.killed;
dirStats.survived += stats.survived;
dirStats.ignored += stats.ignored;
dirStats.untested += stats.untested;
});
results.stats = dirStats;
return results;
}
/**
* Decorate the results object with the mutation score for each directory.
*
* @param {object} results - (part of) mutation testing results, decorated with mutation stats
* @returns {object} - Mutation test results decorated with mutation scores
*/
function addMutationScores(results) {
_.forOwn(results, function(result) {
if(_.has(result, 'stats')) {
addMutationScores(result);
}
});
results.mutationScore = getMutationScore(results.stats);
return results;
}
var resultsPerDir = {};
_.forEach(_.clone(results), function(fileResult) {
_.set(resultsPerDir, IOUtils.getDirectoryList(fileResult.fileName), fileResult);
});
return addMutationScores(addDirStats(resultsPerDir));
} | javascript | function getResultsPerDir(results) {
/**
* Decorate the results object with the stats for each directory.
*
* @param {object} results - (part of) mutation testing results
* @returns {object} - Mutation test results decorated with stats
*/
function addDirStats(results) {
var dirStats = {
all: 0,
killed: 0,
survived: 0,
ignored: 0,
untested: 0
};
_.forOwn(results, function(result) {
var stats = result.stats || addDirStats(result).stats;
dirStats.all += stats.all;
dirStats.killed += stats.killed;
dirStats.survived += stats.survived;
dirStats.ignored += stats.ignored;
dirStats.untested += stats.untested;
});
results.stats = dirStats;
return results;
}
/**
* Decorate the results object with the mutation score for each directory.
*
* @param {object} results - (part of) mutation testing results, decorated with mutation stats
* @returns {object} - Mutation test results decorated with mutation scores
*/
function addMutationScores(results) {
_.forOwn(results, function(result) {
if(_.has(result, 'stats')) {
addMutationScores(result);
}
});
results.mutationScore = getMutationScore(results.stats);
return results;
}
var resultsPerDir = {};
_.forEach(_.clone(results), function(fileResult) {
_.set(resultsPerDir, IOUtils.getDirectoryList(fileResult.fileName), fileResult);
});
return addMutationScores(addDirStats(resultsPerDir));
} | [
"function",
"getResultsPerDir",
"(",
"results",
")",
"{",
"function",
"addDirStats",
"(",
"results",
")",
"{",
"var",
"dirStats",
"=",
"{",
"all",
":",
"0",
",",
"killed",
":",
"0",
",",
"survived",
":",
"0",
",",
"ignored",
":",
"0",
",",
"untested",
":",
"0",
"}",
";",
"_",
".",
"forOwn",
"(",
"results",
",",
"function",
"(",
"result",
")",
"{",
"var",
"stats",
"=",
"result",
".",
"stats",
"||",
"addDirStats",
"(",
"result",
")",
".",
"stats",
";",
"dirStats",
".",
"all",
"+=",
"stats",
".",
"all",
";",
"dirStats",
".",
"killed",
"+=",
"stats",
".",
"killed",
";",
"dirStats",
".",
"survived",
"+=",
"stats",
".",
"survived",
";",
"dirStats",
".",
"ignored",
"+=",
"stats",
".",
"ignored",
";",
"dirStats",
".",
"untested",
"+=",
"stats",
".",
"untested",
";",
"}",
")",
";",
"results",
".",
"stats",
"=",
"dirStats",
";",
"return",
"results",
";",
"}",
"function",
"addMutationScores",
"(",
"results",
")",
"{",
"_",
".",
"forOwn",
"(",
"results",
",",
"function",
"(",
"result",
")",
"{",
"if",
"(",
"_",
".",
"has",
"(",
"result",
",",
"'stats'",
")",
")",
"{",
"addMutationScores",
"(",
"result",
")",
";",
"}",
"}",
")",
";",
"results",
".",
"mutationScore",
"=",
"getMutationScore",
"(",
"results",
".",
"stats",
")",
";",
"return",
"results",
";",
"}",
"var",
"resultsPerDir",
"=",
"{",
"}",
";",
"_",
".",
"forEach",
"(",
"_",
".",
"clone",
"(",
"results",
")",
",",
"function",
"(",
"fileResult",
")",
"{",
"_",
".",
"set",
"(",
"resultsPerDir",
",",
"IOUtils",
".",
"getDirectoryList",
"(",
"fileResult",
".",
"fileName",
")",
",",
"fileResult",
")",
";",
"}",
")",
";",
"return",
"addMutationScores",
"(",
"addDirStats",
"(",
"resultsPerDir",
")",
")",
";",
"}"
] | Calculate the mutation test results per directory.
@param {object} results - Mutation testing results
@returns {object} - The mutation test results per directory | [
"Calculate",
"the",
"mutation",
"test",
"results",
"per",
"directory",
"."
] | 698b1b20813cd7d46cf44f09cc016f5cd6460f5f | https://github.com/jimivdw/grunt-mutation-testing/blob/698b1b20813cd7d46cf44f09cc016f5cd6460f5f/lib/reporting/json/JSONReporter.js#L90-L144 | train |
jimivdw/grunt-mutation-testing | lib/reporting/json/JSONReporter.js | addDirStats | function addDirStats(results) {
var dirStats = {
all: 0,
killed: 0,
survived: 0,
ignored: 0,
untested: 0
};
_.forOwn(results, function(result) {
var stats = result.stats || addDirStats(result).stats;
dirStats.all += stats.all;
dirStats.killed += stats.killed;
dirStats.survived += stats.survived;
dirStats.ignored += stats.ignored;
dirStats.untested += stats.untested;
});
results.stats = dirStats;
return results;
} | javascript | function addDirStats(results) {
var dirStats = {
all: 0,
killed: 0,
survived: 0,
ignored: 0,
untested: 0
};
_.forOwn(results, function(result) {
var stats = result.stats || addDirStats(result).stats;
dirStats.all += stats.all;
dirStats.killed += stats.killed;
dirStats.survived += stats.survived;
dirStats.ignored += stats.ignored;
dirStats.untested += stats.untested;
});
results.stats = dirStats;
return results;
} | [
"function",
"addDirStats",
"(",
"results",
")",
"{",
"var",
"dirStats",
"=",
"{",
"all",
":",
"0",
",",
"killed",
":",
"0",
",",
"survived",
":",
"0",
",",
"ignored",
":",
"0",
",",
"untested",
":",
"0",
"}",
";",
"_",
".",
"forOwn",
"(",
"results",
",",
"function",
"(",
"result",
")",
"{",
"var",
"stats",
"=",
"result",
".",
"stats",
"||",
"addDirStats",
"(",
"result",
")",
".",
"stats",
";",
"dirStats",
".",
"all",
"+=",
"stats",
".",
"all",
";",
"dirStats",
".",
"killed",
"+=",
"stats",
".",
"killed",
";",
"dirStats",
".",
"survived",
"+=",
"stats",
".",
"survived",
";",
"dirStats",
".",
"ignored",
"+=",
"stats",
".",
"ignored",
";",
"dirStats",
".",
"untested",
"+=",
"stats",
".",
"untested",
";",
"}",
")",
";",
"results",
".",
"stats",
"=",
"dirStats",
";",
"return",
"results",
";",
"}"
] | Decorate the results object with the stats for each directory.
@param {object} results - (part of) mutation testing results
@returns {object} - Mutation test results decorated with stats | [
"Decorate",
"the",
"results",
"object",
"with",
"the",
"stats",
"for",
"each",
"directory",
"."
] | 698b1b20813cd7d46cf44f09cc016f5cd6460f5f | https://github.com/jimivdw/grunt-mutation-testing/blob/698b1b20813cd7d46cf44f09cc016f5cd6460f5f/lib/reporting/json/JSONReporter.js#L98-L118 | train |
jimivdw/grunt-mutation-testing | lib/reporting/json/JSONReporter.js | addMutationScores | function addMutationScores(results) {
_.forOwn(results, function(result) {
if(_.has(result, 'stats')) {
addMutationScores(result);
}
});
results.mutationScore = getMutationScore(results.stats);
return results;
} | javascript | function addMutationScores(results) {
_.forOwn(results, function(result) {
if(_.has(result, 'stats')) {
addMutationScores(result);
}
});
results.mutationScore = getMutationScore(results.stats);
return results;
} | [
"function",
"addMutationScores",
"(",
"results",
")",
"{",
"_",
".",
"forOwn",
"(",
"results",
",",
"function",
"(",
"result",
")",
"{",
"if",
"(",
"_",
".",
"has",
"(",
"result",
",",
"'stats'",
")",
")",
"{",
"addMutationScores",
"(",
"result",
")",
";",
"}",
"}",
")",
";",
"results",
".",
"mutationScore",
"=",
"getMutationScore",
"(",
"results",
".",
"stats",
")",
";",
"return",
"results",
";",
"}"
] | Decorate the results object with the mutation score for each directory.
@param {object} results - (part of) mutation testing results, decorated with mutation stats
@returns {object} - Mutation test results decorated with mutation scores | [
"Decorate",
"the",
"results",
"object",
"with",
"the",
"mutation",
"score",
"for",
"each",
"directory",
"."
] | 698b1b20813cd7d46cf44f09cc016f5cd6460f5f | https://github.com/jimivdw/grunt-mutation-testing/blob/698b1b20813cd7d46cf44f09cc016f5cd6460f5f/lib/reporting/json/JSONReporter.js#L126-L135 | train |
petermbenjamin/exploitalert | src/search.js | search | function search(platform) {
return new Promise((resolve, reject) => {
if (!platform || platform === '') reject(new Error('platform cannot be blank'));
const options = {
method: 'GET',
hostname: 'www.exploitalert.com',
path: `/api/search-exploit?name=${platform}`,
};
const req = http.request(options, (res) => {
const chunks = [];
res.on('data', (chunk) => {
chunks.push(chunk);
});
res.on('end', () => {
const body = Buffer.concat(chunks);
resolve(JSON.parse(body));
});
});
req.on('error', err => reject(err));
req.end();
});
} | javascript | function search(platform) {
return new Promise((resolve, reject) => {
if (!platform || platform === '') reject(new Error('platform cannot be blank'));
const options = {
method: 'GET',
hostname: 'www.exploitalert.com',
path: `/api/search-exploit?name=${platform}`,
};
const req = http.request(options, (res) => {
const chunks = [];
res.on('data', (chunk) => {
chunks.push(chunk);
});
res.on('end', () => {
const body = Buffer.concat(chunks);
resolve(JSON.parse(body));
});
});
req.on('error', err => reject(err));
req.end();
});
} | [
"function",
"search",
"(",
"platform",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"if",
"(",
"!",
"platform",
"||",
"platform",
"===",
"''",
")",
"reject",
"(",
"new",
"Error",
"(",
"'platform cannot be blank'",
")",
")",
";",
"const",
"options",
"=",
"{",
"method",
":",
"'GET'",
",",
"hostname",
":",
"'www.exploitalert.com'",
",",
"path",
":",
"`",
"${",
"platform",
"}",
"`",
",",
"}",
";",
"const",
"req",
"=",
"http",
".",
"request",
"(",
"options",
",",
"(",
"res",
")",
"=>",
"{",
"const",
"chunks",
"=",
"[",
"]",
";",
"res",
".",
"on",
"(",
"'data'",
",",
"(",
"chunk",
")",
"=>",
"{",
"chunks",
".",
"push",
"(",
"chunk",
")",
";",
"}",
")",
";",
"res",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"{",
"const",
"body",
"=",
"Buffer",
".",
"concat",
"(",
"chunks",
")",
";",
"resolve",
"(",
"JSON",
".",
"parse",
"(",
"body",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"req",
".",
"on",
"(",
"'error'",
",",
"err",
"=>",
"reject",
"(",
"err",
")",
")",
";",
"req",
".",
"end",
"(",
")",
";",
"}",
")",
";",
"}"
] | Searches exploitalert db
@param {string} platform - the platform to search for | [
"Searches",
"exploitalert",
"db"
] | a250d497a6be13db968b72ab0139028d6d1744ac | https://github.com/petermbenjamin/exploitalert/blob/a250d497a6be13db968b72ab0139028d6d1744ac/src/search.js#L7-L32 | train |
joshfire/woodman | lib/logger.js | function (name, loggerContext) {
/**
* Logger name
*/
this.name = name;
/**
* Reference to the logger context that created this logger
*
* The reference is used to create appenders and layouts when
* configuration is applied.
*/
this.loggerContext = loggerContext;
/**
* Parent logger. All loggers have a parent except the root logger
*/
this.parent = null;
/**
* Children loggers. Mostly used during initialization to propagate
* the configuration.
*/
this.children = [];
/**
* Appenders associated with the logger. Set during initialization
*/
this.appenders = [];
/**
* Logger filter. Set during initialization
*/
this.filter = null;
/**
* The trace level of the logger. Log events whose level is below that
* level are logged. Others are discarded.
*/
this.level = 'inherit';
/**
* Additivity flag. Log events are not propagated to the parent logger
* if the flag is not set.
*/
this.additive = true;
/**
* Function used to determine whether a log level is below the
* trace level of the logger
*/
if (this.loggerContext) {
this.isBelow = function (level, referenceLevel) {
return this.loggerContext.logLevel.isBelow(level, referenceLevel);
};
// Set trace functions for all registered levels
utils.each(this.loggerContext.logLevel.getLevels(), function (level) {
var self = this;
if (!this[level]) {
this[level] = function () {
self.traceAtLevel(level, arguments);
};
}
}, this);
}
else {
this.isBelow = function () {
return true;
};
}
} | javascript | function (name, loggerContext) {
/**
* Logger name
*/
this.name = name;
/**
* Reference to the logger context that created this logger
*
* The reference is used to create appenders and layouts when
* configuration is applied.
*/
this.loggerContext = loggerContext;
/**
* Parent logger. All loggers have a parent except the root logger
*/
this.parent = null;
/**
* Children loggers. Mostly used during initialization to propagate
* the configuration.
*/
this.children = [];
/**
* Appenders associated with the logger. Set during initialization
*/
this.appenders = [];
/**
* Logger filter. Set during initialization
*/
this.filter = null;
/**
* The trace level of the logger. Log events whose level is below that
* level are logged. Others are discarded.
*/
this.level = 'inherit';
/**
* Additivity flag. Log events are not propagated to the parent logger
* if the flag is not set.
*/
this.additive = true;
/**
* Function used to determine whether a log level is below the
* trace level of the logger
*/
if (this.loggerContext) {
this.isBelow = function (level, referenceLevel) {
return this.loggerContext.logLevel.isBelow(level, referenceLevel);
};
// Set trace functions for all registered levels
utils.each(this.loggerContext.logLevel.getLevels(), function (level) {
var self = this;
if (!this[level]) {
this[level] = function () {
self.traceAtLevel(level, arguments);
};
}
}, this);
}
else {
this.isBelow = function () {
return true;
};
}
} | [
"function",
"(",
"name",
",",
"loggerContext",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"loggerContext",
"=",
"loggerContext",
";",
"this",
".",
"parent",
"=",
"null",
";",
"this",
".",
"children",
"=",
"[",
"]",
";",
"this",
".",
"appenders",
"=",
"[",
"]",
";",
"this",
".",
"filter",
"=",
"null",
";",
"this",
".",
"level",
"=",
"'inherit'",
";",
"this",
".",
"additive",
"=",
"true",
";",
"if",
"(",
"this",
".",
"loggerContext",
")",
"{",
"this",
".",
"isBelow",
"=",
"function",
"(",
"level",
",",
"referenceLevel",
")",
"{",
"return",
"this",
".",
"loggerContext",
".",
"logLevel",
".",
"isBelow",
"(",
"level",
",",
"referenceLevel",
")",
";",
"}",
";",
"utils",
".",
"each",
"(",
"this",
".",
"loggerContext",
".",
"logLevel",
".",
"getLevels",
"(",
")",
",",
"function",
"(",
"level",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"!",
"this",
"[",
"level",
"]",
")",
"{",
"this",
"[",
"level",
"]",
"=",
"function",
"(",
")",
"{",
"self",
".",
"traceAtLevel",
"(",
"level",
",",
"arguments",
")",
";",
"}",
";",
"}",
"}",
",",
"this",
")",
";",
"}",
"else",
"{",
"this",
".",
"isBelow",
"=",
"function",
"(",
")",
"{",
"return",
"true",
";",
"}",
";",
"}",
"}"
] | Definition of the Logger class
@constructor | [
"Definition",
"of",
"the",
"Logger",
"class"
] | fdc05de2124388780924980e6f27bf4483056d18 | https://github.com/joshfire/woodman/blob/fdc05de2124388780924980e6f27bf4483056d18/lib/logger.js#L34-L105 | train |
|
AntonyThorpe/knockout-apollo | demo/bower_components/ko.plus/dist/ko.plus.js | function () {
//check if we are able to execute
if (!canExecuteWrapper.call(options.context || this)) {
//dont attach any global handlers
return instantDeferred(false, null, options.context || this).promise();
}
//notify that we are running and clear any existing error message
isRunning(true);
failed(false);
failMessage('');
//try to invoke the action and get a reference to the deferred object
var promise;
try {
promise = options.action.apply(options.context || this, arguments);
//if the returned result is *not* a promise, create a new one that is already resolved
if (!isPromise(promise)) {
promise = instantDeferred(true, promise, options.context || this).promise();
}
} catch (error) {
promise = instantDeferred(false, error, options.context || this).promise();
}
//set up our callbacks
callbacks.always.forEach(function(callback) {
promise.then(callback, callback);
});
callbacks.fail.forEach(function(callback) {
promise.then(null, callback);
});
callbacks.done.forEach(function(callback) {
promise.then(callback);
});
return promise;
} | javascript | function () {
//check if we are able to execute
if (!canExecuteWrapper.call(options.context || this)) {
//dont attach any global handlers
return instantDeferred(false, null, options.context || this).promise();
}
//notify that we are running and clear any existing error message
isRunning(true);
failed(false);
failMessage('');
//try to invoke the action and get a reference to the deferred object
var promise;
try {
promise = options.action.apply(options.context || this, arguments);
//if the returned result is *not* a promise, create a new one that is already resolved
if (!isPromise(promise)) {
promise = instantDeferred(true, promise, options.context || this).promise();
}
} catch (error) {
promise = instantDeferred(false, error, options.context || this).promise();
}
//set up our callbacks
callbacks.always.forEach(function(callback) {
promise.then(callback, callback);
});
callbacks.fail.forEach(function(callback) {
promise.then(null, callback);
});
callbacks.done.forEach(function(callback) {
promise.then(callback);
});
return promise;
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"canExecuteWrapper",
".",
"call",
"(",
"options",
".",
"context",
"||",
"this",
")",
")",
"{",
"return",
"instantDeferred",
"(",
"false",
",",
"null",
",",
"options",
".",
"context",
"||",
"this",
")",
".",
"promise",
"(",
")",
";",
"}",
"isRunning",
"(",
"true",
")",
";",
"failed",
"(",
"false",
")",
";",
"failMessage",
"(",
"''",
")",
";",
"var",
"promise",
";",
"try",
"{",
"promise",
"=",
"options",
".",
"action",
".",
"apply",
"(",
"options",
".",
"context",
"||",
"this",
",",
"arguments",
")",
";",
"if",
"(",
"!",
"isPromise",
"(",
"promise",
")",
")",
"{",
"promise",
"=",
"instantDeferred",
"(",
"true",
",",
"promise",
",",
"options",
".",
"context",
"||",
"this",
")",
".",
"promise",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"error",
")",
"{",
"promise",
"=",
"instantDeferred",
"(",
"false",
",",
"error",
",",
"options",
".",
"context",
"||",
"this",
")",
".",
"promise",
"(",
")",
";",
"}",
"callbacks",
".",
"always",
".",
"forEach",
"(",
"function",
"(",
"callback",
")",
"{",
"promise",
".",
"then",
"(",
"callback",
",",
"callback",
")",
";",
"}",
")",
";",
"callbacks",
".",
"fail",
".",
"forEach",
"(",
"function",
"(",
"callback",
")",
"{",
"promise",
".",
"then",
"(",
"null",
",",
"callback",
")",
";",
"}",
")",
";",
"callbacks",
".",
"done",
".",
"forEach",
"(",
"function",
"(",
"callback",
")",
"{",
"promise",
".",
"then",
"(",
"callback",
")",
";",
"}",
")",
";",
"return",
"promise",
";",
"}"
] | execute function (and return object | [
"execute",
"function",
"(",
"and",
"return",
"object"
] | 573a7caea7e41877710e69bac001771a6ea86d33 | https://github.com/AntonyThorpe/knockout-apollo/blob/573a7caea7e41877710e69bac001771a6ea86d33/demo/bower_components/ko.plus/dist/ko.plus.js#L58-L96 | train |
|
AntonyThorpe/knockout-apollo | demo/bower_components/ko.plus/dist/ko.plus.js | function (callback) {
callbacks.fail.push(function () {
var result = callback.apply(this, arguments);
if (result) {
failMessage(result);
}
});
return execute;
} | javascript | function (callback) {
callbacks.fail.push(function () {
var result = callback.apply(this, arguments);
if (result) {
failMessage(result);
}
});
return execute;
} | [
"function",
"(",
"callback",
")",
"{",
"callbacks",
".",
"fail",
".",
"push",
"(",
"function",
"(",
")",
"{",
"var",
"result",
"=",
"callback",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"if",
"(",
"result",
")",
"{",
"failMessage",
"(",
"result",
")",
";",
"}",
"}",
")",
";",
"return",
"execute",
";",
"}"
] | function used to append failure callbacks | [
"function",
"used",
"to",
"append",
"failure",
"callbacks"
] | 573a7caea7e41877710e69bac001771a6ea86d33 | https://github.com/AntonyThorpe/knockout-apollo/blob/573a7caea7e41877710e69bac001771a6ea86d33/demo/bower_components/ko.plus/dist/ko.plus.js#L121-L129 | train |
|
rfrench/chai-uuid | index.js | getRegEx | function getRegEx(version) {
switch(version.toLowerCase())
{
case 'v1':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v2':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v3':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v4':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v5':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
default:
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
}
} | javascript | function getRegEx(version) {
switch(version.toLowerCase())
{
case 'v1':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v2':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v3':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v4':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
case 'v5':
return /^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i;
default:
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
}
} | [
"function",
"getRegEx",
"(",
"version",
")",
"{",
"switch",
"(",
"version",
".",
"toLowerCase",
"(",
")",
")",
"{",
"case",
"'v1'",
":",
"return",
"/",
"^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$",
"/",
"i",
";",
"case",
"'v2'",
":",
"return",
"/",
"^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$",
"/",
"i",
";",
"case",
"'v3'",
":",
"return",
"/",
"^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$",
"/",
"i",
";",
"case",
"'v4'",
":",
"return",
"/",
"^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$",
"/",
"i",
";",
"case",
"'v5'",
":",
"return",
"/",
"^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$",
"/",
"i",
";",
"default",
":",
"return",
"/",
"^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",
"/",
"i",
";",
"}",
"}"
] | Returns a valid regex for validating the UUID
@param {String} version
@return {Regex} | [
"Returns",
"a",
"valid",
"regex",
"for",
"validating",
"the",
"UUID"
] | 48062e1fc2f8e3dd149f70db6f085650f8aea1b6 | https://github.com/rfrench/chai-uuid/blob/48062e1fc2f8e3dd149f70db6f085650f8aea1b6/index.js#L12-L28 | train |
rfrench/chai-uuid | index.js | uuid | function uuid(version) {
var v = (version) ? version : '';
// verify its a valid string
this.assert(
(typeof this._obj === 'string' || this._obj instanceof String),
'expected #{this} to be of type #{exp} but got #{act}',
'expected #{this} to not be of type #{exp}',
'string',
typeof(this._obj)
);
// assert it is a valid uuid
var regex = getRegEx(v);
this.assert(
regex.test(this._obj),
'expected #{this} to be a valid UUID ' + v,
'expected #{this} to not be a UUID ' + v
);
} | javascript | function uuid(version) {
var v = (version) ? version : '';
// verify its a valid string
this.assert(
(typeof this._obj === 'string' || this._obj instanceof String),
'expected #{this} to be of type #{exp} but got #{act}',
'expected #{this} to not be of type #{exp}',
'string',
typeof(this._obj)
);
// assert it is a valid uuid
var regex = getRegEx(v);
this.assert(
regex.test(this._obj),
'expected #{this} to be a valid UUID ' + v,
'expected #{this} to not be a UUID ' + v
);
} | [
"function",
"uuid",
"(",
"version",
")",
"{",
"var",
"v",
"=",
"(",
"version",
")",
"?",
"version",
":",
"''",
";",
"this",
".",
"assert",
"(",
"(",
"typeof",
"this",
".",
"_obj",
"===",
"'string'",
"||",
"this",
".",
"_obj",
"instanceof",
"String",
")",
",",
"'expected #{this} to be of type #{exp} but got #{act}'",
",",
"'expected #{this} to not be of type #{exp}'",
",",
"'string'",
",",
"typeof",
"(",
"this",
".",
"_obj",
")",
")",
";",
"var",
"regex",
"=",
"getRegEx",
"(",
"v",
")",
";",
"this",
".",
"assert",
"(",
"regex",
".",
"test",
"(",
"this",
".",
"_obj",
")",
",",
"'expected #{this} to be a valid UUID '",
"+",
"v",
",",
"'expected #{this} to not be a UUID '",
"+",
"v",
")",
";",
"}"
] | Validates a uuid
@param {String} version | [
"Validates",
"a",
"uuid"
] | 48062e1fc2f8e3dd149f70db6f085650f8aea1b6 | https://github.com/rfrench/chai-uuid/blob/48062e1fc2f8e3dd149f70db6f085650f8aea1b6/index.js#L34-L53 | train |
jimivdw/grunt-mutation-testing | lib/karma/KarmaCodeSpecsMatcher.js | KarmaCodeSpecsMatcher | function KarmaCodeSpecsMatcher(serverPool, config) {
this._serverPool = serverPool;
this._config = _.merge({ karma: { waitForCoverageTime: 5 } }, config);
this._coverageDir = path.join(config.karma.basePath, 'coverage');
} | javascript | function KarmaCodeSpecsMatcher(serverPool, config) {
this._serverPool = serverPool;
this._config = _.merge({ karma: { waitForCoverageTime: 5 } }, config);
this._coverageDir = path.join(config.karma.basePath, 'coverage');
} | [
"function",
"KarmaCodeSpecsMatcher",
"(",
"serverPool",
",",
"config",
")",
"{",
"this",
".",
"_serverPool",
"=",
"serverPool",
";",
"this",
".",
"_config",
"=",
"_",
".",
"merge",
"(",
"{",
"karma",
":",
"{",
"waitForCoverageTime",
":",
"5",
"}",
"}",
",",
"config",
")",
";",
"this",
".",
"_coverageDir",
"=",
"path",
".",
"join",
"(",
"config",
".",
"karma",
".",
"basePath",
",",
"'coverage'",
")",
";",
"}"
] | Constructor for the KarmaCodeSpecsMatcher
@param {KarmaServerPool} serverPool Karma server pool used to manage the Karma servers
@param {object} config Configuration object
@constructor | [
"Constructor",
"for",
"the",
"KarmaCodeSpecsMatcher"
] | 698b1b20813cd7d46cf44f09cc016f5cd6460f5f | https://github.com/jimivdw/grunt-mutation-testing/blob/698b1b20813cd7d46cf44f09cc016f5cd6460f5f/lib/karma/KarmaCodeSpecsMatcher.js#L27-L31 | train |
jimivdw/grunt-mutation-testing | utils/ScopeUtils.js | processScopeVariables | function processScopeVariables(variableDeclaration, loopVariables) {
var identifiers = [], exclusiveCombination;
_.forEach(variableDeclaration.declarations, function(declaration) {
identifiers.push(declaration.id.name);
});
exclusiveCombination = _.xor(loopVariables, identifiers);
return _.intersection(loopVariables, exclusiveCombination);
} | javascript | function processScopeVariables(variableDeclaration, loopVariables) {
var identifiers = [], exclusiveCombination;
_.forEach(variableDeclaration.declarations, function(declaration) {
identifiers.push(declaration.id.name);
});
exclusiveCombination = _.xor(loopVariables, identifiers);
return _.intersection(loopVariables, exclusiveCombination);
} | [
"function",
"processScopeVariables",
"(",
"variableDeclaration",
",",
"loopVariables",
")",
"{",
"var",
"identifiers",
"=",
"[",
"]",
",",
"exclusiveCombination",
";",
"_",
".",
"forEach",
"(",
"variableDeclaration",
".",
"declarations",
",",
"function",
"(",
"declaration",
")",
"{",
"identifiers",
".",
"push",
"(",
"declaration",
".",
"id",
".",
"name",
")",
";",
"}",
")",
";",
"exclusiveCombination",
"=",
"_",
".",
"xor",
"(",
"loopVariables",
",",
"identifiers",
")",
";",
"return",
"_",
".",
"intersection",
"(",
"loopVariables",
",",
"exclusiveCombination",
")",
";",
"}"
] | Filters Identifiers within given variableDeclaration out of the loopVariables array.
Filtering occurs as follows:
XOR : (intermediate) result + variable identifiers found => a combined array minus identifiers that overlap
INTERSECTION: (intermediate) result + combined array to filter out variables that weren't in the original loopVariables array
@param {object} variableDeclaration declaration block of one or more variables
@param {loopVariables} loopVariables list of variables that are part of a loop invariable and should therefore not undergo mutations - unless overridden by another variable in the current function scope | [
"Filters",
"Identifiers",
"within",
"given",
"variableDeclaration",
"out",
"of",
"the",
"loopVariables",
"array",
"."
] | 698b1b20813cd7d46cf44f09cc016f5cd6460f5f | https://github.com/jimivdw/grunt-mutation-testing/blob/698b1b20813cd7d46cf44f09cc016f5cd6460f5f/utils/ScopeUtils.js#L56-L65 | train |
cb1kenobi/gawk | src/index.js | filterObject | function filterObject(gobj, filter) {
let found = true;
let obj = gobj;
// find the value we're interested in
for (let i = 0, len = filter.length; obj && typeof obj === 'object' && i < len; i++) {
if (!obj.hasOwnProperty(filter[i])) {
found = false;
obj = undefined;
break;
}
obj = obj[filter[i]];
}
return { found, obj };
} | javascript | function filterObject(gobj, filter) {
let found = true;
let obj = gobj;
// find the value we're interested in
for (let i = 0, len = filter.length; obj && typeof obj === 'object' && i < len; i++) {
if (!obj.hasOwnProperty(filter[i])) {
found = false;
obj = undefined;
break;
}
obj = obj[filter[i]];
}
return { found, obj };
} | [
"function",
"filterObject",
"(",
"gobj",
",",
"filter",
")",
"{",
"let",
"found",
"=",
"true",
";",
"let",
"obj",
"=",
"gobj",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"len",
"=",
"filter",
".",
"length",
";",
"obj",
"&&",
"typeof",
"obj",
"===",
"'object'",
"&&",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"obj",
".",
"hasOwnProperty",
"(",
"filter",
"[",
"i",
"]",
")",
")",
"{",
"found",
"=",
"false",
";",
"obj",
"=",
"undefined",
";",
"break",
";",
"}",
"obj",
"=",
"obj",
"[",
"filter",
"[",
"i",
"]",
"]",
";",
"}",
"return",
"{",
"found",
",",
"obj",
"}",
";",
"}"
] | Filters the specified gawk object.
@param {Object} gobj - A gawked object.
@param {Array.<String>} filter - The filter to apply to the gawked object.
@returns {Object} | [
"Filters",
"the",
"specified",
"gawk",
"object",
"."
] | 17b75ec735907dda1920b03a8ccc7b3821381cd1 | https://github.com/cb1kenobi/gawk/blob/17b75ec735907dda1920b03a8ccc7b3821381cd1/src/index.js#L298-L313 | train |
cb1kenobi/gawk | src/index.js | hashValue | function hashValue(it) {
const str = JSON.stringify(it) || '';
let hash = 5381;
let i = str.length;
while (i) {
hash = hash * 33 ^ str.charCodeAt(--i);
}
return hash >>> 0;
} | javascript | function hashValue(it) {
const str = JSON.stringify(it) || '';
let hash = 5381;
let i = str.length;
while (i) {
hash = hash * 33 ^ str.charCodeAt(--i);
}
return hash >>> 0;
} | [
"function",
"hashValue",
"(",
"it",
")",
"{",
"const",
"str",
"=",
"JSON",
".",
"stringify",
"(",
"it",
")",
"||",
"''",
";",
"let",
"hash",
"=",
"5381",
";",
"let",
"i",
"=",
"str",
".",
"length",
";",
"while",
"(",
"i",
")",
"{",
"hash",
"=",
"hash",
"*",
"33",
"^",
"str",
".",
"charCodeAt",
"(",
"--",
"i",
")",
";",
"}",
"return",
"hash",
">>>",
"0",
";",
"}"
] | Hashes a value quick and dirty.
@param {*} it - A value to hash.
@returns {Number} | [
"Hashes",
"a",
"value",
"quick",
"and",
"dirty",
"."
] | 17b75ec735907dda1920b03a8ccc7b3821381cd1 | https://github.com/cb1kenobi/gawk/blob/17b75ec735907dda1920b03a8ccc7b3821381cd1/src/index.js#L321-L329 | train |
cb1kenobi/gawk | src/index.js | notify | function notify(gobj, source) {
const state = gobj.__gawk__;
if (source === undefined) {
source = gobj;
}
// if we're paused, add this object to the list of objects that may have changed
if (state.queue) {
state.queue.add(gobj);
return;
}
// notify all of this object's listeners
if (state.listeners) {
for (const [ listener, filter ] of state.listeners) {
if (filter) {
const { found, obj } = filterObject(gobj, filter);
// compute the hash of the stringified value
const hash = hashValue(obj);
// check if the value changed
if ((found && !state.previous) || (state.previous && hash !== state.previous.get(listener))) {
listener(obj, source);
}
if (!state.previous) {
state.previous = new WeakMap();
}
state.previous.set(listener, hash);
} else {
listener(gobj, source);
}
}
}
// notify all of this object's parents
if (state.parents) {
for (const parent of state.parents) {
notify(parent, source);
}
}
} | javascript | function notify(gobj, source) {
const state = gobj.__gawk__;
if (source === undefined) {
source = gobj;
}
// if we're paused, add this object to the list of objects that may have changed
if (state.queue) {
state.queue.add(gobj);
return;
}
// notify all of this object's listeners
if (state.listeners) {
for (const [ listener, filter ] of state.listeners) {
if (filter) {
const { found, obj } = filterObject(gobj, filter);
// compute the hash of the stringified value
const hash = hashValue(obj);
// check if the value changed
if ((found && !state.previous) || (state.previous && hash !== state.previous.get(listener))) {
listener(obj, source);
}
if (!state.previous) {
state.previous = new WeakMap();
}
state.previous.set(listener, hash);
} else {
listener(gobj, source);
}
}
}
// notify all of this object's parents
if (state.parents) {
for (const parent of state.parents) {
notify(parent, source);
}
}
} | [
"function",
"notify",
"(",
"gobj",
",",
"source",
")",
"{",
"const",
"state",
"=",
"gobj",
".",
"__gawk__",
";",
"if",
"(",
"source",
"===",
"undefined",
")",
"{",
"source",
"=",
"gobj",
";",
"}",
"if",
"(",
"state",
".",
"queue",
")",
"{",
"state",
".",
"queue",
".",
"add",
"(",
"gobj",
")",
";",
"return",
";",
"}",
"if",
"(",
"state",
".",
"listeners",
")",
"{",
"for",
"(",
"const",
"[",
"listener",
",",
"filter",
"]",
"of",
"state",
".",
"listeners",
")",
"{",
"if",
"(",
"filter",
")",
"{",
"const",
"{",
"found",
",",
"obj",
"}",
"=",
"filterObject",
"(",
"gobj",
",",
"filter",
")",
";",
"const",
"hash",
"=",
"hashValue",
"(",
"obj",
")",
";",
"if",
"(",
"(",
"found",
"&&",
"!",
"state",
".",
"previous",
")",
"||",
"(",
"state",
".",
"previous",
"&&",
"hash",
"!==",
"state",
".",
"previous",
".",
"get",
"(",
"listener",
")",
")",
")",
"{",
"listener",
"(",
"obj",
",",
"source",
")",
";",
"}",
"if",
"(",
"!",
"state",
".",
"previous",
")",
"{",
"state",
".",
"previous",
"=",
"new",
"WeakMap",
"(",
")",
";",
"}",
"state",
".",
"previous",
".",
"set",
"(",
"listener",
",",
"hash",
")",
";",
"}",
"else",
"{",
"listener",
"(",
"gobj",
",",
"source",
")",
";",
"}",
"}",
"}",
"if",
"(",
"state",
".",
"parents",
")",
"{",
"for",
"(",
"const",
"parent",
"of",
"state",
".",
"parents",
")",
"{",
"notify",
"(",
"parent",
",",
"source",
")",
";",
"}",
"}",
"}"
] | Dispatches change notifications to the listeners.
@param {Object} gobj - The gawked object.
@param {Object|Array} [source] - The gawk object that was modified. | [
"Dispatches",
"change",
"notifications",
"to",
"the",
"listeners",
"."
] | 17b75ec735907dda1920b03a8ccc7b3821381cd1 | https://github.com/cb1kenobi/gawk/blob/17b75ec735907dda1920b03a8ccc7b3821381cd1/src/index.js#L337-L381 | train |
cb1kenobi/gawk | src/index.js | copyListeners | function copyListeners(dest, src, compareFn) {
if (isGawked(src) && src.__gawk__.listeners) {
if (dest.__gawk__.listeners) {
for (const [ listener, filter ] of src.__gawk__.listeners) {
dest.__gawk__.listeners.set(listener, filter);
}
} else {
dest.__gawk__.listeners = new Map(src.__gawk__.listeners);
}
}
if (!compareFn) {
return;
}
if (Array.isArray(dest)) {
const visited = [];
for (let i = 0, len = dest.length; i < len; i++) {
if (dest[i] !== null && typeof dest[i] === 'object') {
// try to find a match in src
for (let j = 0, len2 = src.length; j < len2; j++) {
if (!visited[j] && src[j] !== null && typeof src[j] === 'object' && compareFn(dest[i], src[j])) {
visited[j] = 1;
copyListeners(dest[i], src[j], compareFn);
break;
}
}
}
}
return;
}
for (const key of Object.getOwnPropertyNames(dest)) {
if (key === '__gawk__') {
continue;
}
if (dest[key] && typeof dest[key] === 'object') {
copyListeners(dest[key], src[key], compareFn);
}
}
} | javascript | function copyListeners(dest, src, compareFn) {
if (isGawked(src) && src.__gawk__.listeners) {
if (dest.__gawk__.listeners) {
for (const [ listener, filter ] of src.__gawk__.listeners) {
dest.__gawk__.listeners.set(listener, filter);
}
} else {
dest.__gawk__.listeners = new Map(src.__gawk__.listeners);
}
}
if (!compareFn) {
return;
}
if (Array.isArray(dest)) {
const visited = [];
for (let i = 0, len = dest.length; i < len; i++) {
if (dest[i] !== null && typeof dest[i] === 'object') {
// try to find a match in src
for (let j = 0, len2 = src.length; j < len2; j++) {
if (!visited[j] && src[j] !== null && typeof src[j] === 'object' && compareFn(dest[i], src[j])) {
visited[j] = 1;
copyListeners(dest[i], src[j], compareFn);
break;
}
}
}
}
return;
}
for (const key of Object.getOwnPropertyNames(dest)) {
if (key === '__gawk__') {
continue;
}
if (dest[key] && typeof dest[key] === 'object') {
copyListeners(dest[key], src[key], compareFn);
}
}
} | [
"function",
"copyListeners",
"(",
"dest",
",",
"src",
",",
"compareFn",
")",
"{",
"if",
"(",
"isGawked",
"(",
"src",
")",
"&&",
"src",
".",
"__gawk__",
".",
"listeners",
")",
"{",
"if",
"(",
"dest",
".",
"__gawk__",
".",
"listeners",
")",
"{",
"for",
"(",
"const",
"[",
"listener",
",",
"filter",
"]",
"of",
"src",
".",
"__gawk__",
".",
"listeners",
")",
"{",
"dest",
".",
"__gawk__",
".",
"listeners",
".",
"set",
"(",
"listener",
",",
"filter",
")",
";",
"}",
"}",
"else",
"{",
"dest",
".",
"__gawk__",
".",
"listeners",
"=",
"new",
"Map",
"(",
"src",
".",
"__gawk__",
".",
"listeners",
")",
";",
"}",
"}",
"if",
"(",
"!",
"compareFn",
")",
"{",
"return",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"dest",
")",
")",
"{",
"const",
"visited",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"len",
"=",
"dest",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"dest",
"[",
"i",
"]",
"!==",
"null",
"&&",
"typeof",
"dest",
"[",
"i",
"]",
"===",
"'object'",
")",
"{",
"for",
"(",
"let",
"j",
"=",
"0",
",",
"len2",
"=",
"src",
".",
"length",
";",
"j",
"<",
"len2",
";",
"j",
"++",
")",
"{",
"if",
"(",
"!",
"visited",
"[",
"j",
"]",
"&&",
"src",
"[",
"j",
"]",
"!==",
"null",
"&&",
"typeof",
"src",
"[",
"j",
"]",
"===",
"'object'",
"&&",
"compareFn",
"(",
"dest",
"[",
"i",
"]",
",",
"src",
"[",
"j",
"]",
")",
")",
"{",
"visited",
"[",
"j",
"]",
"=",
"1",
";",
"copyListeners",
"(",
"dest",
"[",
"i",
"]",
",",
"src",
"[",
"j",
"]",
",",
"compareFn",
")",
";",
"break",
";",
"}",
"}",
"}",
"}",
"return",
";",
"}",
"for",
"(",
"const",
"key",
"of",
"Object",
".",
"getOwnPropertyNames",
"(",
"dest",
")",
")",
"{",
"if",
"(",
"key",
"===",
"'__gawk__'",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"dest",
"[",
"key",
"]",
"&&",
"typeof",
"dest",
"[",
"key",
"]",
"===",
"'object'",
")",
"{",
"copyListeners",
"(",
"dest",
"[",
"key",
"]",
",",
"src",
"[",
"key",
"]",
",",
"compareFn",
")",
";",
"}",
"}",
"}"
] | Copies listeners from a source gawked object ot a destination gawked object. Note that the
arguments must both be objects and only the `dest` is required to already be gawked.
@param {Object|Array} dest - A gawked object to copy the listeners to.
@param {Object|Array} src - An object to copy the listeners from.
@param {Function} [compareFn] - Doubles up as a deep copy flag and a function to call to compare
a source and destination array elements to check if they are the same. | [
"Copies",
"listeners",
"from",
"a",
"source",
"gawked",
"object",
"ot",
"a",
"destination",
"gawked",
"object",
".",
"Note",
"that",
"the",
"arguments",
"must",
"both",
"be",
"objects",
"and",
"only",
"the",
"dest",
"is",
"required",
"to",
"already",
"be",
"gawked",
"."
] | 17b75ec735907dda1920b03a8ccc7b3821381cd1 | https://github.com/cb1kenobi/gawk/blob/17b75ec735907dda1920b03a8ccc7b3821381cd1/src/index.js#L392-L433 | train |
cb1kenobi/gawk | src/index.js | mix | function mix(objs, deep) {
const gobj = gawk(objs.shift());
if (!isGawked(gobj) || Array.isArray(gobj)) {
throw new TypeError('Expected destination to be a gawked object');
}
if (!objs.length) {
return gobj;
}
// validate the objects are good
for (const obj of objs) {
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
throw new TypeError('Expected merge source to be an object');
}
}
// we need to detach the parent and all listeners so that they will be notified after everything
// has been merged
gobj.__gawk__.pause();
/**
* Mix an object or gawked object into a gawked object.
* @param {Object} gobj - The destination gawked object.
* @param {Object} src - The source object to copy from.
*/
const mixer = (gobj, src) => {
for (const key of Object.getOwnPropertyNames(src)) {
if (key === '__gawk__') {
continue;
}
const srcValue = src[key];
if (deep && srcValue !== null && typeof srcValue === 'object' && !Array.isArray(srcValue)) {
if (!isGawked(gobj[key])) {
gobj[key] = gawk({}, gobj);
}
mixer(gobj[key], srcValue);
} else if (Array.isArray(gobj[key]) && Array.isArray(srcValue)) {
// overwrite destination with new values
gobj[key].splice(0, gobj[key].length, ...srcValue);
} else {
gobj[key] = gawk(srcValue, gobj);
}
}
};
for (const obj of objs) {
mixer(gobj, obj);
}
gobj.__gawk__.resume();
return gobj;
} | javascript | function mix(objs, deep) {
const gobj = gawk(objs.shift());
if (!isGawked(gobj) || Array.isArray(gobj)) {
throw new TypeError('Expected destination to be a gawked object');
}
if (!objs.length) {
return gobj;
}
// validate the objects are good
for (const obj of objs) {
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
throw new TypeError('Expected merge source to be an object');
}
}
// we need to detach the parent and all listeners so that they will be notified after everything
// has been merged
gobj.__gawk__.pause();
/**
* Mix an object or gawked object into a gawked object.
* @param {Object} gobj - The destination gawked object.
* @param {Object} src - The source object to copy from.
*/
const mixer = (gobj, src) => {
for (const key of Object.getOwnPropertyNames(src)) {
if (key === '__gawk__') {
continue;
}
const srcValue = src[key];
if (deep && srcValue !== null && typeof srcValue === 'object' && !Array.isArray(srcValue)) {
if (!isGawked(gobj[key])) {
gobj[key] = gawk({}, gobj);
}
mixer(gobj[key], srcValue);
} else if (Array.isArray(gobj[key]) && Array.isArray(srcValue)) {
// overwrite destination with new values
gobj[key].splice(0, gobj[key].length, ...srcValue);
} else {
gobj[key] = gawk(srcValue, gobj);
}
}
};
for (const obj of objs) {
mixer(gobj, obj);
}
gobj.__gawk__.resume();
return gobj;
} | [
"function",
"mix",
"(",
"objs",
",",
"deep",
")",
"{",
"const",
"gobj",
"=",
"gawk",
"(",
"objs",
".",
"shift",
"(",
")",
")",
";",
"if",
"(",
"!",
"isGawked",
"(",
"gobj",
")",
"||",
"Array",
".",
"isArray",
"(",
"gobj",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Expected destination to be a gawked object'",
")",
";",
"}",
"if",
"(",
"!",
"objs",
".",
"length",
")",
"{",
"return",
"gobj",
";",
"}",
"for",
"(",
"const",
"obj",
"of",
"objs",
")",
"{",
"if",
"(",
"!",
"obj",
"||",
"typeof",
"obj",
"!==",
"'object'",
"||",
"Array",
".",
"isArray",
"(",
"obj",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Expected merge source to be an object'",
")",
";",
"}",
"}",
"gobj",
".",
"__gawk__",
".",
"pause",
"(",
")",
";",
"const",
"mixer",
"=",
"(",
"gobj",
",",
"src",
")",
"=>",
"{",
"for",
"(",
"const",
"key",
"of",
"Object",
".",
"getOwnPropertyNames",
"(",
"src",
")",
")",
"{",
"if",
"(",
"key",
"===",
"'__gawk__'",
")",
"{",
"continue",
";",
"}",
"const",
"srcValue",
"=",
"src",
"[",
"key",
"]",
";",
"if",
"(",
"deep",
"&&",
"srcValue",
"!==",
"null",
"&&",
"typeof",
"srcValue",
"===",
"'object'",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"srcValue",
")",
")",
"{",
"if",
"(",
"!",
"isGawked",
"(",
"gobj",
"[",
"key",
"]",
")",
")",
"{",
"gobj",
"[",
"key",
"]",
"=",
"gawk",
"(",
"{",
"}",
",",
"gobj",
")",
";",
"}",
"mixer",
"(",
"gobj",
"[",
"key",
"]",
",",
"srcValue",
")",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"gobj",
"[",
"key",
"]",
")",
"&&",
"Array",
".",
"isArray",
"(",
"srcValue",
")",
")",
"{",
"gobj",
"[",
"key",
"]",
".",
"splice",
"(",
"0",
",",
"gobj",
"[",
"key",
"]",
".",
"length",
",",
"...",
"srcValue",
")",
";",
"}",
"else",
"{",
"gobj",
"[",
"key",
"]",
"=",
"gawk",
"(",
"srcValue",
",",
"gobj",
")",
";",
"}",
"}",
"}",
";",
"for",
"(",
"const",
"obj",
"of",
"objs",
")",
"{",
"mixer",
"(",
"gobj",
",",
"obj",
")",
";",
"}",
"gobj",
".",
"__gawk__",
".",
"resume",
"(",
")",
";",
"return",
"gobj",
";",
"}"
] | Mixes an array of objects or gawked objects into the specified gawked object.
@param {Array.<Object>} objs - An array of objects or gawked objects.
@param {Boolean} [deep=false] - When true, mixes subobjects into each other.
@returns {Object} | [
"Mixes",
"an",
"array",
"of",
"objects",
"or",
"gawked",
"objects",
"into",
"the",
"specified",
"gawked",
"object",
"."
] | 17b75ec735907dda1920b03a8ccc7b3821381cd1 | https://github.com/cb1kenobi/gawk/blob/17b75ec735907dda1920b03a8ccc7b3821381cd1/src/index.js#L658-L713 | train |
AntonyThorpe/knockout-apollo | demo/bower_components/knockoutjs/src/subscribables/dependentObservable.js | computedBeginDependencyDetectionCallback | function computedBeginDependencyDetectionCallback(subscribable, id) {
var computedObservable = this.computedObservable,
state = computedObservable[computedState];
if (!state.isDisposed) {
if (this.disposalCount && this.disposalCandidates[id]) {
// Don't want to dispose this subscription, as it's still being used
computedObservable.addDependencyTracking(id, subscribable, this.disposalCandidates[id]);
this.disposalCandidates[id] = null; // No need to actually delete the property - disposalCandidates is a transient object anyway
--this.disposalCount;
} else if (!state.dependencyTracking[id]) {
// Brand new subscription - add it
computedObservable.addDependencyTracking(id, subscribable, state.isSleeping ? { _target: subscribable } : computedObservable.subscribeToDependency(subscribable));
}
// If the observable we've accessed has a pending notification, ensure we get notified of the actual final value (bypass equality checks)
if (subscribable._notificationIsPending) {
subscribable._notifyNextChangeIfValueIsDifferent();
}
}
} | javascript | function computedBeginDependencyDetectionCallback(subscribable, id) {
var computedObservable = this.computedObservable,
state = computedObservable[computedState];
if (!state.isDisposed) {
if (this.disposalCount && this.disposalCandidates[id]) {
// Don't want to dispose this subscription, as it's still being used
computedObservable.addDependencyTracking(id, subscribable, this.disposalCandidates[id]);
this.disposalCandidates[id] = null; // No need to actually delete the property - disposalCandidates is a transient object anyway
--this.disposalCount;
} else if (!state.dependencyTracking[id]) {
// Brand new subscription - add it
computedObservable.addDependencyTracking(id, subscribable, state.isSleeping ? { _target: subscribable } : computedObservable.subscribeToDependency(subscribable));
}
// If the observable we've accessed has a pending notification, ensure we get notified of the actual final value (bypass equality checks)
if (subscribable._notificationIsPending) {
subscribable._notifyNextChangeIfValueIsDifferent();
}
}
} | [
"function",
"computedBeginDependencyDetectionCallback",
"(",
"subscribable",
",",
"id",
")",
"{",
"var",
"computedObservable",
"=",
"this",
".",
"computedObservable",
",",
"state",
"=",
"computedObservable",
"[",
"computedState",
"]",
";",
"if",
"(",
"!",
"state",
".",
"isDisposed",
")",
"{",
"if",
"(",
"this",
".",
"disposalCount",
"&&",
"this",
".",
"disposalCandidates",
"[",
"id",
"]",
")",
"{",
"computedObservable",
".",
"addDependencyTracking",
"(",
"id",
",",
"subscribable",
",",
"this",
".",
"disposalCandidates",
"[",
"id",
"]",
")",
";",
"this",
".",
"disposalCandidates",
"[",
"id",
"]",
"=",
"null",
";",
"--",
"this",
".",
"disposalCount",
";",
"}",
"else",
"if",
"(",
"!",
"state",
".",
"dependencyTracking",
"[",
"id",
"]",
")",
"{",
"computedObservable",
".",
"addDependencyTracking",
"(",
"id",
",",
"subscribable",
",",
"state",
".",
"isSleeping",
"?",
"{",
"_target",
":",
"subscribable",
"}",
":",
"computedObservable",
".",
"subscribeToDependency",
"(",
"subscribable",
")",
")",
";",
"}",
"if",
"(",
"subscribable",
".",
"_notificationIsPending",
")",
"{",
"subscribable",
".",
"_notifyNextChangeIfValueIsDifferent",
"(",
")",
";",
"}",
"}",
"}"
] | This function gets called each time a dependency is detected while evaluating a computed. It's factored out as a shared function to avoid creating unnecessary function instances during evaluation. | [
"This",
"function",
"gets",
"called",
"each",
"time",
"a",
"dependency",
"is",
"detected",
"while",
"evaluating",
"a",
"computed",
".",
"It",
"s",
"factored",
"out",
"as",
"a",
"shared",
"function",
"to",
"avoid",
"creating",
"unnecessary",
"function",
"instances",
"during",
"evaluation",
"."
] | 573a7caea7e41877710e69bac001771a6ea86d33 | https://github.com/AntonyThorpe/knockout-apollo/blob/573a7caea7e41877710e69bac001771a6ea86d33/demo/bower_components/knockoutjs/src/subscribables/dependentObservable.js#L126-L144 | train |
rjrodger/seneca-perm | express-example/public/js/cookies.js | function (sKey) {
return decodeURI(document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' + encodeURI(sKey).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')) || null;
} | javascript | function (sKey) {
return decodeURI(document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' + encodeURI(sKey).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')) || null;
} | [
"function",
"(",
"sKey",
")",
"{",
"return",
"decodeURI",
"(",
"document",
".",
"cookie",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"'(?:(?:^|.*;)\\\\s*'",
"+",
"\\\\",
"+",
"encodeURI",
"(",
"sKey",
")",
".",
"replace",
"(",
"/",
"[\\-\\.\\+\\*]",
"/",
"g",
",",
"'\\\\$&'",
")",
")",
",",
"\\\\",
")",
")",
"||",
"null",
";",
"}"
] | Read a cookie. If the cookie doesn't exist a null value will be returned.
### Syntax
Cookies.getItem(name)
### Example usage
Cookies.getItem('test1');
Cookies.getItem('test5');
Cookies.getItem('test1');
Cookies.getItem('test5');
Cookies.getItem('unexistingCookie');
Cookies.getItem();
### Parameters
@param sKey - name - the name of the cookie to read (string).
@returns {string|null} | [
"Read",
"a",
"cookie",
".",
"If",
"the",
"cookie",
"doesn",
"t",
"exist",
"a",
"null",
"value",
"will",
"be",
"returned",
"."
] | cca9169e0d40d9796e11d30c2c878486ecfdcb4a | https://github.com/rjrodger/seneca-perm/blob/cca9169e0d40d9796e11d30c2c878486ecfdcb4a/express-example/public/js/cookies.js#L63-L65 | train |
|
rjrodger/seneca-perm | express-example/public/js/cookies.js | function (sKey, sPath) {
if (!sKey || !this.hasItem(sKey)) { return false; }
document.cookie = encodeURI(sKey) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' + (sPath ? '; path=' + sPath : '');
return true;
} | javascript | function (sKey, sPath) {
if (!sKey || !this.hasItem(sKey)) { return false; }
document.cookie = encodeURI(sKey) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' + (sPath ? '; path=' + sPath : '');
return true;
} | [
"function",
"(",
"sKey",
",",
"sPath",
")",
"{",
"if",
"(",
"!",
"sKey",
"||",
"!",
"this",
".",
"hasItem",
"(",
"sKey",
")",
")",
"{",
"return",
"false",
";",
"}",
"document",
".",
"cookie",
"=",
"encodeURI",
"(",
"sKey",
")",
"+",
"'=; expires=Thu, 01 Jan 1970 00:00:00 GMT'",
"+",
"(",
"sPath",
"?",
"'; path='",
"+",
"sPath",
":",
"''",
")",
";",
"return",
"true",
";",
"}"
] | Delete a cookie
### Syntax
Cookies.removeItem(name[, path])
### Example usage
Cookies.removeItem('test1');
Cookies.removeItem('test5', '/home');
### Parameters
@param sKey - name - the name of the cookie to remove (string).
@param sPath - path (optional) - e.g., "/", "/mydir"; if not specified, defaults to the current path of the current document location (string or null).
@returns {boolean} | [
"Delete",
"a",
"cookie"
] | cca9169e0d40d9796e11d30c2c878486ecfdcb4a | https://github.com/rjrodger/seneca-perm/blob/cca9169e0d40d9796e11d30c2c878486ecfdcb4a/express-example/public/js/cookies.js#L141-L145 | train |
|
knockout/tko.binding.if | dist/tko.binding.if.js | bindingContext | function bindingContext(dataItemOrAccessor, parentContext, dataItemAlias, extendCallback, settings) {
var self = this,
isFunc = typeof(dataItemOrAccessor) == "function" && !isObservable(dataItemOrAccessor),
nodes,
subscribable;
// The binding context object includes static properties for the current, parent, and root view models.
// If a view model is actually stored in an observable, the corresponding binding context object, and
// any child contexts, must be updated when the view model is changed.
function updateContext() {
// Most of the time, the context will directly get a view model object, but if a function is given,
// we call the function to retrieve the view model. If the function accesses any observables or returns
// an observable, the dependency is tracked, and those observables can later cause the binding
// context to be updated.
var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
dataItem = unwrap(dataItemOrObservable);
if (parentContext) {
// When a "parent" context is given, register a dependency on the parent context. Thus whenever the
// parent context is updated, this context will also be updated.
if (parentContext._subscribable)
parentContext._subscribable();
// Copy $root and any custom properties from the parent context
extend(self, parentContext);
// Because the above copy overwrites our own properties, we need to reset them.
self._subscribable = subscribable;
} else {
self.$parents = [];
self.$root = dataItem;
// Export 'ko' in the binding context so it will be available in bindings and templates
// even if 'ko' isn't exported as a global, such as when using an AMD loader.
// See https://github.com/SteveSanderson/knockout/issues/490
self.ko = options.knockoutInstance;
}
self.$rawData = dataItemOrObservable;
self.$data = dataItem;
if (dataItemAlias)
self[dataItemAlias] = dataItem;
// The extendCallback function is provided when creating a child context or extending a context.
// It handles the specific actions needed to finish setting up the binding context. Actions in this
// function could also add dependencies to this binding context.
if (extendCallback)
extendCallback(self, parentContext, dataItem);
return self.$data;
}
function disposeWhen() {
return nodes && !anyDomNodeIsAttachedToDocument(nodes);
}
if (settings && settings.exportDependencies) {
// The "exportDependencies" option means that the calling code will track any dependencies and re-create
// the binding context when they change.
updateContext();
return;
}
subscribable = computed(updateContext, null, { disposeWhen: disposeWhen, disposeWhenNodeIsRemoved: true });
// At this point, the binding context has been initialized, and the "subscribable" computed observable is
// subscribed to any observables that were accessed in the process. If there is nothing to track, the
// computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
// the context object.
if (subscribable.isActive()) {
self._subscribable = subscribable;
// Always notify because even if the model ($data) hasn't changed, other context properties might have changed
subscribable.equalityComparer = null;
// We need to be able to dispose of this computed observable when it's no longer needed. This would be
// easy if we had a single node to watch, but binding contexts can be used by many different nodes, and
// we cannot assume that those nodes have any relation to each other. So instead we track any node that
// the context is attached to, and dispose the computed when all of those nodes have been cleaned.
// Add properties to *subscribable* instead of *self* because any properties added to *self* may be overwritten on updates
nodes = [];
subscribable._addNode = function(node) {
nodes.push(node);
addDisposeCallback(node, function(node) {
arrayRemoveItem(nodes, node);
if (!nodes.length) {
subscribable.dispose();
self._subscribable = subscribable = undefined;
}
});
};
}
} | javascript | function bindingContext(dataItemOrAccessor, parentContext, dataItemAlias, extendCallback, settings) {
var self = this,
isFunc = typeof(dataItemOrAccessor) == "function" && !isObservable(dataItemOrAccessor),
nodes,
subscribable;
// The binding context object includes static properties for the current, parent, and root view models.
// If a view model is actually stored in an observable, the corresponding binding context object, and
// any child contexts, must be updated when the view model is changed.
function updateContext() {
// Most of the time, the context will directly get a view model object, but if a function is given,
// we call the function to retrieve the view model. If the function accesses any observables or returns
// an observable, the dependency is tracked, and those observables can later cause the binding
// context to be updated.
var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
dataItem = unwrap(dataItemOrObservable);
if (parentContext) {
// When a "parent" context is given, register a dependency on the parent context. Thus whenever the
// parent context is updated, this context will also be updated.
if (parentContext._subscribable)
parentContext._subscribable();
// Copy $root and any custom properties from the parent context
extend(self, parentContext);
// Because the above copy overwrites our own properties, we need to reset them.
self._subscribable = subscribable;
} else {
self.$parents = [];
self.$root = dataItem;
// Export 'ko' in the binding context so it will be available in bindings and templates
// even if 'ko' isn't exported as a global, such as when using an AMD loader.
// See https://github.com/SteveSanderson/knockout/issues/490
self.ko = options.knockoutInstance;
}
self.$rawData = dataItemOrObservable;
self.$data = dataItem;
if (dataItemAlias)
self[dataItemAlias] = dataItem;
// The extendCallback function is provided when creating a child context or extending a context.
// It handles the specific actions needed to finish setting up the binding context. Actions in this
// function could also add dependencies to this binding context.
if (extendCallback)
extendCallback(self, parentContext, dataItem);
return self.$data;
}
function disposeWhen() {
return nodes && !anyDomNodeIsAttachedToDocument(nodes);
}
if (settings && settings.exportDependencies) {
// The "exportDependencies" option means that the calling code will track any dependencies and re-create
// the binding context when they change.
updateContext();
return;
}
subscribable = computed(updateContext, null, { disposeWhen: disposeWhen, disposeWhenNodeIsRemoved: true });
// At this point, the binding context has been initialized, and the "subscribable" computed observable is
// subscribed to any observables that were accessed in the process. If there is nothing to track, the
// computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
// the context object.
if (subscribable.isActive()) {
self._subscribable = subscribable;
// Always notify because even if the model ($data) hasn't changed, other context properties might have changed
subscribable.equalityComparer = null;
// We need to be able to dispose of this computed observable when it's no longer needed. This would be
// easy if we had a single node to watch, but binding contexts can be used by many different nodes, and
// we cannot assume that those nodes have any relation to each other. So instead we track any node that
// the context is attached to, and dispose the computed when all of those nodes have been cleaned.
// Add properties to *subscribable* instead of *self* because any properties added to *self* may be overwritten on updates
nodes = [];
subscribable._addNode = function(node) {
nodes.push(node);
addDisposeCallback(node, function(node) {
arrayRemoveItem(nodes, node);
if (!nodes.length) {
subscribable.dispose();
self._subscribable = subscribable = undefined;
}
});
};
}
} | [
"function",
"bindingContext",
"(",
"dataItemOrAccessor",
",",
"parentContext",
",",
"dataItemAlias",
",",
"extendCallback",
",",
"settings",
")",
"{",
"var",
"self",
"=",
"this",
",",
"isFunc",
"=",
"typeof",
"(",
"dataItemOrAccessor",
")",
"==",
"\"function\"",
"&&",
"!",
"isObservable",
"(",
"dataItemOrAccessor",
")",
",",
"nodes",
",",
"subscribable",
";",
"function",
"updateContext",
"(",
")",
"{",
"var",
"dataItemOrObservable",
"=",
"isFunc",
"?",
"dataItemOrAccessor",
"(",
")",
":",
"dataItemOrAccessor",
",",
"dataItem",
"=",
"unwrap",
"(",
"dataItemOrObservable",
")",
";",
"if",
"(",
"parentContext",
")",
"{",
"if",
"(",
"parentContext",
".",
"_subscribable",
")",
"parentContext",
".",
"_subscribable",
"(",
")",
";",
"extend",
"(",
"self",
",",
"parentContext",
")",
";",
"self",
".",
"_subscribable",
"=",
"subscribable",
";",
"}",
"else",
"{",
"self",
".",
"$parents",
"=",
"[",
"]",
";",
"self",
".",
"$root",
"=",
"dataItem",
";",
"self",
".",
"ko",
"=",
"options",
".",
"knockoutInstance",
";",
"}",
"self",
".",
"$rawData",
"=",
"dataItemOrObservable",
";",
"self",
".",
"$data",
"=",
"dataItem",
";",
"if",
"(",
"dataItemAlias",
")",
"self",
"[",
"dataItemAlias",
"]",
"=",
"dataItem",
";",
"if",
"(",
"extendCallback",
")",
"extendCallback",
"(",
"self",
",",
"parentContext",
",",
"dataItem",
")",
";",
"return",
"self",
".",
"$data",
";",
"}",
"function",
"disposeWhen",
"(",
")",
"{",
"return",
"nodes",
"&&",
"!",
"anyDomNodeIsAttachedToDocument",
"(",
"nodes",
")",
";",
"}",
"if",
"(",
"settings",
"&&",
"settings",
".",
"exportDependencies",
")",
"{",
"updateContext",
"(",
")",
";",
"return",
";",
"}",
"subscribable",
"=",
"computed",
"(",
"updateContext",
",",
"null",
",",
"{",
"disposeWhen",
":",
"disposeWhen",
",",
"disposeWhenNodeIsRemoved",
":",
"true",
"}",
")",
";",
"if",
"(",
"subscribable",
".",
"isActive",
"(",
")",
")",
"{",
"self",
".",
"_subscribable",
"=",
"subscribable",
";",
"subscribable",
".",
"equalityComparer",
"=",
"null",
";",
"nodes",
"=",
"[",
"]",
";",
"subscribable",
".",
"_addNode",
"=",
"function",
"(",
"node",
")",
"{",
"nodes",
".",
"push",
"(",
"node",
")",
";",
"addDisposeCallback",
"(",
"node",
",",
"function",
"(",
"node",
")",
"{",
"arrayRemoveItem",
"(",
"nodes",
",",
"node",
")",
";",
"if",
"(",
"!",
"nodes",
".",
"length",
")",
"{",
"subscribable",
".",
"dispose",
"(",
")",
";",
"self",
".",
"_subscribable",
"=",
"subscribable",
"=",
"undefined",
";",
"}",
"}",
")",
";",
"}",
";",
"}",
"}"
] | The bindingContext constructor is only called directly to create the root context. For child contexts, use bindingContext.createChildContext or bindingContext.extend. | [
"The",
"bindingContext",
"constructor",
"is",
"only",
"called",
"directly",
"to",
"create",
"the",
"root",
"context",
".",
"For",
"child",
"contexts",
"use",
"bindingContext",
".",
"createChildContext",
"or",
"bindingContext",
".",
"extend",
"."
] | ab33a6a6fd393077243068d1e79f0be838016cc5 | https://github.com/knockout/tko.binding.if/blob/ab33a6a6fd393077243068d1e79f0be838016cc5/dist/tko.binding.if.js#L1942-L2035 | train |
knockout/tko.binding.if | dist/tko.binding.if.js | updateContext | function updateContext() {
// Most of the time, the context will directly get a view model object, but if a function is given,
// we call the function to retrieve the view model. If the function accesses any observables or returns
// an observable, the dependency is tracked, and those observables can later cause the binding
// context to be updated.
var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
dataItem = unwrap(dataItemOrObservable);
if (parentContext) {
// When a "parent" context is given, register a dependency on the parent context. Thus whenever the
// parent context is updated, this context will also be updated.
if (parentContext._subscribable)
parentContext._subscribable();
// Copy $root and any custom properties from the parent context
extend(self, parentContext);
// Because the above copy overwrites our own properties, we need to reset them.
self._subscribable = subscribable;
} else {
self.$parents = [];
self.$root = dataItem;
// Export 'ko' in the binding context so it will be available in bindings and templates
// even if 'ko' isn't exported as a global, such as when using an AMD loader.
// See https://github.com/SteveSanderson/knockout/issues/490
self.ko = options.knockoutInstance;
}
self.$rawData = dataItemOrObservable;
self.$data = dataItem;
if (dataItemAlias)
self[dataItemAlias] = dataItem;
// The extendCallback function is provided when creating a child context or extending a context.
// It handles the specific actions needed to finish setting up the binding context. Actions in this
// function could also add dependencies to this binding context.
if (extendCallback)
extendCallback(self, parentContext, dataItem);
return self.$data;
} | javascript | function updateContext() {
// Most of the time, the context will directly get a view model object, but if a function is given,
// we call the function to retrieve the view model. If the function accesses any observables or returns
// an observable, the dependency is tracked, and those observables can later cause the binding
// context to be updated.
var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
dataItem = unwrap(dataItemOrObservable);
if (parentContext) {
// When a "parent" context is given, register a dependency on the parent context. Thus whenever the
// parent context is updated, this context will also be updated.
if (parentContext._subscribable)
parentContext._subscribable();
// Copy $root and any custom properties from the parent context
extend(self, parentContext);
// Because the above copy overwrites our own properties, we need to reset them.
self._subscribable = subscribable;
} else {
self.$parents = [];
self.$root = dataItem;
// Export 'ko' in the binding context so it will be available in bindings and templates
// even if 'ko' isn't exported as a global, such as when using an AMD loader.
// See https://github.com/SteveSanderson/knockout/issues/490
self.ko = options.knockoutInstance;
}
self.$rawData = dataItemOrObservable;
self.$data = dataItem;
if (dataItemAlias)
self[dataItemAlias] = dataItem;
// The extendCallback function is provided when creating a child context or extending a context.
// It handles the specific actions needed to finish setting up the binding context. Actions in this
// function could also add dependencies to this binding context.
if (extendCallback)
extendCallback(self, parentContext, dataItem);
return self.$data;
} | [
"function",
"updateContext",
"(",
")",
"{",
"var",
"dataItemOrObservable",
"=",
"isFunc",
"?",
"dataItemOrAccessor",
"(",
")",
":",
"dataItemOrAccessor",
",",
"dataItem",
"=",
"unwrap",
"(",
"dataItemOrObservable",
")",
";",
"if",
"(",
"parentContext",
")",
"{",
"if",
"(",
"parentContext",
".",
"_subscribable",
")",
"parentContext",
".",
"_subscribable",
"(",
")",
";",
"extend",
"(",
"self",
",",
"parentContext",
")",
";",
"self",
".",
"_subscribable",
"=",
"subscribable",
";",
"}",
"else",
"{",
"self",
".",
"$parents",
"=",
"[",
"]",
";",
"self",
".",
"$root",
"=",
"dataItem",
";",
"self",
".",
"ko",
"=",
"options",
".",
"knockoutInstance",
";",
"}",
"self",
".",
"$rawData",
"=",
"dataItemOrObservable",
";",
"self",
".",
"$data",
"=",
"dataItem",
";",
"if",
"(",
"dataItemAlias",
")",
"self",
"[",
"dataItemAlias",
"]",
"=",
"dataItem",
";",
"if",
"(",
"extendCallback",
")",
"extendCallback",
"(",
"self",
",",
"parentContext",
",",
"dataItem",
")",
";",
"return",
"self",
".",
"$data",
";",
"}"
] | The binding context object includes static properties for the current, parent, and root view models. If a view model is actually stored in an observable, the corresponding binding context object, and any child contexts, must be updated when the view model is changed. | [
"The",
"binding",
"context",
"object",
"includes",
"static",
"properties",
"for",
"the",
"current",
"parent",
"and",
"root",
"view",
"models",
".",
"If",
"a",
"view",
"model",
"is",
"actually",
"stored",
"in",
"an",
"observable",
"the",
"corresponding",
"binding",
"context",
"object",
"and",
"any",
"child",
"contexts",
"must",
"be",
"updated",
"when",
"the",
"view",
"model",
"is",
"changed",
"."
] | ab33a6a6fd393077243068d1e79f0be838016cc5 | https://github.com/knockout/tko.binding.if/blob/ab33a6a6fd393077243068d1e79f0be838016cc5/dist/tko.binding.if.js#L1952-L1992 | train |
knockout/tko.binding.if | dist/tko.binding.if.js | cloneIfElseNodes | function cloneIfElseNodes(element, hasElse) {
var children = childNodes(element),
ifNodes = [],
elseNodes = [],
target = ifNodes;
for (var i = 0, j = children.length; i < j; ++i) {
if (hasElse && isElseNode(children[i])) {
target = elseNodes;
hasElse = false;
} else {
target.push(cleanNode(children[i].cloneNode(true)));
}
}
return {
ifNodes: ifNodes,
elseNodes: elseNodes
};
} | javascript | function cloneIfElseNodes(element, hasElse) {
var children = childNodes(element),
ifNodes = [],
elseNodes = [],
target = ifNodes;
for (var i = 0, j = children.length; i < j; ++i) {
if (hasElse && isElseNode(children[i])) {
target = elseNodes;
hasElse = false;
} else {
target.push(cleanNode(children[i].cloneNode(true)));
}
}
return {
ifNodes: ifNodes,
elseNodes: elseNodes
};
} | [
"function",
"cloneIfElseNodes",
"(",
"element",
",",
"hasElse",
")",
"{",
"var",
"children",
"=",
"childNodes",
"(",
"element",
")",
",",
"ifNodes",
"=",
"[",
"]",
",",
"elseNodes",
"=",
"[",
"]",
",",
"target",
"=",
"ifNodes",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"j",
"=",
"children",
".",
"length",
";",
"i",
"<",
"j",
";",
"++",
"i",
")",
"{",
"if",
"(",
"hasElse",
"&&",
"isElseNode",
"(",
"children",
"[",
"i",
"]",
")",
")",
"{",
"target",
"=",
"elseNodes",
";",
"hasElse",
"=",
"false",
";",
"}",
"else",
"{",
"target",
".",
"push",
"(",
"cleanNode",
"(",
"children",
"[",
"i",
"]",
".",
"cloneNode",
"(",
"true",
")",
")",
")",
";",
"}",
"}",
"return",
"{",
"ifNodes",
":",
"ifNodes",
",",
"elseNodes",
":",
"elseNodes",
"}",
";",
"}"
] | Clone the nodes, returning `ifNodes`, `elseNodes`
@param {HTMLElement} element The nodes to be cloned
@param {boolean} hasElse short-circuit to speed up the inner-loop.
@return {object} Containing the cloned nodes. | [
"Clone",
"the",
"nodes",
"returning",
"ifNodes",
"elseNodes"
] | ab33a6a6fd393077243068d1e79f0be838016cc5 | https://github.com/knockout/tko.binding.if/blob/ab33a6a6fd393077243068d1e79f0be838016cc5/dist/tko.binding.if.js#L2534-L2553 | train |
knockout/tko.binding.if | dist/tko.binding.if.js | makeWithIfBinding | function makeWithIfBinding(isWith, isNot, isElse, makeContextCallback) {
return {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var didDisplayOnLastUpdate,
hasElse = detectElse(element),
completesElseChain = observable(),
ifElseNodes,
precedingConditional;
set(element, "conditional", {
elseChainSatisfied: completesElseChain,
});
if (isElse) {
precedingConditional = getPrecedingConditional(element);
}
computed(function() {
var rawValue = valueAccessor(),
dataValue = unwrap(rawValue),
shouldDisplayIf = !isNot !== !dataValue || (isElse && rawValue === undefined), // equivalent to (isNot ? !dataValue : !!dataValue) || isElse && rawValue === undefined
isFirstRender = !ifElseNodes,
needsRefresh = isFirstRender || isWith || (shouldDisplayIf !== didDisplayOnLastUpdate);
if (precedingConditional && precedingConditional.elseChainSatisfied()) {
needsRefresh = shouldDisplayIf !== false;
shouldDisplayIf = false;
completesElseChain(true);
} else {
completesElseChain(shouldDisplayIf);
}
if (!needsRefresh) { return; }
if (isFirstRender && (getDependenciesCount() || hasElse)) {
ifElseNodes = cloneIfElseNodes(element, hasElse);
}
if (shouldDisplayIf) {
if (!isFirstRender || hasElse) {
setDomNodeChildren(element, cloneNodes(ifElseNodes.ifNodes));
}
} else if (ifElseNodes) {
setDomNodeChildren(element, cloneNodes(ifElseNodes.elseNodes));
} else {
emptyNode(element);
}
applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, rawValue) : bindingContext, element);
didDisplayOnLastUpdate = shouldDisplayIf;
}, null, { disposeWhenNodeIsRemoved: element });
return { 'controlsDescendantBindings': true };
},
allowVirtualElements: true,
bindingRewriteValidator: false
};
} | javascript | function makeWithIfBinding(isWith, isNot, isElse, makeContextCallback) {
return {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var didDisplayOnLastUpdate,
hasElse = detectElse(element),
completesElseChain = observable(),
ifElseNodes,
precedingConditional;
set(element, "conditional", {
elseChainSatisfied: completesElseChain,
});
if (isElse) {
precedingConditional = getPrecedingConditional(element);
}
computed(function() {
var rawValue = valueAccessor(),
dataValue = unwrap(rawValue),
shouldDisplayIf = !isNot !== !dataValue || (isElse && rawValue === undefined), // equivalent to (isNot ? !dataValue : !!dataValue) || isElse && rawValue === undefined
isFirstRender = !ifElseNodes,
needsRefresh = isFirstRender || isWith || (shouldDisplayIf !== didDisplayOnLastUpdate);
if (precedingConditional && precedingConditional.elseChainSatisfied()) {
needsRefresh = shouldDisplayIf !== false;
shouldDisplayIf = false;
completesElseChain(true);
} else {
completesElseChain(shouldDisplayIf);
}
if (!needsRefresh) { return; }
if (isFirstRender && (getDependenciesCount() || hasElse)) {
ifElseNodes = cloneIfElseNodes(element, hasElse);
}
if (shouldDisplayIf) {
if (!isFirstRender || hasElse) {
setDomNodeChildren(element, cloneNodes(ifElseNodes.ifNodes));
}
} else if (ifElseNodes) {
setDomNodeChildren(element, cloneNodes(ifElseNodes.elseNodes));
} else {
emptyNode(element);
}
applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, rawValue) : bindingContext, element);
didDisplayOnLastUpdate = shouldDisplayIf;
}, null, { disposeWhenNodeIsRemoved: element });
return { 'controlsDescendantBindings': true };
},
allowVirtualElements: true,
bindingRewriteValidator: false
};
} | [
"function",
"makeWithIfBinding",
"(",
"isWith",
",",
"isNot",
",",
"isElse",
",",
"makeContextCallback",
")",
"{",
"return",
"{",
"init",
":",
"function",
"(",
"element",
",",
"valueAccessor",
",",
"allBindings",
",",
"viewModel",
",",
"bindingContext",
")",
"{",
"var",
"didDisplayOnLastUpdate",
",",
"hasElse",
"=",
"detectElse",
"(",
"element",
")",
",",
"completesElseChain",
"=",
"observable",
"(",
")",
",",
"ifElseNodes",
",",
"precedingConditional",
";",
"set",
"(",
"element",
",",
"\"conditional\"",
",",
"{",
"elseChainSatisfied",
":",
"completesElseChain",
",",
"}",
")",
";",
"if",
"(",
"isElse",
")",
"{",
"precedingConditional",
"=",
"getPrecedingConditional",
"(",
"element",
")",
";",
"}",
"computed",
"(",
"function",
"(",
")",
"{",
"var",
"rawValue",
"=",
"valueAccessor",
"(",
")",
",",
"dataValue",
"=",
"unwrap",
"(",
"rawValue",
")",
",",
"shouldDisplayIf",
"=",
"!",
"isNot",
"!==",
"!",
"dataValue",
"||",
"(",
"isElse",
"&&",
"rawValue",
"===",
"undefined",
")",
",",
"isFirstRender",
"=",
"!",
"ifElseNodes",
",",
"needsRefresh",
"=",
"isFirstRender",
"||",
"isWith",
"||",
"(",
"shouldDisplayIf",
"!==",
"didDisplayOnLastUpdate",
")",
";",
"if",
"(",
"precedingConditional",
"&&",
"precedingConditional",
".",
"elseChainSatisfied",
"(",
")",
")",
"{",
"needsRefresh",
"=",
"shouldDisplayIf",
"!==",
"false",
";",
"shouldDisplayIf",
"=",
"false",
";",
"completesElseChain",
"(",
"true",
")",
";",
"}",
"else",
"{",
"completesElseChain",
"(",
"shouldDisplayIf",
")",
";",
"}",
"if",
"(",
"!",
"needsRefresh",
")",
"{",
"return",
";",
"}",
"if",
"(",
"isFirstRender",
"&&",
"(",
"getDependenciesCount",
"(",
")",
"||",
"hasElse",
")",
")",
"{",
"ifElseNodes",
"=",
"cloneIfElseNodes",
"(",
"element",
",",
"hasElse",
")",
";",
"}",
"if",
"(",
"shouldDisplayIf",
")",
"{",
"if",
"(",
"!",
"isFirstRender",
"||",
"hasElse",
")",
"{",
"setDomNodeChildren",
"(",
"element",
",",
"cloneNodes",
"(",
"ifElseNodes",
".",
"ifNodes",
")",
")",
";",
"}",
"}",
"else",
"if",
"(",
"ifElseNodes",
")",
"{",
"setDomNodeChildren",
"(",
"element",
",",
"cloneNodes",
"(",
"ifElseNodes",
".",
"elseNodes",
")",
")",
";",
"}",
"else",
"{",
"emptyNode",
"(",
"element",
")",
";",
"}",
"applyBindingsToDescendants",
"(",
"makeContextCallback",
"?",
"makeContextCallback",
"(",
"bindingContext",
",",
"rawValue",
")",
":",
"bindingContext",
",",
"element",
")",
";",
"didDisplayOnLastUpdate",
"=",
"shouldDisplayIf",
";",
"}",
",",
"null",
",",
"{",
"disposeWhenNodeIsRemoved",
":",
"element",
"}",
")",
";",
"return",
"{",
"'controlsDescendantBindings'",
":",
"true",
"}",
";",
"}",
",",
"allowVirtualElements",
":",
"true",
",",
"bindingRewriteValidator",
":",
"false",
"}",
";",
"}"
] | Create a DOMbinding that controls DOM nodes presence
Covers e.g.
1. DOM Nodes contents
<div data-bind='if: x'>
<!-- else --> ... an optional "if"
</div>
2. Virtual elements
<!-- ko if: x -->
<!-- else -->
<!-- /ko -->
3. Else binding
<div data-bind='if: x'></div>
<div data-bind='else'></div> | [
"Create",
"a",
"DOMbinding",
"that",
"controls",
"DOM",
"nodes",
"presence"
] | ab33a6a6fd393077243068d1e79f0be838016cc5 | https://github.com/knockout/tko.binding.if/blob/ab33a6a6fd393077243068d1e79f0be838016cc5/dist/tko.binding.if.js#L2596-L2655 | train |
ToMMApps/express-waf | modules/csrf-module.js | filterByUrls | function filterByUrls(url) {
if(_config.refererIndependentUrls) {
var isRefererIndependend = false;
for(var i in _config.refererIndependentUrls) {
if(new RegExp(_config.refererIndependentUrls[i]).test(url.split('?')[0])) {
isRefererIndependend = true;
break;
}
}
return isRefererIndependend;
} else {
return url === '/';
}
} | javascript | function filterByUrls(url) {
if(_config.refererIndependentUrls) {
var isRefererIndependend = false;
for(var i in _config.refererIndependentUrls) {
if(new RegExp(_config.refererIndependentUrls[i]).test(url.split('?')[0])) {
isRefererIndependend = true;
break;
}
}
return isRefererIndependend;
} else {
return url === '/';
}
} | [
"function",
"filterByUrls",
"(",
"url",
")",
"{",
"if",
"(",
"_config",
".",
"refererIndependentUrls",
")",
"{",
"var",
"isRefererIndependend",
"=",
"false",
";",
"for",
"(",
"var",
"i",
"in",
"_config",
".",
"refererIndependentUrls",
")",
"{",
"if",
"(",
"new",
"RegExp",
"(",
"_config",
".",
"refererIndependentUrls",
"[",
"i",
"]",
")",
".",
"test",
"(",
"url",
".",
"split",
"(",
"'?'",
")",
"[",
"0",
"]",
")",
")",
"{",
"isRefererIndependend",
"=",
"true",
";",
"break",
";",
"}",
"}",
"return",
"isRefererIndependend",
";",
"}",
"else",
"{",
"return",
"url",
"===",
"'/'",
";",
"}",
"}"
] | This method checks by configured whitelist, if the url is in the list of allowed urls without a
referer in the header
@param url
@returns {boolean} | [
"This",
"method",
"checks",
"by",
"configured",
"whitelist",
"if",
"the",
"url",
"is",
"in",
"the",
"list",
"of",
"allowed",
"urls",
"without",
"a",
"referer",
"in",
"the",
"header"
] | 5c2c3ec379722d3ee63b3bf8c5fe65d4a0c0bb6a | https://github.com/ToMMApps/express-waf/blob/5c2c3ec379722d3ee63b3bf8c5fe65d4a0c0bb6a/modules/csrf-module.js#L79-L92 | train |
ToMMApps/express-waf | modules/csrf-module.js | filterByMethods | function filterByMethods(req) {
if(_config.allowedMethods) {
return _config.allowedMethods.indexOf(req.method) > -1;
} else if(_config.blockedMethods){
return !(_config.blockedMethods.indexOf(req.method) > -1);
} else {
return true;
}
} | javascript | function filterByMethods(req) {
if(_config.allowedMethods) {
return _config.allowedMethods.indexOf(req.method) > -1;
} else if(_config.blockedMethods){
return !(_config.blockedMethods.indexOf(req.method) > -1);
} else {
return true;
}
} | [
"function",
"filterByMethods",
"(",
"req",
")",
"{",
"if",
"(",
"_config",
".",
"allowedMethods",
")",
"{",
"return",
"_config",
".",
"allowedMethods",
".",
"indexOf",
"(",
"req",
".",
"method",
")",
">",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"_config",
".",
"blockedMethods",
")",
"{",
"return",
"!",
"(",
"_config",
".",
"blockedMethods",
".",
"indexOf",
"(",
"req",
".",
"method",
")",
">",
"-",
"1",
")",
";",
"}",
"else",
"{",
"return",
"true",
";",
"}",
"}"
] | This Method checks by configured black or whitelist, if the REST-Method is allowed or not
If no black or whitelist exists it allows method by default
@param req
@returns {boolean} | [
"This",
"Method",
"checks",
"by",
"configured",
"black",
"or",
"whitelist",
"if",
"the",
"REST",
"-",
"Method",
"is",
"allowed",
"or",
"not",
"If",
"no",
"black",
"or",
"whitelist",
"exists",
"it",
"allows",
"method",
"by",
"default"
] | 5c2c3ec379722d3ee63b3bf8c5fe65d4a0c0bb6a | https://github.com/ToMMApps/express-waf/blob/5c2c3ec379722d3ee63b3bf8c5fe65d4a0c0bb6a/modules/csrf-module.js#L100-L108 | train |
jonschlinkert/arr | index.js | indexOf | function indexOf(arr, value, start) {
start = start || 0;
if (arr == null) {
return -1;
}
var len = arr.length;
var i = start < 0 ? len + start : start;
while (i < len) {
if (arr[i] === value) {
return i;
}
i++;
}
return -1;
} | javascript | function indexOf(arr, value, start) {
start = start || 0;
if (arr == null) {
return -1;
}
var len = arr.length;
var i = start < 0 ? len + start : start;
while (i < len) {
if (arr[i] === value) {
return i;
}
i++;
}
return -1;
} | [
"function",
"indexOf",
"(",
"arr",
",",
"value",
",",
"start",
")",
"{",
"start",
"=",
"start",
"||",
"0",
";",
"if",
"(",
"arr",
"==",
"null",
")",
"{",
"return",
"-",
"1",
";",
"}",
"var",
"len",
"=",
"arr",
".",
"length",
";",
"var",
"i",
"=",
"start",
"<",
"0",
"?",
"len",
"+",
"start",
":",
"start",
";",
"while",
"(",
"i",
"<",
"len",
")",
"{",
"if",
"(",
"arr",
"[",
"i",
"]",
"===",
"value",
")",
"{",
"return",
"i",
";",
"}",
"i",
"++",
";",
"}",
"return",
"-",
"1",
";",
"}"
] | Custom `indexOf` implementation that works with sparse arrays
to provide consisten results in any environment or browser.
@param {Array} `arr`
@param {*} `value`
@param {Array} `start` Optionally define a starting index.
@return {Array} | [
"Custom",
"indexOf",
"implementation",
"that",
"works",
"with",
"sparse",
"arrays",
"to",
"provide",
"consisten",
"results",
"in",
"any",
"environment",
"or",
"browser",
"."
] | a816f3da59bef18a91b8a6936560f723a5cd57f3 | https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L30-L44 | train |
jonschlinkert/arr | index.js | every | function every(arr, cb, thisArg) {
cb = makeIterator(cb, thisArg);
var result = true;
if (arr == null) {
return result;
}
var len = arr.length;
var i = -1;
while (++i < len) {
if (!cb(arr[i], i, arr)) {
result = false;
break;
}
}
return result;
} | javascript | function every(arr, cb, thisArg) {
cb = makeIterator(cb, thisArg);
var result = true;
if (arr == null) {
return result;
}
var len = arr.length;
var i = -1;
while (++i < len) {
if (!cb(arr[i], i, arr)) {
result = false;
break;
}
}
return result;
} | [
"function",
"every",
"(",
"arr",
",",
"cb",
",",
"thisArg",
")",
"{",
"cb",
"=",
"makeIterator",
"(",
"cb",
",",
"thisArg",
")",
";",
"var",
"result",
"=",
"true",
";",
"if",
"(",
"arr",
"==",
"null",
")",
"{",
"return",
"result",
";",
"}",
"var",
"len",
"=",
"arr",
".",
"length",
";",
"var",
"i",
"=",
"-",
"1",
";",
"while",
"(",
"++",
"i",
"<",
"len",
")",
"{",
"if",
"(",
"!",
"cb",
"(",
"arr",
"[",
"i",
"]",
",",
"i",
",",
"arr",
")",
")",
"{",
"result",
"=",
"false",
";",
"break",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | Return `true` if the callback returns `true`
for every element in the `array`.
@param {Array} `array` The array to check.
@param {*} `value`
@return {Boolean} | [
"Return",
"true",
"if",
"the",
"callback",
"returns",
"true",
"for",
"every",
"element",
"in",
"the",
"array",
"."
] | a816f3da59bef18a91b8a6936560f723a5cd57f3 | https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L68-L85 | train |
jonschlinkert/arr | index.js | filter | function filter(arr, cb, thisArg) {
cb = makeIterator(cb, thisArg);
if (arr == null) {
return [];
}
var len = arr.length;
var res = [];
for (var i = 0; i < len; i++) {
var ele = arr[i];
if (cb(ele, i, arr)) {
res.push(ele);
}
}
return res;
} | javascript | function filter(arr, cb, thisArg) {
cb = makeIterator(cb, thisArg);
if (arr == null) {
return [];
}
var len = arr.length;
var res = [];
for (var i = 0; i < len; i++) {
var ele = arr[i];
if (cb(ele, i, arr)) {
res.push(ele);
}
}
return res;
} | [
"function",
"filter",
"(",
"arr",
",",
"cb",
",",
"thisArg",
")",
"{",
"cb",
"=",
"makeIterator",
"(",
"cb",
",",
"thisArg",
")",
";",
"if",
"(",
"arr",
"==",
"null",
")",
"{",
"return",
"[",
"]",
";",
"}",
"var",
"len",
"=",
"arr",
".",
"length",
";",
"var",
"res",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"ele",
"=",
"arr",
"[",
"i",
"]",
";",
"if",
"(",
"cb",
"(",
"ele",
",",
"i",
",",
"arr",
")",
")",
"{",
"res",
".",
"push",
"(",
"ele",
")",
";",
"}",
"}",
"return",
"res",
";",
"}"
] | Like JavaScript's native filter method, but faster.
@param {Array} `arr` The array to filter
@param {Function} `cb` Callback function.
@param {Array} `thisArg`
@return {Array} | [
"Like",
"JavaScript",
"s",
"native",
"filter",
"method",
"but",
"faster",
"."
] | a816f3da59bef18a91b8a6936560f723a5cd57f3 | https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L96-L111 | train |
jonschlinkert/arr | index.js | filterType | function filterType(arr, type) {
var len = arr.length;
var res = [];
for (var i = 0; i < len; i++) {
var ele = arr[i];
if (typeOf(ele) === type) {
res.push(ele);
}
}
return res;
} | javascript | function filterType(arr, type) {
var len = arr.length;
var res = [];
for (var i = 0; i < len; i++) {
var ele = arr[i];
if (typeOf(ele) === type) {
res.push(ele);
}
}
return res;
} | [
"function",
"filterType",
"(",
"arr",
",",
"type",
")",
"{",
"var",
"len",
"=",
"arr",
".",
"length",
";",
"var",
"res",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"ele",
"=",
"arr",
"[",
"i",
"]",
";",
"if",
"(",
"typeOf",
"(",
"ele",
")",
"===",
"type",
")",
"{",
"res",
".",
"push",
"(",
"ele",
")",
";",
"}",
"}",
"return",
"res",
";",
"}"
] | Filter `array`, returning only the values of the given `type`.
```js
var arr = ['a', {a: 'b'}, 1, 'b', 2, {c: 'd'}, 'c'];
utils.filterType(arr, 'object');
//=> [{a: 'b'}, {c: 'd'}]
```
@param {Array} `array`
@param {String} `type` Native type, e.g. `string`, `object`
@return {Boolean}
@api public | [
"Filter",
"array",
"returning",
"only",
"the",
"values",
"of",
"the",
"given",
"type",
"."
] | a816f3da59bef18a91b8a6936560f723a5cd57f3 | https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L129-L139 | train |
jonschlinkert/arr | index.js | strings | function strings(arr, i) {
var values = filterType(arr, 'string');
return i ? values[i] : values;
} | javascript | function strings(arr, i) {
var values = filterType(arr, 'string');
return i ? values[i] : values;
} | [
"function",
"strings",
"(",
"arr",
",",
"i",
")",
"{",
"var",
"values",
"=",
"filterType",
"(",
"arr",
",",
"'string'",
")",
";",
"return",
"i",
"?",
"values",
"[",
"i",
"]",
":",
"values",
";",
"}"
] | Filter `array`, returning only the strings.
```js
var arr = ['a', {a: 'b'}, 1, 'b', 2, {c: 'd'}, 'c'];
utils.strings(arr);
//=> ['a', 'b', 'c']
```
@param {Array} `array`
@param {Array} `index` Optionally specify the index of the string to return, otherwise all strings are returned.
@return {Array} Array of strings or empty array.
@api public | [
"Filter",
"array",
"returning",
"only",
"the",
"strings",
"."
] | a816f3da59bef18a91b8a6936560f723a5cd57f3 | https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L296-L299 | train |
jonschlinkert/arr | index.js | objects | function objects(arr, i) {
var values = filterType(arr, 'object');
return i ? values[i] : values;
} | javascript | function objects(arr, i) {
var values = filterType(arr, 'object');
return i ? values[i] : values;
} | [
"function",
"objects",
"(",
"arr",
",",
"i",
")",
"{",
"var",
"values",
"=",
"filterType",
"(",
"arr",
",",
"'object'",
")",
";",
"return",
"i",
"?",
"values",
"[",
"i",
"]",
":",
"values",
";",
"}"
] | Filter `array`, returning only the objects.
```js
var arr = ['a', {a: 'b'}, 1, 'b', 2, {c: 'd'}, 'c'];
utils.objects(arr);
//=> [{a: 'b'}, {c: 'd'}]
```
@param {Array} `array`
@param {Array} `index` Optionally specify the index of the object to return, otherwise all objects are returned.
@return {Array} Array of objects or empty array.
@api public | [
"Filter",
"array",
"returning",
"only",
"the",
"objects",
"."
] | a816f3da59bef18a91b8a6936560f723a5cd57f3 | https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L317-L320 | train |
jonschlinkert/arr | index.js | functions | function functions(arr, i) {
var values = filterType(arr, 'function');
return i ? values[i] : values;
} | javascript | function functions(arr, i) {
var values = filterType(arr, 'function');
return i ? values[i] : values;
} | [
"function",
"functions",
"(",
"arr",
",",
"i",
")",
"{",
"var",
"values",
"=",
"filterType",
"(",
"arr",
",",
"'function'",
")",
";",
"return",
"i",
"?",
"values",
"[",
"i",
"]",
":",
"values",
";",
"}"
] | Filter `array`, returning only the functions.
```js
var one = function() {};
var two = function() {};
var arr = ['a', {a: 'b'}, 1, one, 'b', 2, {c: 'd'}, two, 'c'];
utils.functions(arr);
//=> [one, two]
```
@param {Array} `array`
@param {Array} `index` Optionally specify the index of the function to return, otherwise all functions are returned.
@return {Array} Array of functions or empty array.
@api public | [
"Filter",
"array",
"returning",
"only",
"the",
"functions",
"."
] | a816f3da59bef18a91b8a6936560f723a5cd57f3 | https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L340-L343 | train |
jonschlinkert/arr | index.js | arrays | function arrays(arr, i) {
var values = filterType(arr, 'array');
return i ? values[i] : values;
} | javascript | function arrays(arr, i) {
var values = filterType(arr, 'array');
return i ? values[i] : values;
} | [
"function",
"arrays",
"(",
"arr",
",",
"i",
")",
"{",
"var",
"values",
"=",
"filterType",
"(",
"arr",
",",
"'array'",
")",
";",
"return",
"i",
"?",
"values",
"[",
"i",
"]",
":",
"values",
";",
"}"
] | Filter `array`, returning only the arrays.
```js
var arr = ['a', ['aaa'], 1, 'b', ['bbb'], 2, {c: 'd'}, 'c'];
utils.objects(arr);
//=> [['aaa'], ['bbb']]
```
@param {Array} `array`
@param {Array} `index` Optionally specify the index of the array to return, otherwise all arrays are returned.
@return {Array} Array of arrays or empty array.
@api public | [
"Filter",
"array",
"returning",
"only",
"the",
"arrays",
"."
] | a816f3da59bef18a91b8a6936560f723a5cd57f3 | https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L361-L364 | train |
jonschlinkert/arr | index.js | first | function first(arr, cb, thisArg) {
if (arguments.length === 1) {
return arr[0];
}
if (typeOf(cb) === 'string') {
return findFirst(arr, isType(cb));
}
return findFirst(arr, cb, thisArg);
} | javascript | function first(arr, cb, thisArg) {
if (arguments.length === 1) {
return arr[0];
}
if (typeOf(cb) === 'string') {
return findFirst(arr, isType(cb));
}
return findFirst(arr, cb, thisArg);
} | [
"function",
"first",
"(",
"arr",
",",
"cb",
",",
"thisArg",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
")",
"{",
"return",
"arr",
"[",
"0",
"]",
";",
"}",
"if",
"(",
"typeOf",
"(",
"cb",
")",
"===",
"'string'",
")",
"{",
"return",
"findFirst",
"(",
"arr",
",",
"isType",
"(",
"cb",
")",
")",
";",
"}",
"return",
"findFirst",
"(",
"arr",
",",
"cb",
",",
"thisArg",
")",
";",
"}"
] | Return the first element in `array`, or, if a callback is passed,
return the first value for which the returns true.
```js
var arr = ['a', {a: 'b'}, 1, one, 'b', 2, {c: 'd'}, two, 'c'];
utils.first(arr);
//=> 'a'
utils.first(arr, isType('object'));
//=> {a: 'b'}
utils.first(arr, 'object');
//=> {a: 'b'}
```
@param {Array} `array`
@return {*}
@api public | [
"Return",
"the",
"first",
"element",
"in",
"array",
"or",
"if",
"a",
"callback",
"is",
"passed",
"return",
"the",
"first",
"value",
"for",
"which",
"the",
"returns",
"true",
"."
] | a816f3da59bef18a91b8a6936560f723a5cd57f3 | https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L388-L396 | train |
jonschlinkert/arr | index.js | last | function last(arr, cb, thisArg) {
if (arguments.length === 1) {
return arr[arr.length - 1];
}
if (typeOf(cb) === 'string') {
return findLast(arr, isType(cb));
}
return findLast(arr, cb, thisArg);
} | javascript | function last(arr, cb, thisArg) {
if (arguments.length === 1) {
return arr[arr.length - 1];
}
if (typeOf(cb) === 'string') {
return findLast(arr, isType(cb));
}
return findLast(arr, cb, thisArg);
} | [
"function",
"last",
"(",
"arr",
",",
"cb",
",",
"thisArg",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
")",
"{",
"return",
"arr",
"[",
"arr",
".",
"length",
"-",
"1",
"]",
";",
"}",
"if",
"(",
"typeOf",
"(",
"cb",
")",
"===",
"'string'",
")",
"{",
"return",
"findLast",
"(",
"arr",
",",
"isType",
"(",
"cb",
")",
")",
";",
"}",
"return",
"findLast",
"(",
"arr",
",",
"cb",
",",
"thisArg",
")",
";",
"}"
] | Return the last element in `array`, or, if a callback is passed,
return the last value for which the returns true.
```js
// `one` and `two` are functions
var arr = ['a', {a: 'b'}, 1, one, 'b', 2, {c: 'd'}, two, 'c'];
utils.last(arr);
//=> 'c'
utils.last(arr, isType('function'));
//=> two
utils.last(arr, 'object');
//=> {c: 'd'}
```
@param {Array} `array`
@return {*}
@api public | [
"Return",
"the",
"last",
"element",
"in",
"array",
"or",
"if",
"a",
"callback",
"is",
"passed",
"return",
"the",
"last",
"value",
"for",
"which",
"the",
"returns",
"true",
"."
] | a816f3da59bef18a91b8a6936560f723a5cd57f3 | https://github.com/jonschlinkert/arr/blob/a816f3da59bef18a91b8a6936560f723a5cd57f3/index.js#L420-L428 | train |
hiproxy/open-browser | lib/index.js | function (browser, url, proxyURL, pacFileURL, dataDir, bypassList) {
// Firefox pac set
// http://www.indexdata.com/connector-platform/enginedoc/proxy-auto.html
// http://kb.mozillazine.org/Network.proxy.autoconfig_url
// user_pref("network.proxy.autoconfig_url", "http://us2.indexdata.com:9005/id/cf.pac");
// user_pref("network.proxy.type", 2);
return this.detect(browser).then(function (browserPath) {
if (!browserPath) {
throw Error('[Error] can not find browser ' + browser);
} else {
dataDir = dataDir || path.join(os.tmpdir(), 'op-browser');
if (os.platform() === 'win32') {
browserPath = '"' + browserPath + '"';
}
var commandOptions = configUtil[browser](dataDir, url, browserPath, proxyURL, pacFileURL, bypassList);
return new Promise(function (resolve, reject) {
var cmdStr = browserPath + ' ' + commandOptions;
childProcess.exec(cmdStr, {maxBuffer: 50000 * 1024}, function (err) {
if (err) {
reject(err);
} else {
resolve({
path: browserPath,
cmdOptions: commandOptions,
proxyURL: proxyURL,
pacFileURL: pacFileURL
});
}
});
});
}
});
} | javascript | function (browser, url, proxyURL, pacFileURL, dataDir, bypassList) {
// Firefox pac set
// http://www.indexdata.com/connector-platform/enginedoc/proxy-auto.html
// http://kb.mozillazine.org/Network.proxy.autoconfig_url
// user_pref("network.proxy.autoconfig_url", "http://us2.indexdata.com:9005/id/cf.pac");
// user_pref("network.proxy.type", 2);
return this.detect(browser).then(function (browserPath) {
if (!browserPath) {
throw Error('[Error] can not find browser ' + browser);
} else {
dataDir = dataDir || path.join(os.tmpdir(), 'op-browser');
if (os.platform() === 'win32') {
browserPath = '"' + browserPath + '"';
}
var commandOptions = configUtil[browser](dataDir, url, browserPath, proxyURL, pacFileURL, bypassList);
return new Promise(function (resolve, reject) {
var cmdStr = browserPath + ' ' + commandOptions;
childProcess.exec(cmdStr, {maxBuffer: 50000 * 1024}, function (err) {
if (err) {
reject(err);
} else {
resolve({
path: browserPath,
cmdOptions: commandOptions,
proxyURL: proxyURL,
pacFileURL: pacFileURL
});
}
});
});
}
});
} | [
"function",
"(",
"browser",
",",
"url",
",",
"proxyURL",
",",
"pacFileURL",
",",
"dataDir",
",",
"bypassList",
")",
"{",
"return",
"this",
".",
"detect",
"(",
"browser",
")",
".",
"then",
"(",
"function",
"(",
"browserPath",
")",
"{",
"if",
"(",
"!",
"browserPath",
")",
"{",
"throw",
"Error",
"(",
"'[Error] can not find browser '",
"+",
"browser",
")",
";",
"}",
"else",
"{",
"dataDir",
"=",
"dataDir",
"||",
"path",
".",
"join",
"(",
"os",
".",
"tmpdir",
"(",
")",
",",
"'op-browser'",
")",
";",
"if",
"(",
"os",
".",
"platform",
"(",
")",
"===",
"'win32'",
")",
"{",
"browserPath",
"=",
"'\"'",
"+",
"browserPath",
"+",
"'\"'",
";",
"}",
"var",
"commandOptions",
"=",
"configUtil",
"[",
"browser",
"]",
"(",
"dataDir",
",",
"url",
",",
"browserPath",
",",
"proxyURL",
",",
"pacFileURL",
",",
"bypassList",
")",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"cmdStr",
"=",
"browserPath",
"+",
"' '",
"+",
"commandOptions",
";",
"childProcess",
".",
"exec",
"(",
"cmdStr",
",",
"{",
"maxBuffer",
":",
"50000",
"*",
"1024",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
"else",
"{",
"resolve",
"(",
"{",
"path",
":",
"browserPath",
",",
"cmdOptions",
":",
"commandOptions",
",",
"proxyURL",
":",
"proxyURL",
",",
"pacFileURL",
":",
"pacFileURL",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | open browser window, if the `pacFileURL` is not empty, will use `proxy auto-configuration`
@memberof op-browser
@param {String} browser the browser's name
@param {String} url the url that to open
@param {String} proxyURL the proxy url, format: `http://<hostname>[:[port]]`
@param {String} pacFileURL the proxy url, format: `http://<hostname>[:[port]]/[pac-file-name]`
@param {String} dataDir the user data directory
@param {String} bypassList the list of hosts for whom we bypass proxy settings and use direct connections. the list of hosts for whom we bypass proxy settings and use direct connections, See: "[net/proxy/proxy_bypass_rules.h](https://cs.chromium.org/chromium/src/net/proxy_resolution/proxy_bypass_rules.h?sq=package:chromium&type=cs)" for the format of these rules
@return {Promise} | [
"open",
"browser",
"window",
"if",
"the",
"pacFileURL",
"is",
"not",
"empty",
"will",
"use",
"proxy",
"auto",
"-",
"configuration"
] | bc88e3ab741d1bac8d4358a60e8ba5a273a3ea38 | https://github.com/hiproxy/open-browser/blob/bc88e3ab741d1bac8d4358a60e8ba5a273a3ea38/lib/index.js#L54-L90 | train |
|
infrabel/themes-gnap | raw/bootstrap/docs/assets/js/vendor/holder.js | extend | function extend(a,b){
var c={};
for(var i in a){
if(a.hasOwnProperty(i)){
c[i]=a[i];
}
}
for(var i in b){
if(b.hasOwnProperty(i)){
c[i]=b[i];
}
}
return c
} | javascript | function extend(a,b){
var c={};
for(var i in a){
if(a.hasOwnProperty(i)){
c[i]=a[i];
}
}
for(var i in b){
if(b.hasOwnProperty(i)){
c[i]=b[i];
}
}
return c
} | [
"function",
"extend",
"(",
"a",
",",
"b",
")",
"{",
"var",
"c",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"in",
"a",
")",
"{",
"if",
"(",
"a",
".",
"hasOwnProperty",
"(",
"i",
")",
")",
"{",
"c",
"[",
"i",
"]",
"=",
"a",
"[",
"i",
"]",
";",
"}",
"}",
"for",
"(",
"var",
"i",
"in",
"b",
")",
"{",
"if",
"(",
"b",
".",
"hasOwnProperty",
"(",
"i",
")",
")",
"{",
"c",
"[",
"i",
"]",
"=",
"b",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"c",
"}"
] | shallow object property extend | [
"shallow",
"object",
"property",
"extend"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/bootstrap/docs/assets/js/vendor/holder.js#L624-L637 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/bootstrap-colorpicker.js | function(){
try {
this.preview.backgroundColor = this.format.call(this);
} catch(e) {
this.preview.backgroundColor = this.color.toHex();
}
//set the color for brightness/saturation slider
this.base.backgroundColor = this.color.toHex(this.color.value.h, 1, 1, 1);
//set te color for alpha slider
if (this.alpha) {
this.alpha.backgroundColor = this.color.toHex();
}
} | javascript | function(){
try {
this.preview.backgroundColor = this.format.call(this);
} catch(e) {
this.preview.backgroundColor = this.color.toHex();
}
//set the color for brightness/saturation slider
this.base.backgroundColor = this.color.toHex(this.color.value.h, 1, 1, 1);
//set te color for alpha slider
if (this.alpha) {
this.alpha.backgroundColor = this.color.toHex();
}
} | [
"function",
"(",
")",
"{",
"try",
"{",
"this",
".",
"preview",
".",
"backgroundColor",
"=",
"this",
".",
"format",
".",
"call",
"(",
"this",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"this",
".",
"preview",
".",
"backgroundColor",
"=",
"this",
".",
"color",
".",
"toHex",
"(",
")",
";",
"}",
"this",
".",
"base",
".",
"backgroundColor",
"=",
"this",
".",
"color",
".",
"toHex",
"(",
"this",
".",
"color",
".",
"value",
".",
"h",
",",
"1",
",",
"1",
",",
"1",
")",
";",
"if",
"(",
"this",
".",
"alpha",
")",
"{",
"this",
".",
"alpha",
".",
"backgroundColor",
"=",
"this",
".",
"color",
".",
"toHex",
"(",
")",
";",
"}",
"}"
] | preview color change | [
"preview",
"color",
"change"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/bootstrap-colorpicker.js#L248-L260 | train |
|
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/jquery.gritter.js | function(unique_id, e, manual_close){
// Remove it then run the callback function
e.remove();
this['_after_close_' + unique_id](e, manual_close);
// Check if the wrapper is empty, if it is.. remove the wrapper
if($('.gritter-item-wrapper').length == 0){
$('#gritter-notice-wrapper').remove();
}
} | javascript | function(unique_id, e, manual_close){
// Remove it then run the callback function
e.remove();
this['_after_close_' + unique_id](e, manual_close);
// Check if the wrapper is empty, if it is.. remove the wrapper
if($('.gritter-item-wrapper').length == 0){
$('#gritter-notice-wrapper').remove();
}
} | [
"function",
"(",
"unique_id",
",",
"e",
",",
"manual_close",
")",
"{",
"e",
".",
"remove",
"(",
")",
";",
"this",
"[",
"'_after_close_'",
"+",
"unique_id",
"]",
"(",
"e",
",",
"manual_close",
")",
";",
"if",
"(",
"$",
"(",
"'.gritter-item-wrapper'",
")",
".",
"length",
"==",
"0",
")",
"{",
"$",
"(",
"'#gritter-notice-wrapper'",
")",
".",
"remove",
"(",
")",
";",
"}",
"}"
] | If we don't have any more gritter notifications, get rid of the wrapper using this check
@private
@param {Integer} unique_id The ID of the element that was just deleted, use it for a callback
@param {Object} e The jQuery element that we're going to perform the remove() action on
@param {Boolean} manual_close Did we close the gritter dialog with the (X) button | [
"If",
"we",
"don",
"t",
"have",
"any",
"more",
"gritter",
"notifications",
"get",
"rid",
"of",
"the",
"wrapper",
"using",
"this",
"check"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/jquery.gritter.js#L198-L209 | train |
|
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/jquery.gritter.js | function(e, unique_id, params, unbind_events){
var params = params || {},
fade = (typeof(params.fade) != 'undefined') ? params.fade : true,
fade_out_speed = params.speed || this.fade_out_speed,
manual_close = unbind_events;
this['_before_close_' + unique_id](e, manual_close);
// If this is true, then we are coming from clicking the (X)
if(unbind_events){
e.unbind('mouseenter mouseleave');
}
// Fade it out or remove it
if(fade){
e.animate({
opacity: 0
}, fade_out_speed, function(){
e.animate({ height: 0 }, 300, function(){
Gritter._countRemoveWrapper(unique_id, e, manual_close);
})
})
}
else {
this._countRemoveWrapper(unique_id, e);
}
} | javascript | function(e, unique_id, params, unbind_events){
var params = params || {},
fade = (typeof(params.fade) != 'undefined') ? params.fade : true,
fade_out_speed = params.speed || this.fade_out_speed,
manual_close = unbind_events;
this['_before_close_' + unique_id](e, manual_close);
// If this is true, then we are coming from clicking the (X)
if(unbind_events){
e.unbind('mouseenter mouseleave');
}
// Fade it out or remove it
if(fade){
e.animate({
opacity: 0
}, fade_out_speed, function(){
e.animate({ height: 0 }, 300, function(){
Gritter._countRemoveWrapper(unique_id, e, manual_close);
})
})
}
else {
this._countRemoveWrapper(unique_id, e);
}
} | [
"function",
"(",
"e",
",",
"unique_id",
",",
"params",
",",
"unbind_events",
")",
"{",
"var",
"params",
"=",
"params",
"||",
"{",
"}",
",",
"fade",
"=",
"(",
"typeof",
"(",
"params",
".",
"fade",
")",
"!=",
"'undefined'",
")",
"?",
"params",
".",
"fade",
":",
"true",
",",
"fade_out_speed",
"=",
"params",
".",
"speed",
"||",
"this",
".",
"fade_out_speed",
",",
"manual_close",
"=",
"unbind_events",
";",
"this",
"[",
"'_before_close_'",
"+",
"unique_id",
"]",
"(",
"e",
",",
"manual_close",
")",
";",
"if",
"(",
"unbind_events",
")",
"{",
"e",
".",
"unbind",
"(",
"'mouseenter mouseleave'",
")",
";",
"}",
"if",
"(",
"fade",
")",
"{",
"e",
".",
"animate",
"(",
"{",
"opacity",
":",
"0",
"}",
",",
"fade_out_speed",
",",
"function",
"(",
")",
"{",
"e",
".",
"animate",
"(",
"{",
"height",
":",
"0",
"}",
",",
"300",
",",
"function",
"(",
")",
"{",
"Gritter",
".",
"_countRemoveWrapper",
"(",
"unique_id",
",",
"e",
",",
"manual_close",
")",
";",
"}",
")",
"}",
")",
"}",
"else",
"{",
"this",
".",
"_countRemoveWrapper",
"(",
"unique_id",
",",
"e",
")",
";",
"}",
"}"
] | Fade out an element after it's been on the screen for x amount of time
@private
@param {Object} e The jQuery element to get rid of
@param {Integer} unique_id The id of the element to remove
@param {Object} params An optional list of params to set fade speeds etc.
@param {Boolean} unbind_events Unbind the mouseenter/mouseleave events if they click (X) | [
"Fade",
"out",
"an",
"element",
"after",
"it",
"s",
"been",
"on",
"the",
"screen",
"for",
"x",
"amount",
"of",
"time"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/jquery.gritter.js#L219-L251 | train |
|
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/jquery.gritter.js | function(unique_id, params, e, unbind_events){
if(!e){
var e = $('#gritter-item-' + unique_id);
}
// We set the fourth param to let the _fade function know to
// unbind the "mouseleave" event. Once you click (X) there's no going back!
this._fade(e, unique_id, params || {}, unbind_events);
} | javascript | function(unique_id, params, e, unbind_events){
if(!e){
var e = $('#gritter-item-' + unique_id);
}
// We set the fourth param to let the _fade function know to
// unbind the "mouseleave" event. Once you click (X) there's no going back!
this._fade(e, unique_id, params || {}, unbind_events);
} | [
"function",
"(",
"unique_id",
",",
"params",
",",
"e",
",",
"unbind_events",
")",
"{",
"if",
"(",
"!",
"e",
")",
"{",
"var",
"e",
"=",
"$",
"(",
"'#gritter-item-'",
"+",
"unique_id",
")",
";",
"}",
"this",
".",
"_fade",
"(",
"e",
",",
"unique_id",
",",
"params",
"||",
"{",
"}",
",",
"unbind_events",
")",
";",
"}"
] | Remove a specific notification based on an ID
@param {Integer} unique_id The ID used to delete a specific notification
@param {Object} params A set of options passed in to determine how to get rid of it
@param {Object} e The jQuery element that we're "fading" then removing
@param {Boolean} unbind_events If we clicked on the (X) we set this to true to unbind mouseenter/mouseleave | [
"Remove",
"a",
"specific",
"notification",
"based",
"on",
"an",
"ID"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/jquery.gritter.js#L289-L299 | train |
|
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/jquery.gritter.js | function(e, unique_id){
var timer_str = (this._custom_timer) ? this._custom_timer : this.time;
this['_int_id_' + unique_id] = setTimeout(function(){
Gritter._fade(e, unique_id);
}, timer_str);
} | javascript | function(e, unique_id){
var timer_str = (this._custom_timer) ? this._custom_timer : this.time;
this['_int_id_' + unique_id] = setTimeout(function(){
Gritter._fade(e, unique_id);
}, timer_str);
} | [
"function",
"(",
"e",
",",
"unique_id",
")",
"{",
"var",
"timer_str",
"=",
"(",
"this",
".",
"_custom_timer",
")",
"?",
"this",
".",
"_custom_timer",
":",
"this",
".",
"time",
";",
"this",
"[",
"'_int_id_'",
"+",
"unique_id",
"]",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"Gritter",
".",
"_fade",
"(",
"e",
",",
"unique_id",
")",
";",
"}",
",",
"timer_str",
")",
";",
"}"
] | Set the notification to fade out after a certain amount of time
@private
@param {Object} item The HTML element we're dealing with
@param {Integer} unique_id The ID of the element | [
"Set",
"the",
"notification",
"to",
"fade",
"out",
"after",
"a",
"certain",
"amount",
"of",
"time"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/jquery.gritter.js#L333-L340 | train |
|
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/jquery.gritter.js | function(params){
// callbacks (if passed)
var before_close = ($.isFunction(params.before_close)) ? params.before_close : function(){};
var after_close = ($.isFunction(params.after_close)) ? params.after_close : function(){};
var wrap = $('#gritter-notice-wrapper');
before_close(wrap);
wrap.fadeOut(function(){
$(this).remove();
after_close();
});
} | javascript | function(params){
// callbacks (if passed)
var before_close = ($.isFunction(params.before_close)) ? params.before_close : function(){};
var after_close = ($.isFunction(params.after_close)) ? params.after_close : function(){};
var wrap = $('#gritter-notice-wrapper');
before_close(wrap);
wrap.fadeOut(function(){
$(this).remove();
after_close();
});
} | [
"function",
"(",
"params",
")",
"{",
"var",
"before_close",
"=",
"(",
"$",
".",
"isFunction",
"(",
"params",
".",
"before_close",
")",
")",
"?",
"params",
".",
"before_close",
":",
"function",
"(",
")",
"{",
"}",
";",
"var",
"after_close",
"=",
"(",
"$",
".",
"isFunction",
"(",
"params",
".",
"after_close",
")",
")",
"?",
"params",
".",
"after_close",
":",
"function",
"(",
")",
"{",
"}",
";",
"var",
"wrap",
"=",
"$",
"(",
"'#gritter-notice-wrapper'",
")",
";",
"before_close",
"(",
"wrap",
")",
";",
"wrap",
".",
"fadeOut",
"(",
"function",
"(",
")",
"{",
"$",
"(",
"this",
")",
".",
"remove",
"(",
")",
";",
"after_close",
"(",
")",
";",
"}",
")",
";",
"}"
] | Bring everything to a halt
@param {Object} params A list of callback functions to pass when all notifications are removed | [
"Bring",
"everything",
"to",
"a",
"halt"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/jquery.gritter.js#L346-L359 | train |
|
jimivdw/grunt-mutation-testing | lib/reporting/html/HtmlReporter.js | function(basePath, config) {
this._basePath = basePath;
this._config = config;
var directories = IOUtils.getDirectoryList(basePath, false);
IOUtils.createPathIfNotExists(directories, './');
} | javascript | function(basePath, config) {
this._basePath = basePath;
this._config = config;
var directories = IOUtils.getDirectoryList(basePath, false);
IOUtils.createPathIfNotExists(directories, './');
} | [
"function",
"(",
"basePath",
",",
"config",
")",
"{",
"this",
".",
"_basePath",
"=",
"basePath",
";",
"this",
".",
"_config",
"=",
"config",
";",
"var",
"directories",
"=",
"IOUtils",
".",
"getDirectoryList",
"(",
"basePath",
",",
"false",
")",
";",
"IOUtils",
".",
"createPathIfNotExists",
"(",
"directories",
",",
"'./'",
")",
";",
"}"
] | Constructor for the HTML reporter.
@param {string} basePath The base path where the report should be created
@param {object=} config Configuration object
@constructor | [
"Constructor",
"for",
"the",
"HTML",
"reporter",
"."
] | 698b1b20813cd7d46cf44f09cc016f5cd6460f5f | https://github.com/jimivdw/grunt-mutation-testing/blob/698b1b20813cd7d46cf44f09cc016f5cd6460f5f/lib/reporting/html/HtmlReporter.js#L29-L35 | train |
|
infrabel/themes-gnap | raw/angular-dynamic-locale/tmhDynamicLocale.js | loadScript | function loadScript(url, callback, errorCallback, $timeout) {
var script = document.createElement('script'),
body = document.getElementsByTagName('body')[0],
removed = false;
script.type = 'text/javascript';
if (script.readyState) { // IE
script.onreadystatechange = function () {
if (script.readyState === 'complete' ||
script.readyState === 'loaded') {
script.onreadystatechange = null;
$timeout(
function () {
if (removed) return;
removed = true;
body.removeChild(script);
callback();
}, 30, false);
}
};
} else { // Others
script.onload = function () {
if (removed) return;
removed = true;
body.removeChild(script);
callback();
};
script.onerror = function () {
if (removed) return;
removed = true;
body.removeChild(script);
errorCallback();
};
}
script.src = url;
script.async = false;
body.appendChild(script);
} | javascript | function loadScript(url, callback, errorCallback, $timeout) {
var script = document.createElement('script'),
body = document.getElementsByTagName('body')[0],
removed = false;
script.type = 'text/javascript';
if (script.readyState) { // IE
script.onreadystatechange = function () {
if (script.readyState === 'complete' ||
script.readyState === 'loaded') {
script.onreadystatechange = null;
$timeout(
function () {
if (removed) return;
removed = true;
body.removeChild(script);
callback();
}, 30, false);
}
};
} else { // Others
script.onload = function () {
if (removed) return;
removed = true;
body.removeChild(script);
callback();
};
script.onerror = function () {
if (removed) return;
removed = true;
body.removeChild(script);
errorCallback();
};
}
script.src = url;
script.async = false;
body.appendChild(script);
} | [
"function",
"loadScript",
"(",
"url",
",",
"callback",
",",
"errorCallback",
",",
"$timeout",
")",
"{",
"var",
"script",
"=",
"document",
".",
"createElement",
"(",
"'script'",
")",
",",
"body",
"=",
"document",
".",
"getElementsByTagName",
"(",
"'body'",
")",
"[",
"0",
"]",
",",
"removed",
"=",
"false",
";",
"script",
".",
"type",
"=",
"'text/javascript'",
";",
"if",
"(",
"script",
".",
"readyState",
")",
"{",
"script",
".",
"onreadystatechange",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"script",
".",
"readyState",
"===",
"'complete'",
"||",
"script",
".",
"readyState",
"===",
"'loaded'",
")",
"{",
"script",
".",
"onreadystatechange",
"=",
"null",
";",
"$timeout",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"removed",
")",
"return",
";",
"removed",
"=",
"true",
";",
"body",
".",
"removeChild",
"(",
"script",
")",
";",
"callback",
"(",
")",
";",
"}",
",",
"30",
",",
"false",
")",
";",
"}",
"}",
";",
"}",
"else",
"{",
"script",
".",
"onload",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"removed",
")",
"return",
";",
"removed",
"=",
"true",
";",
"body",
".",
"removeChild",
"(",
"script",
")",
";",
"callback",
"(",
")",
";",
"}",
";",
"script",
".",
"onerror",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"removed",
")",
"return",
";",
"removed",
"=",
"true",
";",
"body",
".",
"removeChild",
"(",
"script",
")",
";",
"errorCallback",
"(",
")",
";",
"}",
";",
"}",
"script",
".",
"src",
"=",
"url",
";",
"script",
".",
"async",
"=",
"false",
";",
"body",
".",
"appendChild",
"(",
"script",
")",
";",
"}"
] | Loads a script asynchronously
@param {string} url The url for the script
@ @param {function) callback A function to be called once the script is loaded | [
"Loads",
"a",
"script",
"asynchronously"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/angular-dynamic-locale/tmhDynamicLocale.js#L19-L56 | train |
infrabel/themes-gnap | raw/angular-dynamic-locale/tmhDynamicLocale.js | loadLocale | function loadLocale(localeUrl, $locale, localeId, $rootScope, $q, localeCache, $timeout) {
function overrideValues(oldObject, newObject) {
if (activeLocale !== localeId) {
return;
}
angular.forEach(oldObject, function(value, key) {
if (!newObject[key]) {
delete oldObject[key];
} else if (angular.isArray(newObject[key])) {
oldObject[key].length = newObject[key].length;
}
});
angular.forEach(newObject, function(value, key) {
if (angular.isArray(newObject[key]) || angular.isObject(newObject[key])) {
if (!oldObject[key]) {
oldObject[key] = angular.isArray(newObject[key]) ? [] : {};
}
overrideValues(oldObject[key], newObject[key]);
} else {
oldObject[key] = newObject[key];
}
});
}
if (promiseCache[localeId]) return promiseCache[localeId];
var cachedLocale,
deferred = $q.defer();
if (localeId === activeLocale) {
deferred.resolve($locale);
} else if ((cachedLocale = localeCache.get(localeId))) {
activeLocale = localeId;
$rootScope.$evalAsync(function() {
overrideValues($locale, cachedLocale);
$rootScope.$broadcast('$localeChangeSuccess', localeId, $locale);
storage.put(storeKey, localeId);
deferred.resolve($locale);
});
} else {
activeLocale = localeId;
promiseCache[localeId] = deferred.promise;
loadScript(localeUrl, function () {
// Create a new injector with the new locale
var localInjector = angular.injector(['ngLocale']),
externalLocale = localInjector.get('$locale');
overrideValues($locale, externalLocale);
localeCache.put(localeId, externalLocale);
delete promiseCache[localeId];
$rootScope.$apply(function () {
$rootScope.$broadcast('$localeChangeSuccess', localeId, $locale);
storage.put(storeKey, localeId);
deferred.resolve($locale);
});
}, function () {
delete promiseCache[localeId];
$rootScope.$apply(function () {
$rootScope.$broadcast('$localeChangeError', localeId);
deferred.reject(localeId);
});
}, $timeout);
}
return deferred.promise;
} | javascript | function loadLocale(localeUrl, $locale, localeId, $rootScope, $q, localeCache, $timeout) {
function overrideValues(oldObject, newObject) {
if (activeLocale !== localeId) {
return;
}
angular.forEach(oldObject, function(value, key) {
if (!newObject[key]) {
delete oldObject[key];
} else if (angular.isArray(newObject[key])) {
oldObject[key].length = newObject[key].length;
}
});
angular.forEach(newObject, function(value, key) {
if (angular.isArray(newObject[key]) || angular.isObject(newObject[key])) {
if (!oldObject[key]) {
oldObject[key] = angular.isArray(newObject[key]) ? [] : {};
}
overrideValues(oldObject[key], newObject[key]);
} else {
oldObject[key] = newObject[key];
}
});
}
if (promiseCache[localeId]) return promiseCache[localeId];
var cachedLocale,
deferred = $q.defer();
if (localeId === activeLocale) {
deferred.resolve($locale);
} else if ((cachedLocale = localeCache.get(localeId))) {
activeLocale = localeId;
$rootScope.$evalAsync(function() {
overrideValues($locale, cachedLocale);
$rootScope.$broadcast('$localeChangeSuccess', localeId, $locale);
storage.put(storeKey, localeId);
deferred.resolve($locale);
});
} else {
activeLocale = localeId;
promiseCache[localeId] = deferred.promise;
loadScript(localeUrl, function () {
// Create a new injector with the new locale
var localInjector = angular.injector(['ngLocale']),
externalLocale = localInjector.get('$locale');
overrideValues($locale, externalLocale);
localeCache.put(localeId, externalLocale);
delete promiseCache[localeId];
$rootScope.$apply(function () {
$rootScope.$broadcast('$localeChangeSuccess', localeId, $locale);
storage.put(storeKey, localeId);
deferred.resolve($locale);
});
}, function () {
delete promiseCache[localeId];
$rootScope.$apply(function () {
$rootScope.$broadcast('$localeChangeError', localeId);
deferred.reject(localeId);
});
}, $timeout);
}
return deferred.promise;
} | [
"function",
"loadLocale",
"(",
"localeUrl",
",",
"$locale",
",",
"localeId",
",",
"$rootScope",
",",
"$q",
",",
"localeCache",
",",
"$timeout",
")",
"{",
"function",
"overrideValues",
"(",
"oldObject",
",",
"newObject",
")",
"{",
"if",
"(",
"activeLocale",
"!==",
"localeId",
")",
"{",
"return",
";",
"}",
"angular",
".",
"forEach",
"(",
"oldObject",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"if",
"(",
"!",
"newObject",
"[",
"key",
"]",
")",
"{",
"delete",
"oldObject",
"[",
"key",
"]",
";",
"}",
"else",
"if",
"(",
"angular",
".",
"isArray",
"(",
"newObject",
"[",
"key",
"]",
")",
")",
"{",
"oldObject",
"[",
"key",
"]",
".",
"length",
"=",
"newObject",
"[",
"key",
"]",
".",
"length",
";",
"}",
"}",
")",
";",
"angular",
".",
"forEach",
"(",
"newObject",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"if",
"(",
"angular",
".",
"isArray",
"(",
"newObject",
"[",
"key",
"]",
")",
"||",
"angular",
".",
"isObject",
"(",
"newObject",
"[",
"key",
"]",
")",
")",
"{",
"if",
"(",
"!",
"oldObject",
"[",
"key",
"]",
")",
"{",
"oldObject",
"[",
"key",
"]",
"=",
"angular",
".",
"isArray",
"(",
"newObject",
"[",
"key",
"]",
")",
"?",
"[",
"]",
":",
"{",
"}",
";",
"}",
"overrideValues",
"(",
"oldObject",
"[",
"key",
"]",
",",
"newObject",
"[",
"key",
"]",
")",
";",
"}",
"else",
"{",
"oldObject",
"[",
"key",
"]",
"=",
"newObject",
"[",
"key",
"]",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"promiseCache",
"[",
"localeId",
"]",
")",
"return",
"promiseCache",
"[",
"localeId",
"]",
";",
"var",
"cachedLocale",
",",
"deferred",
"=",
"$q",
".",
"defer",
"(",
")",
";",
"if",
"(",
"localeId",
"===",
"activeLocale",
")",
"{",
"deferred",
".",
"resolve",
"(",
"$locale",
")",
";",
"}",
"else",
"if",
"(",
"(",
"cachedLocale",
"=",
"localeCache",
".",
"get",
"(",
"localeId",
")",
")",
")",
"{",
"activeLocale",
"=",
"localeId",
";",
"$rootScope",
".",
"$evalAsync",
"(",
"function",
"(",
")",
"{",
"overrideValues",
"(",
"$locale",
",",
"cachedLocale",
")",
";",
"$rootScope",
".",
"$broadcast",
"(",
"'$localeChangeSuccess'",
",",
"localeId",
",",
"$locale",
")",
";",
"storage",
".",
"put",
"(",
"storeKey",
",",
"localeId",
")",
";",
"deferred",
".",
"resolve",
"(",
"$locale",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"activeLocale",
"=",
"localeId",
";",
"promiseCache",
"[",
"localeId",
"]",
"=",
"deferred",
".",
"promise",
";",
"loadScript",
"(",
"localeUrl",
",",
"function",
"(",
")",
"{",
"var",
"localInjector",
"=",
"angular",
".",
"injector",
"(",
"[",
"'ngLocale'",
"]",
")",
",",
"externalLocale",
"=",
"localInjector",
".",
"get",
"(",
"'$locale'",
")",
";",
"overrideValues",
"(",
"$locale",
",",
"externalLocale",
")",
";",
"localeCache",
".",
"put",
"(",
"localeId",
",",
"externalLocale",
")",
";",
"delete",
"promiseCache",
"[",
"localeId",
"]",
";",
"$rootScope",
".",
"$apply",
"(",
"function",
"(",
")",
"{",
"$rootScope",
".",
"$broadcast",
"(",
"'$localeChangeSuccess'",
",",
"localeId",
",",
"$locale",
")",
";",
"storage",
".",
"put",
"(",
"storeKey",
",",
"localeId",
")",
";",
"deferred",
".",
"resolve",
"(",
"$locale",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
")",
"{",
"delete",
"promiseCache",
"[",
"localeId",
"]",
";",
"$rootScope",
".",
"$apply",
"(",
"function",
"(",
")",
"{",
"$rootScope",
".",
"$broadcast",
"(",
"'$localeChangeError'",
",",
"localeId",
")",
";",
"deferred",
".",
"reject",
"(",
"localeId",
")",
";",
"}",
")",
";",
"}",
",",
"$timeout",
")",
";",
"}",
"return",
"deferred",
".",
"promise",
";",
"}"
] | Loads a locale and replaces the properties from the current locale with the new locale information
@param localeUrl The path to the new locale
@param $locale The locale at the curent scope | [
"Loads",
"a",
"locale",
"and",
"replaces",
"the",
"properties",
"from",
"the",
"current",
"locale",
"with",
"the",
"new",
"locale",
"information"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/angular-dynamic-locale/tmhDynamicLocale.js#L64-L131 | train |
kenahrens/newrelic-api-client-js | scripts/get-expirations.js | outputFile | function outputFile(configId, outputdata){
var fname= configId+ '_accounts.csv';
console.log("Outputing file... "+fname);
var input= {
data: outputdata,
fields: ['id','name','status','subscriptionStarts','subscriptionExpires']
};
json2csv(input, function(err, csv) {
if (err) {
console.log('ERROR!');
console.log(err);
} else {
fs.writeFileSync(fname,csv);
}
});
} | javascript | function outputFile(configId, outputdata){
var fname= configId+ '_accounts.csv';
console.log("Outputing file... "+fname);
var input= {
data: outputdata,
fields: ['id','name','status','subscriptionStarts','subscriptionExpires']
};
json2csv(input, function(err, csv) {
if (err) {
console.log('ERROR!');
console.log(err);
} else {
fs.writeFileSync(fname,csv);
}
});
} | [
"function",
"outputFile",
"(",
"configId",
",",
"outputdata",
")",
"{",
"var",
"fname",
"=",
"configId",
"+",
"'_accounts.csv'",
";",
"console",
".",
"log",
"(",
"\"Outputing file... \"",
"+",
"fname",
")",
";",
"var",
"input",
"=",
"{",
"data",
":",
"outputdata",
",",
"fields",
":",
"[",
"'id'",
",",
"'name'",
",",
"'status'",
",",
"'subscriptionStarts'",
",",
"'subscriptionExpires'",
"]",
"}",
";",
"json2csv",
"(",
"input",
",",
"function",
"(",
"err",
",",
"csv",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"'ERROR!'",
")",
";",
"console",
".",
"log",
"(",
"err",
")",
";",
"}",
"else",
"{",
"fs",
".",
"writeFileSync",
"(",
"fname",
",",
"csv",
")",
";",
"}",
"}",
")",
";",
"}"
] | Get all the accounts and apikeys for a partner account, output as CSV Write the output file | [
"Get",
"all",
"the",
"accounts",
"and",
"apikeys",
"for",
"a",
"partner",
"account",
"output",
"as",
"CSV",
"Write",
"the",
"output",
"file"
] | 0776c66e3959ab489f600c16dba4ec9f62f99d2a | https://github.com/kenahrens/newrelic-api-client-js/blob/0776c66e3959ab489f600c16dba4ec9f62f99d2a/scripts/get-expirations.js#L14-L29 | train |
RoganMurley/hitagi.js | src/utils.js | function (originalObj, originalProp, targetObj, targetProp) {
Object.defineProperty(
originalObj,
originalProp,
{
get: function () {
return targetObj[targetProp];
},
set: function (newValue) {
targetObj[targetProp] = newValue;
}
}
);
} | javascript | function (originalObj, originalProp, targetObj, targetProp) {
Object.defineProperty(
originalObj,
originalProp,
{
get: function () {
return targetObj[targetProp];
},
set: function (newValue) {
targetObj[targetProp] = newValue;
}
}
);
} | [
"function",
"(",
"originalObj",
",",
"originalProp",
",",
"targetObj",
",",
"targetProp",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"originalObj",
",",
"originalProp",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"targetObj",
"[",
"targetProp",
"]",
";",
"}",
",",
"set",
":",
"function",
"(",
"newValue",
")",
"{",
"targetObj",
"[",
"targetProp",
"]",
"=",
"newValue",
";",
"}",
"}",
")",
";",
"}"
] | Proxy a property, simillar to the proxy in ES6. Allows us to propagate changes to the target property. | [
"Proxy",
"a",
"property",
"simillar",
"to",
"the",
"proxy",
"in",
"ES6",
".",
"Allows",
"us",
"to",
"propagate",
"changes",
"to",
"the",
"target",
"property",
"."
] | 6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053 | https://github.com/RoganMurley/hitagi.js/blob/6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053/src/utils.js#L17-L30 | train |
|
RoganMurley/hitagi.js | src/utils.js | function (originalObj, originalProp, targetObj, targetProp) {
Object.defineProperty(
originalObj,
originalProp,
{
get: function () {
return targetObj[targetProp];
},
set: function (newValue) {
console.error(targetProp + ' is read-only.');
throw new Error('ReadOnly');
}
}
);
} | javascript | function (originalObj, originalProp, targetObj, targetProp) {
Object.defineProperty(
originalObj,
originalProp,
{
get: function () {
return targetObj[targetProp];
},
set: function (newValue) {
console.error(targetProp + ' is read-only.');
throw new Error('ReadOnly');
}
}
);
} | [
"function",
"(",
"originalObj",
",",
"originalProp",
",",
"targetObj",
",",
"targetProp",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"originalObj",
",",
"originalProp",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"targetObj",
"[",
"targetProp",
"]",
";",
"}",
",",
"set",
":",
"function",
"(",
"newValue",
")",
"{",
"console",
".",
"error",
"(",
"targetProp",
"+",
"' is read-only.'",
")",
";",
"throw",
"new",
"Error",
"(",
"'ReadOnly'",
")",
";",
"}",
"}",
")",
";",
"}"
] | A read-only version of proxy, see above. | [
"A",
"read",
"-",
"only",
"version",
"of",
"proxy",
"see",
"above",
"."
] | 6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053 | https://github.com/RoganMurley/hitagi.js/blob/6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053/src/utils.js#L34-L48 | train |
|
RoganMurley/hitagi.js | src/utils.js | function (obj, prop, callback, callbackParams) {
var value = obj[prop];
Object.defineProperty(
obj,
prop,
{
get: function () {
return value;
},
set: function (newValue) {
value = newValue;
callback(newValue, callbackParams);
}
}
);
} | javascript | function (obj, prop, callback, callbackParams) {
var value = obj[prop];
Object.defineProperty(
obj,
prop,
{
get: function () {
return value;
},
set: function (newValue) {
value = newValue;
callback(newValue, callbackParams);
}
}
);
} | [
"function",
"(",
"obj",
",",
"prop",
",",
"callback",
",",
"callbackParams",
")",
"{",
"var",
"value",
"=",
"obj",
"[",
"prop",
"]",
";",
"Object",
".",
"defineProperty",
"(",
"obj",
",",
"prop",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"value",
";",
"}",
",",
"set",
":",
"function",
"(",
"newValue",
")",
"{",
"value",
"=",
"newValue",
";",
"callback",
"(",
"newValue",
",",
"callbackParams",
")",
";",
"}",
"}",
")",
";",
"}"
] | Watches a property, executing a callback when the property changes. | [
"Watches",
"a",
"property",
"executing",
"a",
"callback",
"when",
"the",
"property",
"changes",
"."
] | 6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053 | https://github.com/RoganMurley/hitagi.js/blob/6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053/src/utils.js#L52-L68 | train |
|
kenahrens/newrelic-api-client-js | scripts/dashboard-from-json.js | function(error, response, body) {
var rspBody = helper.handleCB(error, response, body);
if (rspBody != null) {
var destId = config.get(program.dest).accountId;
var url = 'http://insights.newrelic.com/accounts/' + destId + '/dashboards/' + rspBody.dashboard.id;
console.log('Dashboard created: ' + url);
}
} | javascript | function(error, response, body) {
var rspBody = helper.handleCB(error, response, body);
if (rspBody != null) {
var destId = config.get(program.dest).accountId;
var url = 'http://insights.newrelic.com/accounts/' + destId + '/dashboards/' + rspBody.dashboard.id;
console.log('Dashboard created: ' + url);
}
} | [
"function",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"var",
"rspBody",
"=",
"helper",
".",
"handleCB",
"(",
"error",
",",
"response",
",",
"body",
")",
";",
"if",
"(",
"rspBody",
"!=",
"null",
")",
"{",
"var",
"destId",
"=",
"config",
".",
"get",
"(",
"program",
".",
"dest",
")",
".",
"accountId",
";",
"var",
"url",
"=",
"'http://insights.newrelic.com/accounts/'",
"+",
"destId",
"+",
"'/dashboards/'",
"+",
"rspBody",
".",
"dashboard",
".",
"id",
";",
"console",
".",
"log",
"(",
"'Dashboard created: '",
"+",
"url",
")",
";",
"}",
"}"
] | Print out the URL of the newly created dashboard | [
"Print",
"out",
"the",
"URL",
"of",
"the",
"newly",
"created",
"dashboard"
] | 0776c66e3959ab489f600c16dba4ec9f62f99d2a | https://github.com/kenahrens/newrelic-api-client-js/blob/0776c66e3959ab489f600c16dba4ec9f62f99d2a/scripts/dashboard-from-json.js#L8-L15 | train |
|
kenahrens/newrelic-api-client-js | scripts/dashboard-from-json.js | readDashFromFS | function readDashFromFS(fname) {
var dashboardBody = fs.readFileSync(fname);
console.log('Read file:', fname);
// Set the proper account_id on all widgets
if (dashboardBody != null) {
dashboardBody = JSON.parse(dashboardBody);
console.log('Read source dashboard named: ' + dashboardBody.dashboard.title);
var destId = config.get(program.dest).accountId;
dashboardBody = dashboards.updateAccountId(dashboardBody, 1, destId);
console.log(dashboardBody);
} else {
console.error('Problem reading file', fname);
}
return dashboardBody;
} | javascript | function readDashFromFS(fname) {
var dashboardBody = fs.readFileSync(fname);
console.log('Read file:', fname);
// Set the proper account_id on all widgets
if (dashboardBody != null) {
dashboardBody = JSON.parse(dashboardBody);
console.log('Read source dashboard named: ' + dashboardBody.dashboard.title);
var destId = config.get(program.dest).accountId;
dashboardBody = dashboards.updateAccountId(dashboardBody, 1, destId);
console.log(dashboardBody);
} else {
console.error('Problem reading file', fname);
}
return dashboardBody;
} | [
"function",
"readDashFromFS",
"(",
"fname",
")",
"{",
"var",
"dashboardBody",
"=",
"fs",
".",
"readFileSync",
"(",
"fname",
")",
";",
"console",
".",
"log",
"(",
"'Read file:'",
",",
"fname",
")",
";",
"if",
"(",
"dashboardBody",
"!=",
"null",
")",
"{",
"dashboardBody",
"=",
"JSON",
".",
"parse",
"(",
"dashboardBody",
")",
";",
"console",
".",
"log",
"(",
"'Read source dashboard named: '",
"+",
"dashboardBody",
".",
"dashboard",
".",
"title",
")",
";",
"var",
"destId",
"=",
"config",
".",
"get",
"(",
"program",
".",
"dest",
")",
".",
"accountId",
";",
"dashboardBody",
"=",
"dashboards",
".",
"updateAccountId",
"(",
"dashboardBody",
",",
"1",
",",
"destId",
")",
";",
"console",
".",
"log",
"(",
"dashboardBody",
")",
";",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"'Problem reading file'",
",",
"fname",
")",
";",
"}",
"return",
"dashboardBody",
";",
"}"
] | Read the source dashboard from the file system | [
"Read",
"the",
"source",
"dashboard",
"from",
"the",
"file",
"system"
] | 0776c66e3959ab489f600c16dba4ec9f62f99d2a | https://github.com/kenahrens/newrelic-api-client-js/blob/0776c66e3959ab489f600c16dba4ec9f62f99d2a/scripts/dashboard-from-json.js#L18-L36 | train |
dominicbarnes/node-couchdb-api | docs/render.js | function (done) {
glob(path.join(__dirname, "*.ejs"), function (err, files) {
if (err) {
return done(err);
}
var templates = {};
async.forEach(files, function (file, done) {
fs.readFile(file, "utf8", function (err, data) {
if (err) {
return done(err);
} else {
templates[path.basename(file, ".ejs")] = _.template(data);
done();
}
});
}, function (err) {
if (err) {
return done(err);
}
done(null, templates);
});
});
} | javascript | function (done) {
glob(path.join(__dirname, "*.ejs"), function (err, files) {
if (err) {
return done(err);
}
var templates = {};
async.forEach(files, function (file, done) {
fs.readFile(file, "utf8", function (err, data) {
if (err) {
return done(err);
} else {
templates[path.basename(file, ".ejs")] = _.template(data);
done();
}
});
}, function (err) {
if (err) {
return done(err);
}
done(null, templates);
});
});
} | [
"function",
"(",
"done",
")",
"{",
"glob",
"(",
"path",
".",
"join",
"(",
"__dirname",
",",
"\"*.ejs\"",
")",
",",
"function",
"(",
"err",
",",
"files",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"done",
"(",
"err",
")",
";",
"}",
"var",
"templates",
"=",
"{",
"}",
";",
"async",
".",
"forEach",
"(",
"files",
",",
"function",
"(",
"file",
",",
"done",
")",
"{",
"fs",
".",
"readFile",
"(",
"file",
",",
"\"utf8\"",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"done",
"(",
"err",
")",
";",
"}",
"else",
"{",
"templates",
"[",
"path",
".",
"basename",
"(",
"file",
",",
"\".ejs\"",
")",
"]",
"=",
"_",
".",
"template",
"(",
"data",
")",
";",
"done",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"done",
"(",
"err",
")",
";",
"}",
"done",
"(",
"null",
",",
"templates",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | gather the templates | [
"gather",
"the",
"templates"
] | 4363d9b41fddd39db201472c44116aab1a010d99 | https://github.com/dominicbarnes/node-couchdb-api/blob/4363d9b41fddd39db201472c44116aab1a010d99/docs/render.js#L11-L36 | train |
|
RoganMurley/hitagi.js | examples/example4/example4.js | function () {
this.update = {
gravity: function (entity, dt) {
// Accelerate entity until it reaches terminal velocity.
if (entity.c.velocity.yspeed < entity.c.gravity.terminal) {
entity.c.velocity.yspeed += hitagi.utils.delta(entity.c.gravity.magnitude, dt);
}
}
};
} | javascript | function () {
this.update = {
gravity: function (entity, dt) {
// Accelerate entity until it reaches terminal velocity.
if (entity.c.velocity.yspeed < entity.c.gravity.terminal) {
entity.c.velocity.yspeed += hitagi.utils.delta(entity.c.gravity.magnitude, dt);
}
}
};
} | [
"function",
"(",
")",
"{",
"this",
".",
"update",
"=",
"{",
"gravity",
":",
"function",
"(",
"entity",
",",
"dt",
")",
"{",
"if",
"(",
"entity",
".",
"c",
".",
"velocity",
".",
"yspeed",
"<",
"entity",
".",
"c",
".",
"gravity",
".",
"terminal",
")",
"{",
"entity",
".",
"c",
".",
"velocity",
".",
"yspeed",
"+=",
"hitagi",
".",
"utils",
".",
"delta",
"(",
"entity",
".",
"c",
".",
"gravity",
".",
"magnitude",
",",
"dt",
")",
";",
"}",
"}",
"}",
";",
"}"
] | Define systems. | [
"Define",
"systems",
"."
] | 6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053 | https://github.com/RoganMurley/hitagi.js/blob/6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053/examples/example4/example4.js#L17-L26 | train |
|
AntonyThorpe/knockout-apollo | demo/src/viewModel.js | function(data) {
//initialise with a few Todos because we are very busy people
self.todoList.insert(data.data.todoList);
self.todoList2.insert(data.data.todoList);
self.todoList3.insert(data.data.todoList);
self.todoList4.insert(data.data.todoList);
} | javascript | function(data) {
//initialise with a few Todos because we are very busy people
self.todoList.insert(data.data.todoList);
self.todoList2.insert(data.data.todoList);
self.todoList3.insert(data.data.todoList);
self.todoList4.insert(data.data.todoList);
} | [
"function",
"(",
"data",
")",
"{",
"self",
".",
"todoList",
".",
"insert",
"(",
"data",
".",
"data",
".",
"todoList",
")",
";",
"self",
".",
"todoList2",
".",
"insert",
"(",
"data",
".",
"data",
".",
"todoList",
")",
";",
"self",
".",
"todoList3",
".",
"insert",
"(",
"data",
".",
"data",
".",
"todoList",
")",
";",
"self",
".",
"todoList4",
".",
"insert",
"(",
"data",
".",
"data",
".",
"todoList",
")",
";",
"}"
] | callback when successful | [
"callback",
"when",
"successful"
] | 573a7caea7e41877710e69bac001771a6ea86d33 | https://github.com/AntonyThorpe/knockout-apollo/blob/573a7caea7e41877710e69bac001771a6ea86d33/demo/src/viewModel.js#L102-L108 | train |
|
ToMMApps/express-waf | database/mongo-db.js | MongoDB | function MongoDB(host, port, database, collection, username, password){
_self = this;
if(arguments.length < 3){
throw ("MongoDB constructor requires at least three arguments!");
}
if(collection){
_collection = collection;
} else{
_collection = DEFAULT_COLLECTION_NAME;
}
_username = username;
_password = password;
_host = host;
//create new database connection
_db = new Db(database, new Server(host, port), {safe:false}, {auto_reconnect: true});
} | javascript | function MongoDB(host, port, database, collection, username, password){
_self = this;
if(arguments.length < 3){
throw ("MongoDB constructor requires at least three arguments!");
}
if(collection){
_collection = collection;
} else{
_collection = DEFAULT_COLLECTION_NAME;
}
_username = username;
_password = password;
_host = host;
//create new database connection
_db = new Db(database, new Server(host, port), {safe:false}, {auto_reconnect: true});
} | [
"function",
"MongoDB",
"(",
"host",
",",
"port",
",",
"database",
",",
"collection",
",",
"username",
",",
"password",
")",
"{",
"_self",
"=",
"this",
";",
"if",
"(",
"arguments",
".",
"length",
"<",
"3",
")",
"{",
"throw",
"(",
"\"MongoDB constructor requires at least three arguments!\"",
")",
";",
"}",
"if",
"(",
"collection",
")",
"{",
"_collection",
"=",
"collection",
";",
"}",
"else",
"{",
"_collection",
"=",
"DEFAULT_COLLECTION_NAME",
";",
"}",
"_username",
"=",
"username",
";",
"_password",
"=",
"password",
";",
"_host",
"=",
"host",
";",
"_db",
"=",
"new",
"Db",
"(",
"database",
",",
"new",
"Server",
"(",
"host",
",",
"port",
")",
",",
"{",
"safe",
":",
"false",
"}",
",",
"{",
"auto_reconnect",
":",
"true",
"}",
")",
";",
"}"
] | Wrapper class for MongoDB for use with the Blocker modules.
Host and port specify on which computer MongoDB is running.
@param host Host of the database which shall be used for the Blocklist.
@param port Number of the port which shall be used for the Blocklist.
@param database Name of the database which shall be used for the Blocklist.
@param collection Name of the collection that shall be used for the Blocklist.
@param username optional parameter for username to connect to database.
@param password optional parameter for password to connect to database.
@attention This class is permanently holding a connection to the database. | [
"Wrapper",
"class",
"for",
"MongoDB",
"for",
"use",
"with",
"the",
"Blocker",
"modules",
".",
"Host",
"and",
"port",
"specify",
"on",
"which",
"computer",
"MongoDB",
"is",
"running",
"."
] | 5c2c3ec379722d3ee63b3bf8c5fe65d4a0c0bb6a | https://github.com/ToMMApps/express-waf/blob/5c2c3ec379722d3ee63b3bf8c5fe65d4a0c0bb6a/database/mongo-db.js#L28-L48 | train |
ToMMApps/express-waf | database/mongo-db.js | function(cb){
if(!_isOpen){
_self.open(function () {
_self.removeAll(function() {
getCollection(cb);
});
});
} else {
getCollection(cb);
}
function getCollection(cb) {
_db.collection(_collection, cb);
}
} | javascript | function(cb){
if(!_isOpen){
_self.open(function () {
_self.removeAll(function() {
getCollection(cb);
});
});
} else {
getCollection(cb);
}
function getCollection(cb) {
_db.collection(_collection, cb);
}
} | [
"function",
"(",
"cb",
")",
"{",
"if",
"(",
"!",
"_isOpen",
")",
"{",
"_self",
".",
"open",
"(",
"function",
"(",
")",
"{",
"_self",
".",
"removeAll",
"(",
"function",
"(",
")",
"{",
"getCollection",
"(",
"cb",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"getCollection",
"(",
"cb",
")",
";",
"}",
"function",
"getCollection",
"(",
"cb",
")",
"{",
"_db",
".",
"collection",
"(",
"_collection",
",",
"cb",
")",
";",
"}",
"}"
] | Gets the Blocklist collection from the MongoDB instance. | [
"Gets",
"the",
"Blocklist",
"collection",
"from",
"the",
"MongoDB",
"instance",
"."
] | 5c2c3ec379722d3ee63b3bf8c5fe65d4a0c0bb6a | https://github.com/ToMMApps/express-waf/blob/5c2c3ec379722d3ee63b3bf8c5fe65d4a0c0bb6a/database/mongo-db.js#L79-L94 | train |
|
chriszarate/supergenpass-lib | src/lib/generate.js | hashRound | function hashRound(input, length, hashFunction, rounds, callback) {
if (rounds > 0 || !validatePassword(input, length)) {
process.nextTick(() => {
hashRound(hashFunction(input), length, hashFunction, rounds - 1, callback);
});
return;
}
process.nextTick(() => {
callback(input.substring(0, length));
});
} | javascript | function hashRound(input, length, hashFunction, rounds, callback) {
if (rounds > 0 || !validatePassword(input, length)) {
process.nextTick(() => {
hashRound(hashFunction(input), length, hashFunction, rounds - 1, callback);
});
return;
}
process.nextTick(() => {
callback(input.substring(0, length));
});
} | [
"function",
"hashRound",
"(",
"input",
",",
"length",
",",
"hashFunction",
",",
"rounds",
",",
"callback",
")",
"{",
"if",
"(",
"rounds",
">",
"0",
"||",
"!",
"validatePassword",
"(",
"input",
",",
"length",
")",
")",
"{",
"process",
".",
"nextTick",
"(",
"(",
")",
"=>",
"{",
"hashRound",
"(",
"hashFunction",
"(",
"input",
")",
",",
"length",
",",
"hashFunction",
",",
"rounds",
"-",
"1",
",",
"callback",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"process",
".",
"nextTick",
"(",
"(",
")",
"=>",
"{",
"callback",
"(",
"input",
".",
"substring",
"(",
"0",
",",
"length",
")",
")",
";",
"}",
")",
";",
"}"
] | Hash the input for the requested number of rounds, then continue hashing until the password policy is satisfied. Finally, pass result to callback. | [
"Hash",
"the",
"input",
"for",
"the",
"requested",
"number",
"of",
"rounds",
"then",
"continue",
"hashing",
"until",
"the",
"password",
"policy",
"is",
"satisfied",
".",
"Finally",
"pass",
"result",
"to",
"callback",
"."
] | eb9ee92050813d498229bfe0e6ccbcb87124cf90 | https://github.com/chriszarate/supergenpass-lib/blob/eb9ee92050813d498229bfe0e6ccbcb87124cf90/src/lib/generate.js#L20-L30 | train |
compose-us/todastic | packages/server-web/src/client/socket.io-bundle.js | selectColor | function selectColor(namespace) {
var hash = 0,
i;
for (i in namespace) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
} | javascript | function selectColor(namespace) {
var hash = 0,
i;
for (i in namespace) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
} | [
"function",
"selectColor",
"(",
"namespace",
")",
"{",
"var",
"hash",
"=",
"0",
",",
"i",
";",
"for",
"(",
"i",
"in",
"namespace",
")",
"{",
"hash",
"=",
"(",
"hash",
"<<",
"5",
")",
"-",
"hash",
"+",
"namespace",
".",
"charCodeAt",
"(",
"i",
")",
";",
"hash",
"|=",
"0",
";",
"}",
"return",
"exports",
".",
"colors",
"[",
"Math",
".",
"abs",
"(",
"hash",
")",
"%",
"exports",
".",
"colors",
".",
"length",
"]",
";",
"}"
] | Select a color.
@param {String} namespace
@return {Number}
@api private | [
"Select",
"a",
"color",
"."
] | 4807d8e564905a2b49fe90d8046be9f1a19cf344 | https://github.com/compose-us/todastic/blob/4807d8e564905a2b49fe90d8046be9f1a19cf344/packages/server-web/src/client/socket.io-bundle.js#L260-L270 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.