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 |
---|---|---|---|---|---|---|---|---|---|---|---|
canjs/can-query-logic | can-query-logic.js | QueryLogic | function QueryLogic(Type, options){
Type = Type || {};
var passedHydrator = options && options.toQuery;
var passedSerializer = options && options.toParams;
var schema;
if(Type[schemaSymbol]) {
schema = Type[schemaSymbol]();
} else {
schema = Type;
}
// check that the basics are here
var id = schema.identity && schema.identity[0];
if(!id) {
//console.warn("can-query given a type without an identity schema. Using `id` as the identity id.");
schema.identity = ["id"];
}
var converter = makeBasicQueryConvert(schema),
hydrate,
serialize;
if(passedHydrator) {
hydrate = function(query){
return converter.hydrate(passedHydrator(query));
};
} else {
hydrate = converter.hydrate;
}
if(passedSerializer) {
serialize = function(query){
return passedSerializer(converter.serializer.serialize(query));
};
} else {
serialize = converter.serializer.serialize;
}
this.hydrate = hydrate;
this.serialize = serialize;
this.schema = schema;
} | javascript | function QueryLogic(Type, options){
Type = Type || {};
var passedHydrator = options && options.toQuery;
var passedSerializer = options && options.toParams;
var schema;
if(Type[schemaSymbol]) {
schema = Type[schemaSymbol]();
} else {
schema = Type;
}
// check that the basics are here
var id = schema.identity && schema.identity[0];
if(!id) {
//console.warn("can-query given a type without an identity schema. Using `id` as the identity id.");
schema.identity = ["id"];
}
var converter = makeBasicQueryConvert(schema),
hydrate,
serialize;
if(passedHydrator) {
hydrate = function(query){
return converter.hydrate(passedHydrator(query));
};
} else {
hydrate = converter.hydrate;
}
if(passedSerializer) {
serialize = function(query){
return passedSerializer(converter.serializer.serialize(query));
};
} else {
serialize = converter.serializer.serialize;
}
this.hydrate = hydrate;
this.serialize = serialize;
this.schema = schema;
} | [
"function",
"QueryLogic",
"(",
"Type",
",",
"options",
")",
"{",
"Type",
"=",
"Type",
"||",
"{",
"}",
";",
"var",
"passedHydrator",
"=",
"options",
"&&",
"options",
".",
"toQuery",
";",
"var",
"passedSerializer",
"=",
"options",
"&&",
"options",
".",
"toParams",
";",
"var",
"schema",
";",
"if",
"(",
"Type",
"[",
"schemaSymbol",
"]",
")",
"{",
"schema",
"=",
"Type",
"[",
"schemaSymbol",
"]",
"(",
")",
";",
"}",
"else",
"{",
"schema",
"=",
"Type",
";",
"}",
"var",
"id",
"=",
"schema",
".",
"identity",
"&&",
"schema",
".",
"identity",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"id",
")",
"{",
"schema",
".",
"identity",
"=",
"[",
"\"id\"",
"]",
";",
"}",
"var",
"converter",
"=",
"makeBasicQueryConvert",
"(",
"schema",
")",
",",
"hydrate",
",",
"serialize",
";",
"if",
"(",
"passedHydrator",
")",
"{",
"hydrate",
"=",
"function",
"(",
"query",
")",
"{",
"return",
"converter",
".",
"hydrate",
"(",
"passedHydrator",
"(",
"query",
")",
")",
";",
"}",
";",
"}",
"else",
"{",
"hydrate",
"=",
"converter",
".",
"hydrate",
";",
"}",
"if",
"(",
"passedSerializer",
")",
"{",
"serialize",
"=",
"function",
"(",
"query",
")",
"{",
"return",
"passedSerializer",
"(",
"converter",
".",
"serializer",
".",
"serialize",
"(",
"query",
")",
")",
";",
"}",
";",
"}",
"else",
"{",
"serialize",
"=",
"converter",
".",
"serializer",
".",
"serialize",
";",
"}",
"this",
".",
"hydrate",
"=",
"hydrate",
";",
"this",
".",
"serialize",
"=",
"serialize",
";",
"this",
".",
"schema",
"=",
"schema",
";",
"}"
] | Creates an algebra used to convert primitives to types and back | [
"Creates",
"an",
"algebra",
"used",
"to",
"convert",
"primitives",
"to",
"types",
"and",
"back"
] | fe32908e7aa36853362fbc1a4df276193247f38d | https://github.com/canjs/can-query-logic/blob/fe32908e7aa36853362fbc1a4df276193247f38d/can-query-logic.js#L13-L55 | train |
steve-gray/swagger-service-skeleton | src/index.js | generateApplicationCode | function generateApplicationCode(swagger, codegenOptions) {
debug('Generating application code.');
// Build up the execution parameters for the templates.
const templateFunc = codegenOptions.templateSet;
const outputDirectory = codegenOptions.temporaryDirectory;
const codegenSettings = defaults(
templateFunc(codegenOptions.templateSettings),
{
output: (name, content) => {
const fullName = path.join(outputDirectory, name);
const parsed = path.parse(fullName);
mkdirp.sync(parsed.dir);
fs.writeFileSync(fullName, content);
},
swagger: JSON.parse(JSON.stringify(swagger)), // Clone to avoid issues
});
// Perform the actual code generation
codegen(codegenSettings);
} | javascript | function generateApplicationCode(swagger, codegenOptions) {
debug('Generating application code.');
// Build up the execution parameters for the templates.
const templateFunc = codegenOptions.templateSet;
const outputDirectory = codegenOptions.temporaryDirectory;
const codegenSettings = defaults(
templateFunc(codegenOptions.templateSettings),
{
output: (name, content) => {
const fullName = path.join(outputDirectory, name);
const parsed = path.parse(fullName);
mkdirp.sync(parsed.dir);
fs.writeFileSync(fullName, content);
},
swagger: JSON.parse(JSON.stringify(swagger)), // Clone to avoid issues
});
// Perform the actual code generation
codegen(codegenSettings);
} | [
"function",
"generateApplicationCode",
"(",
"swagger",
",",
"codegenOptions",
")",
"{",
"debug",
"(",
"'Generating application code.'",
")",
";",
"const",
"templateFunc",
"=",
"codegenOptions",
".",
"templateSet",
";",
"const",
"outputDirectory",
"=",
"codegenOptions",
".",
"temporaryDirectory",
";",
"const",
"codegenSettings",
"=",
"defaults",
"(",
"templateFunc",
"(",
"codegenOptions",
".",
"templateSettings",
")",
",",
"{",
"output",
":",
"(",
"name",
",",
"content",
")",
"=>",
"{",
"const",
"fullName",
"=",
"path",
".",
"join",
"(",
"outputDirectory",
",",
"name",
")",
";",
"const",
"parsed",
"=",
"path",
".",
"parse",
"(",
"fullName",
")",
";",
"mkdirp",
".",
"sync",
"(",
"parsed",
".",
"dir",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"fullName",
",",
"content",
")",
";",
"}",
",",
"swagger",
":",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"swagger",
")",
")",
",",
"}",
")",
";",
"codegen",
"(",
"codegenSettings",
")",
";",
"}"
] | Generate the application code in the specified temporary directory. | [
"Generate",
"the",
"application",
"code",
"in",
"the",
"specified",
"temporary",
"directory",
"."
] | a3b81fc53f33af0cde195225907c247088e3ad40 | https://github.com/steve-gray/swagger-service-skeleton/blob/a3b81fc53f33af0cde195225907c247088e3ad40/src/index.js#L24-L44 | train |
steve-gray/swagger-service-skeleton | src/index.js | startSkeletonApplication | function startSkeletonApplication(options) {
debug('Starting to create application skeleton');
const configWithDefaults = defaults(
options, {
redirects: {
'documentation-from-root': {
match: /^\/$/,
target: '/docs',
},
},
ioc: {
},
customMiddleware: {
beforeSwagger: [],
afterSwagger: [],
beforeController: [],
},
codegen: {
controllerStubFolder: 'controllers',
temporaryDirectory: './.temp',
templateSet: templates,
},
service: {
listenPort: 10010,
},
cors: {
},
});
// If the swagger input is a string, then load it as a filename
const swaggerFile = configWithDefaults.service.swagger;
const swagger = typeof swaggerFile === 'string' ?
yamljs.load(swaggerFile) : swaggerFile;
// Create service instances
const app = connect();
const ioc = connectIoc(configWithDefaults.ioc);
// Generate custom application code
generateApplicationCode(
swagger,
configWithDefaults.codegen);
initializeSwagger(swagger, (middleware) => {
// Pre-request handling middleware
app.use(query()); // Query-string parsing
app.use(fiddleware.respondJson()); // res.json(data, status) support.
app.use(ioc.middleware); // Somersault IoC for controllers.
app.use(cors(configWithDefaults.cors)); // Cross-origin
app.use(cookieParser());
// Custom middleware
for (const item of configWithDefaults.customMiddleware.beforeSwagger) {
app.use(item);
}
// Swagger-tools middleware
app.use(middleware.swaggerMetadata());
app.use(middleware.swaggerValidator());
for (const item of configWithDefaults.customMiddleware.beforeController) {
app.use(item);
}
app.use(middleware.swaggerRouter({
controllers: path.join(
configWithDefaults.codegen.temporaryDirectory,
configWithDefaults.codegen.controllerStubFolder),
}));
app.use(middleware.swaggerUi());
// Post-request handling middleware
app.use(redirect(configWithDefaults.redirects)); // Redirect / to /docs
// Custom middleware
for (const item of configWithDefaults.customMiddleware.afterSwagger) {
app.use(item);
}
app.use(errorHandler()); // When there's an exception.
const server = app.listen(configWithDefaults.service.listenPort);
app.close = function closeServer() {
server.close();
};
});
return app;
} | javascript | function startSkeletonApplication(options) {
debug('Starting to create application skeleton');
const configWithDefaults = defaults(
options, {
redirects: {
'documentation-from-root': {
match: /^\/$/,
target: '/docs',
},
},
ioc: {
},
customMiddleware: {
beforeSwagger: [],
afterSwagger: [],
beforeController: [],
},
codegen: {
controllerStubFolder: 'controllers',
temporaryDirectory: './.temp',
templateSet: templates,
},
service: {
listenPort: 10010,
},
cors: {
},
});
// If the swagger input is a string, then load it as a filename
const swaggerFile = configWithDefaults.service.swagger;
const swagger = typeof swaggerFile === 'string' ?
yamljs.load(swaggerFile) : swaggerFile;
// Create service instances
const app = connect();
const ioc = connectIoc(configWithDefaults.ioc);
// Generate custom application code
generateApplicationCode(
swagger,
configWithDefaults.codegen);
initializeSwagger(swagger, (middleware) => {
// Pre-request handling middleware
app.use(query()); // Query-string parsing
app.use(fiddleware.respondJson()); // res.json(data, status) support.
app.use(ioc.middleware); // Somersault IoC for controllers.
app.use(cors(configWithDefaults.cors)); // Cross-origin
app.use(cookieParser());
// Custom middleware
for (const item of configWithDefaults.customMiddleware.beforeSwagger) {
app.use(item);
}
// Swagger-tools middleware
app.use(middleware.swaggerMetadata());
app.use(middleware.swaggerValidator());
for (const item of configWithDefaults.customMiddleware.beforeController) {
app.use(item);
}
app.use(middleware.swaggerRouter({
controllers: path.join(
configWithDefaults.codegen.temporaryDirectory,
configWithDefaults.codegen.controllerStubFolder),
}));
app.use(middleware.swaggerUi());
// Post-request handling middleware
app.use(redirect(configWithDefaults.redirects)); // Redirect / to /docs
// Custom middleware
for (const item of configWithDefaults.customMiddleware.afterSwagger) {
app.use(item);
}
app.use(errorHandler()); // When there's an exception.
const server = app.listen(configWithDefaults.service.listenPort);
app.close = function closeServer() {
server.close();
};
});
return app;
} | [
"function",
"startSkeletonApplication",
"(",
"options",
")",
"{",
"debug",
"(",
"'Starting to create application skeleton'",
")",
";",
"const",
"configWithDefaults",
"=",
"defaults",
"(",
"options",
",",
"{",
"redirects",
":",
"{",
"'documentation-from-root'",
":",
"{",
"match",
":",
"/",
"^\\/$",
"/",
",",
"target",
":",
"'/docs'",
",",
"}",
",",
"}",
",",
"ioc",
":",
"{",
"}",
",",
"customMiddleware",
":",
"{",
"beforeSwagger",
":",
"[",
"]",
",",
"afterSwagger",
":",
"[",
"]",
",",
"beforeController",
":",
"[",
"]",
",",
"}",
",",
"codegen",
":",
"{",
"controllerStubFolder",
":",
"'controllers'",
",",
"temporaryDirectory",
":",
"'./.temp'",
",",
"templateSet",
":",
"templates",
",",
"}",
",",
"service",
":",
"{",
"listenPort",
":",
"10010",
",",
"}",
",",
"cors",
":",
"{",
"}",
",",
"}",
")",
";",
"const",
"swaggerFile",
"=",
"configWithDefaults",
".",
"service",
".",
"swagger",
";",
"const",
"swagger",
"=",
"typeof",
"swaggerFile",
"===",
"'string'",
"?",
"yamljs",
".",
"load",
"(",
"swaggerFile",
")",
":",
"swaggerFile",
";",
"const",
"app",
"=",
"connect",
"(",
")",
";",
"const",
"ioc",
"=",
"connectIoc",
"(",
"configWithDefaults",
".",
"ioc",
")",
";",
"generateApplicationCode",
"(",
"swagger",
",",
"configWithDefaults",
".",
"codegen",
")",
";",
"initializeSwagger",
"(",
"swagger",
",",
"(",
"middleware",
")",
"=>",
"{",
"app",
".",
"use",
"(",
"query",
"(",
")",
")",
";",
"app",
".",
"use",
"(",
"fiddleware",
".",
"respondJson",
"(",
")",
")",
";",
"app",
".",
"use",
"(",
"ioc",
".",
"middleware",
")",
";",
"app",
".",
"use",
"(",
"cors",
"(",
"configWithDefaults",
".",
"cors",
")",
")",
";",
"app",
".",
"use",
"(",
"cookieParser",
"(",
")",
")",
";",
"for",
"(",
"const",
"item",
"of",
"configWithDefaults",
".",
"customMiddleware",
".",
"beforeSwagger",
")",
"{",
"app",
".",
"use",
"(",
"item",
")",
";",
"}",
"app",
".",
"use",
"(",
"middleware",
".",
"swaggerMetadata",
"(",
")",
")",
";",
"app",
".",
"use",
"(",
"middleware",
".",
"swaggerValidator",
"(",
")",
")",
";",
"for",
"(",
"const",
"item",
"of",
"configWithDefaults",
".",
"customMiddleware",
".",
"beforeController",
")",
"{",
"app",
".",
"use",
"(",
"item",
")",
";",
"}",
"app",
".",
"use",
"(",
"middleware",
".",
"swaggerRouter",
"(",
"{",
"controllers",
":",
"path",
".",
"join",
"(",
"configWithDefaults",
".",
"codegen",
".",
"temporaryDirectory",
",",
"configWithDefaults",
".",
"codegen",
".",
"controllerStubFolder",
")",
",",
"}",
")",
")",
";",
"app",
".",
"use",
"(",
"middleware",
".",
"swaggerUi",
"(",
")",
")",
";",
"app",
".",
"use",
"(",
"redirect",
"(",
"configWithDefaults",
".",
"redirects",
")",
")",
";",
"for",
"(",
"const",
"item",
"of",
"configWithDefaults",
".",
"customMiddleware",
".",
"afterSwagger",
")",
"{",
"app",
".",
"use",
"(",
"item",
")",
";",
"}",
"app",
".",
"use",
"(",
"errorHandler",
"(",
")",
")",
";",
"const",
"server",
"=",
"app",
".",
"listen",
"(",
"configWithDefaults",
".",
"service",
".",
"listenPort",
")",
";",
"app",
".",
"close",
"=",
"function",
"closeServer",
"(",
")",
"{",
"server",
".",
"close",
"(",
")",
";",
"}",
";",
"}",
")",
";",
"return",
"app",
";",
"}"
] | Initialize the application skeleton | [
"Initialize",
"the",
"application",
"skeleton"
] | a3b81fc53f33af0cde195225907c247088e3ad40 | https://github.com/steve-gray/swagger-service-skeleton/blob/a3b81fc53f33af0cde195225907c247088e3ad40/src/index.js#L49-L136 | train |
relution-io/relution-sdk | server/backend/routes/routes.js | getRoutes | function getRoutes(req, res) {
var index = {
name: about.name,
version: about.version,
description: about.description,
routes: app.routes
};
return res.json(index);
} | javascript | function getRoutes(req, res) {
var index = {
name: about.name,
version: about.version,
description: about.description,
routes: app.routes
};
return res.json(index);
} | [
"function",
"getRoutes",
"(",
"req",
",",
"res",
")",
"{",
"var",
"index",
"=",
"{",
"name",
":",
"about",
".",
"name",
",",
"version",
":",
"about",
".",
"version",
",",
"description",
":",
"about",
".",
"description",
",",
"routes",
":",
"app",
".",
"routes",
"}",
";",
"return",
"res",
".",
"json",
"(",
"index",
")",
";",
"}"
] | provides an overview of available API, state, etc.
@param req unused.
@param res body is an informal JSON that can be used for health monitoring, for example.
@return {*} unspecified value. | [
"provides",
"an",
"overview",
"of",
"available",
"API",
"state",
"etc",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/server/backend/routes/routes.js#L15-L23 | train |
canjs/can-query-logic | src/schema-helpers.js | function(Type){
return Type && canReflect.isConstructorLike(Type) &&
!set.hasComparisons(Type) &&
!Type[canSymbol.for("can.SetType")] &&
Type.prototype.valueOf && Type.prototype.valueOf !== Object.prototype.valueOf;
} | javascript | function(Type){
return Type && canReflect.isConstructorLike(Type) &&
!set.hasComparisons(Type) &&
!Type[canSymbol.for("can.SetType")] &&
Type.prototype.valueOf && Type.prototype.valueOf !== Object.prototype.valueOf;
} | [
"function",
"(",
"Type",
")",
"{",
"return",
"Type",
"&&",
"canReflect",
".",
"isConstructorLike",
"(",
"Type",
")",
"&&",
"!",
"set",
".",
"hasComparisons",
"(",
"Type",
")",
"&&",
"!",
"Type",
"[",
"canSymbol",
".",
"for",
"(",
"\"can.SetType\"",
")",
"]",
"&&",
"Type",
".",
"prototype",
".",
"valueOf",
"&&",
"Type",
".",
"prototype",
".",
"valueOf",
"!==",
"Object",
".",
"prototype",
".",
"valueOf",
";",
"}"
] | Number is a ranged type | [
"Number",
"is",
"a",
"ranged",
"type"
] | fe32908e7aa36853362fbc1a4df276193247f38d | https://github.com/canjs/can-query-logic/blob/fe32908e7aa36853362fbc1a4df276193247f38d/src/schema-helpers.js#L8-L13 | train |
|
relution-io/relution-sdk | lib/livedata/Collection.js | isCollection | function isCollection(object) {
if (!object || typeof object !== 'object') {
return false;
}
else if ('isCollection' in object) {
diag.debug.assert(function () { return object.isCollection === Collection.prototype.isPrototypeOf(object); });
return object.isCollection;
}
else {
return Collection.prototype.isPrototypeOf(object);
}
} | javascript | function isCollection(object) {
if (!object || typeof object !== 'object') {
return false;
}
else if ('isCollection' in object) {
diag.debug.assert(function () { return object.isCollection === Collection.prototype.isPrototypeOf(object); });
return object.isCollection;
}
else {
return Collection.prototype.isPrototypeOf(object);
}
} | [
"function",
"isCollection",
"(",
"object",
")",
"{",
"if",
"(",
"!",
"object",
"||",
"typeof",
"object",
"!==",
"'object'",
")",
"{",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"'isCollection'",
"in",
"object",
")",
"{",
"diag",
".",
"debug",
".",
"assert",
"(",
"function",
"(",
")",
"{",
"return",
"object",
".",
"isCollection",
"===",
"Collection",
".",
"prototype",
".",
"isPrototypeOf",
"(",
"object",
")",
";",
"}",
")",
";",
"return",
"object",
".",
"isCollection",
";",
"}",
"else",
"{",
"return",
"Collection",
".",
"prototype",
".",
"isPrototypeOf",
"(",
"object",
")",
";",
"}",
"}"
] | tests whether a given object is a Collection.
@param {object} object to check.
@return {boolean} whether object is a Collection. | [
"tests",
"whether",
"a",
"given",
"object",
"is",
"a",
"Collection",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/lib/livedata/Collection.js#L43-L54 | train |
relution-io/relution-sdk | lib/query/SortOrderComparator.js | jsonCompare | function jsonCompare(arg, options) {
var sortOrder;
if (typeof arg === 'string') {
sortOrder = new SortOrder_1.SortOrder();
sortOrder.fromJSON([arg]);
}
else if (_.isArray(arg)) {
sortOrder = new SortOrder_1.SortOrder();
sortOrder.fromJSON(arg);
}
else {
sortOrder = arg;
}
var comparator = new SortOrderComparator(sortOrder, options);
return (_.bind(comparator.compare, comparator));
} | javascript | function jsonCompare(arg, options) {
var sortOrder;
if (typeof arg === 'string') {
sortOrder = new SortOrder_1.SortOrder();
sortOrder.fromJSON([arg]);
}
else if (_.isArray(arg)) {
sortOrder = new SortOrder_1.SortOrder();
sortOrder.fromJSON(arg);
}
else {
sortOrder = arg;
}
var comparator = new SortOrderComparator(sortOrder, options);
return (_.bind(comparator.compare, comparator));
} | [
"function",
"jsonCompare",
"(",
"arg",
",",
"options",
")",
"{",
"var",
"sortOrder",
";",
"if",
"(",
"typeof",
"arg",
"===",
"'string'",
")",
"{",
"sortOrder",
"=",
"new",
"SortOrder_1",
".",
"SortOrder",
"(",
")",
";",
"sortOrder",
".",
"fromJSON",
"(",
"[",
"arg",
"]",
")",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isArray",
"(",
"arg",
")",
")",
"{",
"sortOrder",
"=",
"new",
"SortOrder_1",
".",
"SortOrder",
"(",
")",
";",
"sortOrder",
".",
"fromJSON",
"(",
"arg",
")",
";",
"}",
"else",
"{",
"sortOrder",
"=",
"arg",
";",
"}",
"var",
"comparator",
"=",
"new",
"SortOrderComparator",
"(",
"sortOrder",
",",
"options",
")",
";",
"return",
"(",
"_",
".",
"bind",
"(",
"comparator",
".",
"compare",
",",
"comparator",
")",
")",
";",
"}"
] | compiles a JsonCompareFn from a given SortOrder.
@param arg defining the SortOrder being compiled.
@return {function} a JsonCompareFn function compatible to Array.sort(). | [
"compiles",
"a",
"JsonCompareFn",
"from",
"a",
"given",
"SortOrder",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/lib/query/SortOrderComparator.js#L34-L49 | train |
relution-io/relution-sdk | lib/query/SortOrderComparator.js | SortOrderComparator | function SortOrderComparator(sortOrder, options) {
this.sortOrder = sortOrder;
this.options = {
casesensitive: false
};
if (options) {
_.extend(this.options, options);
}
this.expressions = new Array(sortOrder.sortFields.length);
for (var i = 0; i < this.expressions.length; ++i) {
this.expressions[i] = new JsonPath_1.JsonPath(sortOrder.sortFields[i].name);
}
} | javascript | function SortOrderComparator(sortOrder, options) {
this.sortOrder = sortOrder;
this.options = {
casesensitive: false
};
if (options) {
_.extend(this.options, options);
}
this.expressions = new Array(sortOrder.sortFields.length);
for (var i = 0; i < this.expressions.length; ++i) {
this.expressions[i] = new JsonPath_1.JsonPath(sortOrder.sortFields[i].name);
}
} | [
"function",
"SortOrderComparator",
"(",
"sortOrder",
",",
"options",
")",
"{",
"this",
".",
"sortOrder",
"=",
"sortOrder",
";",
"this",
".",
"options",
"=",
"{",
"casesensitive",
":",
"false",
"}",
";",
"if",
"(",
"options",
")",
"{",
"_",
".",
"extend",
"(",
"this",
".",
"options",
",",
"options",
")",
";",
"}",
"this",
".",
"expressions",
"=",
"new",
"Array",
"(",
"sortOrder",
".",
"sortFields",
".",
"length",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"expressions",
".",
"length",
";",
"++",
"i",
")",
"{",
"this",
".",
"expressions",
"[",
"i",
"]",
"=",
"new",
"JsonPath_1",
".",
"JsonPath",
"(",
"sortOrder",
".",
"sortFields",
"[",
"i",
"]",
".",
"name",
")",
";",
"}",
"}"
] | constructs a compiled SortOrder for object comparison.
@param sortOrder to realize. | [
"constructs",
"a",
"compiled",
"SortOrder",
"for",
"object",
"comparison",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/lib/query/SortOrderComparator.js#L62-L74 | train |
wingbotai/wingbot | src/graphApi/apiAuthorizer.js | apiAuthorizer | function apiAuthorizer (args, ctx, acl) {
const { token = {}, groups } = ctx;
const { groups: tokenGroups = [] } = token;
if (typeof acl === 'function') {
return acl(args, ctx);
}
let check = groups;
if (Array.isArray(acl)) {
check = [...groups, ...acl];
}
return tokenGroups.some(g => check.includes(g.group));
} | javascript | function apiAuthorizer (args, ctx, acl) {
const { token = {}, groups } = ctx;
const { groups: tokenGroups = [] } = token;
if (typeof acl === 'function') {
return acl(args, ctx);
}
let check = groups;
if (Array.isArray(acl)) {
check = [...groups, ...acl];
}
return tokenGroups.some(g => check.includes(g.group));
} | [
"function",
"apiAuthorizer",
"(",
"args",
",",
"ctx",
",",
"acl",
")",
"{",
"const",
"{",
"token",
"=",
"{",
"}",
",",
"groups",
"}",
"=",
"ctx",
";",
"const",
"{",
"groups",
":",
"tokenGroups",
"=",
"[",
"]",
"}",
"=",
"token",
";",
"if",
"(",
"typeof",
"acl",
"===",
"'function'",
")",
"{",
"return",
"acl",
"(",
"args",
",",
"ctx",
")",
";",
"}",
"let",
"check",
"=",
"groups",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"acl",
")",
")",
"{",
"check",
"=",
"[",
"...",
"groups",
",",
"...",
"acl",
"]",
";",
"}",
"return",
"tokenGroups",
".",
"some",
"(",
"g",
"=>",
"check",
".",
"includes",
"(",
"g",
".",
"group",
")",
")",
";",
"}"
] | If API call is authorized - use for own implementations of API endpoints
@param {Object} args - gql request
@param {{groups:string[],token:Object}} ctx - request context
@param {string[]|null|Function} acl - custom acl settings
@returns {boolean}
@example
const { apiAuthorizer } = require('wingbot');
function createApi (acl = null) {
return {
gqlEndpoint (args, ctx) {
if (!apiAuthorizer(args, ctx, acl)) {
return null;
}
}
}
} | [
"If",
"API",
"call",
"is",
"authorized",
"-",
"use",
"for",
"own",
"implementations",
"of",
"API",
"endpoints"
] | 2a917d6a5798e6f3e2258ef445b600eddfd1961b | https://github.com/wingbotai/wingbot/blob/2a917d6a5798e6f3e2258ef445b600eddfd1961b/src/graphApi/apiAuthorizer.js#L26-L40 | train |
JS-DevTools/globify | lib/index.js | globify | function globify (args) {
let parsed = new ParsedArgs(args);
let expandGlob = parsed.args[parsed.globIndex];
let renameOutfile = parsed.args[parsed.outfileIndex];
let files = expandGlob && expandGlob(parsed.globOptions);
if (!expandGlob) {
// No glob patterns were found, so just run browserify as-is
if (renameOutfile) {
parsed.args[parsed.outfileIndex] = renameOutfile();
}
browserify(parsed.cmd, parsed.args);
}
else if (!renameOutfile) {
// Run browserify with the expanded list of file names
Array.prototype.splice.apply(parsed.args, [parsed.globIndex, 1].concat(files));
browserify(parsed.cmd, parsed.args);
}
else {
// Run browserify separately for each file
files.forEach((file) => {
let fileArgs = parsed.args.slice();
fileArgs[parsed.globIndex] = file;
fileArgs[parsed.outfileIndex] = renameOutfile(file, parsed.baseDir);
browserify(parsed.cmd, fileArgs);
});
}
} | javascript | function globify (args) {
let parsed = new ParsedArgs(args);
let expandGlob = parsed.args[parsed.globIndex];
let renameOutfile = parsed.args[parsed.outfileIndex];
let files = expandGlob && expandGlob(parsed.globOptions);
if (!expandGlob) {
// No glob patterns were found, so just run browserify as-is
if (renameOutfile) {
parsed.args[parsed.outfileIndex] = renameOutfile();
}
browserify(parsed.cmd, parsed.args);
}
else if (!renameOutfile) {
// Run browserify with the expanded list of file names
Array.prototype.splice.apply(parsed.args, [parsed.globIndex, 1].concat(files));
browserify(parsed.cmd, parsed.args);
}
else {
// Run browserify separately for each file
files.forEach((file) => {
let fileArgs = parsed.args.slice();
fileArgs[parsed.globIndex] = file;
fileArgs[parsed.outfileIndex] = renameOutfile(file, parsed.baseDir);
browserify(parsed.cmd, fileArgs);
});
}
} | [
"function",
"globify",
"(",
"args",
")",
"{",
"let",
"parsed",
"=",
"new",
"ParsedArgs",
"(",
"args",
")",
";",
"let",
"expandGlob",
"=",
"parsed",
".",
"args",
"[",
"parsed",
".",
"globIndex",
"]",
";",
"let",
"renameOutfile",
"=",
"parsed",
".",
"args",
"[",
"parsed",
".",
"outfileIndex",
"]",
";",
"let",
"files",
"=",
"expandGlob",
"&&",
"expandGlob",
"(",
"parsed",
".",
"globOptions",
")",
";",
"if",
"(",
"!",
"expandGlob",
")",
"{",
"if",
"(",
"renameOutfile",
")",
"{",
"parsed",
".",
"args",
"[",
"parsed",
".",
"outfileIndex",
"]",
"=",
"renameOutfile",
"(",
")",
";",
"}",
"browserify",
"(",
"parsed",
".",
"cmd",
",",
"parsed",
".",
"args",
")",
";",
"}",
"else",
"if",
"(",
"!",
"renameOutfile",
")",
"{",
"Array",
".",
"prototype",
".",
"splice",
".",
"apply",
"(",
"parsed",
".",
"args",
",",
"[",
"parsed",
".",
"globIndex",
",",
"1",
"]",
".",
"concat",
"(",
"files",
")",
")",
";",
"browserify",
"(",
"parsed",
".",
"cmd",
",",
"parsed",
".",
"args",
")",
";",
"}",
"else",
"{",
"files",
".",
"forEach",
"(",
"(",
"file",
")",
"=>",
"{",
"let",
"fileArgs",
"=",
"parsed",
".",
"args",
".",
"slice",
"(",
")",
";",
"fileArgs",
"[",
"parsed",
".",
"globIndex",
"]",
"=",
"file",
";",
"fileArgs",
"[",
"parsed",
".",
"outfileIndex",
"]",
"=",
"renameOutfile",
"(",
"file",
",",
"parsed",
".",
"baseDir",
")",
";",
"browserify",
"(",
"parsed",
".",
"cmd",
",",
"fileArgs",
")",
";",
"}",
")",
";",
"}",
"}"
] | Runs browserify or watchify with the given arguments for each file that matches the glob pattern.
@param {string[]} args - the command-line arguments | [
"Runs",
"browserify",
"or",
"watchify",
"with",
"the",
"given",
"arguments",
"for",
"each",
"file",
"that",
"matches",
"the",
"glob",
"pattern",
"."
] | 650a0a8727982427c5d1d66e1094b0e23a15a8b6 | https://github.com/JS-DevTools/globify/blob/650a0a8727982427c5d1d66e1094b0e23a15a8b6/lib/index.js#L13-L40 | train |
JoystreamClassic/joystream-node | lib/utils.js | areTermsMatching | function areTermsMatching (buyerTerms, sellerTerms) {
if (buyerTerms.maxPrice >= sellerTerms.minPrice &&
buyerTerms.maxLock >= sellerTerms.minLock &&
buyerTerms.minNumberOfSellers <= sellerTerms.maxNumberOfSellers &&
buyerTerms.maxContractFeePerKb >= sellerTerms.minContractFeePerKb
) {
return true
} else {
return false
}
} | javascript | function areTermsMatching (buyerTerms, sellerTerms) {
if (buyerTerms.maxPrice >= sellerTerms.minPrice &&
buyerTerms.maxLock >= sellerTerms.minLock &&
buyerTerms.minNumberOfSellers <= sellerTerms.maxNumberOfSellers &&
buyerTerms.maxContractFeePerKb >= sellerTerms.minContractFeePerKb
) {
return true
} else {
return false
}
} | [
"function",
"areTermsMatching",
"(",
"buyerTerms",
",",
"sellerTerms",
")",
"{",
"if",
"(",
"buyerTerms",
".",
"maxPrice",
">=",
"sellerTerms",
".",
"minPrice",
"&&",
"buyerTerms",
".",
"maxLock",
">=",
"sellerTerms",
".",
"minLock",
"&&",
"buyerTerms",
".",
"minNumberOfSellers",
"<=",
"sellerTerms",
".",
"maxNumberOfSellers",
"&&",
"buyerTerms",
".",
"maxContractFeePerKb",
">=",
"sellerTerms",
".",
"minContractFeePerKb",
")",
"{",
"return",
"true",
"}",
"else",
"{",
"return",
"false",
"}",
"}"
] | Test if the seller and buyer terms are a match.
@param {object} The buyer terms
@param {object} The seller terms
@return {bool} True if it is a match or false if it isn't | [
"Test",
"if",
"the",
"seller",
"and",
"buyer",
"terms",
"are",
"a",
"match",
"."
] | 2450382bb937abdd959b460791c25f2d8f127168 | https://github.com/JoystreamClassic/joystream-node/blob/2450382bb937abdd959b460791c25f2d8f127168/lib/utils.js#L8-L19 | train |
relution-io/relution-sdk | lib/push/cordova.js | onPushNotificationError | function onPushNotificationError(error) {
Q(pushCallback(error)).done(undefined, function (e) {
diag.debug.assert(e === error, 'push callback failed: ' + e.message);
});
} | javascript | function onPushNotificationError(error) {
Q(pushCallback(error)).done(undefined, function (e) {
diag.debug.assert(e === error, 'push callback failed: ' + e.message);
});
} | [
"function",
"onPushNotificationError",
"(",
"error",
")",
"{",
"Q",
"(",
"pushCallback",
"(",
"error",
")",
")",
".",
"done",
"(",
"undefined",
",",
"function",
"(",
"e",
")",
"{",
"diag",
".",
"debug",
".",
"assert",
"(",
"e",
"===",
"error",
",",
"'push callback failed: '",
"+",
"e",
".",
"message",
")",
";",
"}",
")",
";",
"}"
] | executed when the pushNotification plugin fails internally. | [
"executed",
"when",
"the",
"pushNotification",
"plugin",
"fails",
"internally",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/lib/push/cordova.js#L34-L38 | train |
relution-io/relution-sdk | lib/push/cordova.js | onPushNotificationRegistration | function onPushNotificationRegistration(response) {
if (resolveRegistrationEventResponse) {
diag.debug.assert(!!rejectRegistrationEventResponse);
resolveRegistrationEventResponse(response);
resolveRegistrationEventResponse = undefined;
rejectRegistrationEventResponse = undefined;
}
else {
promiseRegistrationEventResponse = Q.resolve(response);
}
return promiseRegistrationEventResponse.done();
} | javascript | function onPushNotificationRegistration(response) {
if (resolveRegistrationEventResponse) {
diag.debug.assert(!!rejectRegistrationEventResponse);
resolveRegistrationEventResponse(response);
resolveRegistrationEventResponse = undefined;
rejectRegistrationEventResponse = undefined;
}
else {
promiseRegistrationEventResponse = Q.resolve(response);
}
return promiseRegistrationEventResponse.done();
} | [
"function",
"onPushNotificationRegistration",
"(",
"response",
")",
"{",
"if",
"(",
"resolveRegistrationEventResponse",
")",
"{",
"diag",
".",
"debug",
".",
"assert",
"(",
"!",
"!",
"rejectRegistrationEventResponse",
")",
";",
"resolveRegistrationEventResponse",
"(",
"response",
")",
";",
"resolveRegistrationEventResponse",
"=",
"undefined",
";",
"rejectRegistrationEventResponse",
"=",
"undefined",
";",
"}",
"else",
"{",
"promiseRegistrationEventResponse",
"=",
"Q",
".",
"resolve",
"(",
"response",
")",
";",
"}",
"return",
"promiseRegistrationEventResponse",
".",
"done",
"(",
")",
";",
"}"
] | executed when registration at 3rd party push server succeeded and a registration was issued, or a registration is renewed meaning this may be called several times. | [
"executed",
"when",
"registration",
"at",
"3rd",
"party",
"push",
"server",
"succeeded",
"and",
"a",
"registration",
"was",
"issued",
"or",
"a",
"registration",
"is",
"renewed",
"meaning",
"this",
"may",
"be",
"called",
"several",
"times",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/lib/push/cordova.js#L45-L56 | train |
relution-io/relution-sdk | lib/push/cordova.js | onPushNotificationNotification | function onPushNotificationNotification(response) {
// assignments avoiding changes of implementation state during promise chain
var plugin = pushPlugin;
var callback = pushCallback;
return Q(response).then(function (r) {
diag.debug.assert(r === response, 'just begins promise chain avoiding explicit try-catch');
return callback(undefined, response) || response;
}).then(function (r) {
diag.debug.assert(r === response, 'push callback must respond same object');
return Q.Promise(function (resolve, reject) {
try {
if ('notId' in response.additionalData) {
plugin.finish(resolve, reject, response.additionalData.notId);
}
else {
plugin.finish(resolve, reject);
}
}
catch (error) {
reject(error);
}
});
}).done(undefined, function (error) {
return Q(callback(error, response) || response).catch(function (e) {
diag.debug.assert(e === error, 'push callback failed: ' + e.message);
return response;
});
});
} | javascript | function onPushNotificationNotification(response) {
// assignments avoiding changes of implementation state during promise chain
var plugin = pushPlugin;
var callback = pushCallback;
return Q(response).then(function (r) {
diag.debug.assert(r === response, 'just begins promise chain avoiding explicit try-catch');
return callback(undefined, response) || response;
}).then(function (r) {
diag.debug.assert(r === response, 'push callback must respond same object');
return Q.Promise(function (resolve, reject) {
try {
if ('notId' in response.additionalData) {
plugin.finish(resolve, reject, response.additionalData.notId);
}
else {
plugin.finish(resolve, reject);
}
}
catch (error) {
reject(error);
}
});
}).done(undefined, function (error) {
return Q(callback(error, response) || response).catch(function (e) {
diag.debug.assert(e === error, 'push callback failed: ' + e.message);
return response;
});
});
} | [
"function",
"onPushNotificationNotification",
"(",
"response",
")",
"{",
"var",
"plugin",
"=",
"pushPlugin",
";",
"var",
"callback",
"=",
"pushCallback",
";",
"return",
"Q",
"(",
"response",
")",
".",
"then",
"(",
"function",
"(",
"r",
")",
"{",
"diag",
".",
"debug",
".",
"assert",
"(",
"r",
"===",
"response",
",",
"'just begins promise chain avoiding explicit try-catch'",
")",
";",
"return",
"callback",
"(",
"undefined",
",",
"response",
")",
"||",
"response",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"r",
")",
"{",
"diag",
".",
"debug",
".",
"assert",
"(",
"r",
"===",
"response",
",",
"'push callback must respond same object'",
")",
";",
"return",
"Q",
".",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"try",
"{",
"if",
"(",
"'notId'",
"in",
"response",
".",
"additionalData",
")",
"{",
"plugin",
".",
"finish",
"(",
"resolve",
",",
"reject",
",",
"response",
".",
"additionalData",
".",
"notId",
")",
";",
"}",
"else",
"{",
"plugin",
".",
"finish",
"(",
"resolve",
",",
"reject",
")",
";",
"}",
"}",
"catch",
"(",
"error",
")",
"{",
"reject",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"}",
")",
".",
"done",
"(",
"undefined",
",",
"function",
"(",
"error",
")",
"{",
"return",
"Q",
"(",
"callback",
"(",
"error",
",",
"response",
")",
"||",
"response",
")",
".",
"catch",
"(",
"function",
"(",
"e",
")",
"{",
"diag",
".",
"debug",
".",
"assert",
"(",
"e",
"===",
"error",
",",
"'push callback failed: '",
"+",
"e",
".",
"message",
")",
";",
"return",
"response",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | executed on each incoming push notification message calling the pushCallback in an error-agnostic fashion. | [
"executed",
"on",
"each",
"incoming",
"push",
"notification",
"message",
"calling",
"the",
"pushCallback",
"in",
"an",
"error",
"-",
"agnostic",
"fashion",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/lib/push/cordova.js#L59-L87 | train |
relution-io/relution-sdk | lib/push/cordova.js | defaultPushCallback | function defaultPushCallback(error, pushMessage) {
if (error) {
diag.debug.error('push failure', error);
}
else if (pushMessage && pushMessage.message) {
diag.debug.info('push received', pushMessage.message);
}
return pushMessage;
} | javascript | function defaultPushCallback(error, pushMessage) {
if (error) {
diag.debug.error('push failure', error);
}
else if (pushMessage && pushMessage.message) {
diag.debug.info('push received', pushMessage.message);
}
return pushMessage;
} | [
"function",
"defaultPushCallback",
"(",
"error",
",",
"pushMessage",
")",
"{",
"if",
"(",
"error",
")",
"{",
"diag",
".",
"debug",
".",
"error",
"(",
"'push failure'",
",",
"error",
")",
";",
"}",
"else",
"if",
"(",
"pushMessage",
"&&",
"pushMessage",
".",
"message",
")",
"{",
"diag",
".",
"debug",
".",
"info",
"(",
"'push received'",
",",
"pushMessage",
".",
"message",
")",
";",
"}",
"return",
"pushMessage",
";",
"}"
] | default implementation of PushCallback reporting errors and incoming messages to the console.
@param error cause of failure.
@param pushMessage incoming notification data.
@return {PushMessage} same value as parameter causing confirmation of message. | [
"default",
"implementation",
"of",
"PushCallback",
"reporting",
"errors",
"and",
"incoming",
"messages",
"to",
"the",
"console",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/lib/push/cordova.js#L96-L104 | train |
relution-io/relution-sdk | lib/push/cordova.js | listenPushNotification | function listenPushNotification(callback) {
if (callback === void 0) { callback = defaultPushCallback; }
if (resolveRegistrationEventResponse) {
diag.debug.assert(!!rejectRegistrationEventResponse);
resolveRegistrationEventResponse(undefined);
resolveRegistrationEventResponse = undefined;
rejectRegistrationEventResponse = undefined;
}
if (callback) {
// perform registration
promiseRegistrationEventResponse = device.ready.then(function (info) {
var pushInitOptions = init.initOptions.push;
var pushPlatform = info.platform.id;
if (pushPlatform === 'windowsphone') {
pushPlatform = 'windows';
}
if (!pushInitOptions || !pushPlatform || !(pushPlatform in pushInitOptions)) {
// no push configuration for current platform
promiseRegistrationEventResponse = Q.resolve(undefined);
return promiseRegistrationEventResponse;
}
// init or reinit push
var pushStatic = global['PushNotification'];
var pushImpl = pushStatic.init(pushInitOptions);
if (pushPlugin !== pushImpl) {
if (pushPlugin) {
// turn off existing event handlers (in reverse order of registration)
pushPlugin.off('notification', onPushNotificationNotification);
pushPlugin.off('registration', onPushNotificationRegistration);
pushPlugin.off('error', onPushNotificationError);
}
// set up new registration results
promiseRegistrationEventResponse = Q.Promise(function (resolve, reject) {
resolveRegistrationEventResponse = resolve;
rejectRegistrationEventResponse = reject;
});
// activation of new implementation
pushCallback = callback;
pushPlugin = pushImpl;
// turn on event handlers (in order of relevance)
pushPlugin.on('error', onPushNotificationError);
pushPlugin.on('registration', onPushNotificationRegistration);
pushPlugin.on('notification', onPushNotificationNotification);
}
return promiseRegistrationEventResponse;
});
}
else if (pushPlugin) {
// perform unregistration
promiseRegistrationEventResponse = Q.Promise(function (resolve, reject) {
try {
pushPlugin.unregister(resolve, reject);
}
catch (error) {
reject(error);
}
});
}
else {
// nothing to unregister
promiseRegistrationEventResponse = Q.resolve(undefined);
}
return promiseRegistrationEventResponse;
} | javascript | function listenPushNotification(callback) {
if (callback === void 0) { callback = defaultPushCallback; }
if (resolveRegistrationEventResponse) {
diag.debug.assert(!!rejectRegistrationEventResponse);
resolveRegistrationEventResponse(undefined);
resolveRegistrationEventResponse = undefined;
rejectRegistrationEventResponse = undefined;
}
if (callback) {
// perform registration
promiseRegistrationEventResponse = device.ready.then(function (info) {
var pushInitOptions = init.initOptions.push;
var pushPlatform = info.platform.id;
if (pushPlatform === 'windowsphone') {
pushPlatform = 'windows';
}
if (!pushInitOptions || !pushPlatform || !(pushPlatform in pushInitOptions)) {
// no push configuration for current platform
promiseRegistrationEventResponse = Q.resolve(undefined);
return promiseRegistrationEventResponse;
}
// init or reinit push
var pushStatic = global['PushNotification'];
var pushImpl = pushStatic.init(pushInitOptions);
if (pushPlugin !== pushImpl) {
if (pushPlugin) {
// turn off existing event handlers (in reverse order of registration)
pushPlugin.off('notification', onPushNotificationNotification);
pushPlugin.off('registration', onPushNotificationRegistration);
pushPlugin.off('error', onPushNotificationError);
}
// set up new registration results
promiseRegistrationEventResponse = Q.Promise(function (resolve, reject) {
resolveRegistrationEventResponse = resolve;
rejectRegistrationEventResponse = reject;
});
// activation of new implementation
pushCallback = callback;
pushPlugin = pushImpl;
// turn on event handlers (in order of relevance)
pushPlugin.on('error', onPushNotificationError);
pushPlugin.on('registration', onPushNotificationRegistration);
pushPlugin.on('notification', onPushNotificationNotification);
}
return promiseRegistrationEventResponse;
});
}
else if (pushPlugin) {
// perform unregistration
promiseRegistrationEventResponse = Q.Promise(function (resolve, reject) {
try {
pushPlugin.unregister(resolve, reject);
}
catch (error) {
reject(error);
}
});
}
else {
// nothing to unregister
promiseRegistrationEventResponse = Q.resolve(undefined);
}
return promiseRegistrationEventResponse;
} | [
"function",
"listenPushNotification",
"(",
"callback",
")",
"{",
"if",
"(",
"callback",
"===",
"void",
"0",
")",
"{",
"callback",
"=",
"defaultPushCallback",
";",
"}",
"if",
"(",
"resolveRegistrationEventResponse",
")",
"{",
"diag",
".",
"debug",
".",
"assert",
"(",
"!",
"!",
"rejectRegistrationEventResponse",
")",
";",
"resolveRegistrationEventResponse",
"(",
"undefined",
")",
";",
"resolveRegistrationEventResponse",
"=",
"undefined",
";",
"rejectRegistrationEventResponse",
"=",
"undefined",
";",
"}",
"if",
"(",
"callback",
")",
"{",
"promiseRegistrationEventResponse",
"=",
"device",
".",
"ready",
".",
"then",
"(",
"function",
"(",
"info",
")",
"{",
"var",
"pushInitOptions",
"=",
"init",
".",
"initOptions",
".",
"push",
";",
"var",
"pushPlatform",
"=",
"info",
".",
"platform",
".",
"id",
";",
"if",
"(",
"pushPlatform",
"===",
"'windowsphone'",
")",
"{",
"pushPlatform",
"=",
"'windows'",
";",
"}",
"if",
"(",
"!",
"pushInitOptions",
"||",
"!",
"pushPlatform",
"||",
"!",
"(",
"pushPlatform",
"in",
"pushInitOptions",
")",
")",
"{",
"promiseRegistrationEventResponse",
"=",
"Q",
".",
"resolve",
"(",
"undefined",
")",
";",
"return",
"promiseRegistrationEventResponse",
";",
"}",
"var",
"pushStatic",
"=",
"global",
"[",
"'PushNotification'",
"]",
";",
"var",
"pushImpl",
"=",
"pushStatic",
".",
"init",
"(",
"pushInitOptions",
")",
";",
"if",
"(",
"pushPlugin",
"!==",
"pushImpl",
")",
"{",
"if",
"(",
"pushPlugin",
")",
"{",
"pushPlugin",
".",
"off",
"(",
"'notification'",
",",
"onPushNotificationNotification",
")",
";",
"pushPlugin",
".",
"off",
"(",
"'registration'",
",",
"onPushNotificationRegistration",
")",
";",
"pushPlugin",
".",
"off",
"(",
"'error'",
",",
"onPushNotificationError",
")",
";",
"}",
"promiseRegistrationEventResponse",
"=",
"Q",
".",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"resolveRegistrationEventResponse",
"=",
"resolve",
";",
"rejectRegistrationEventResponse",
"=",
"reject",
";",
"}",
")",
";",
"pushCallback",
"=",
"callback",
";",
"pushPlugin",
"=",
"pushImpl",
";",
"pushPlugin",
".",
"on",
"(",
"'error'",
",",
"onPushNotificationError",
")",
";",
"pushPlugin",
".",
"on",
"(",
"'registration'",
",",
"onPushNotificationRegistration",
")",
";",
"pushPlugin",
".",
"on",
"(",
"'notification'",
",",
"onPushNotificationNotification",
")",
";",
"}",
"return",
"promiseRegistrationEventResponse",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"pushPlugin",
")",
"{",
"promiseRegistrationEventResponse",
"=",
"Q",
".",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"try",
"{",
"pushPlugin",
".",
"unregister",
"(",
"resolve",
",",
"reject",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"reject",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"promiseRegistrationEventResponse",
"=",
"Q",
".",
"resolve",
"(",
"undefined",
")",
";",
"}",
"return",
"promiseRegistrationEventResponse",
";",
"}"
] | installs a callback for receiving push notification messages, and registers the device with the
3rd party push service provider.
Usually push configuration is provided to `init()` and a call to this method is chained passing
the sink callback. Application using an explicit login then call `configurePushDevice()` as part
of the `LogonCallback` while anonymous applications call the latter directly.
In general it is not wise to unregister from push messages. However, this functionality is
available by passing `null` as callback.
@param callback to install, or explicitly null to unregister.
@return promise of registration, for informal purposes. | [
"installs",
"a",
"callback",
"for",
"receiving",
"push",
"notification",
"messages",
"and",
"registers",
"the",
"device",
"with",
"the",
"3rd",
"party",
"push",
"service",
"provider",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/lib/push/cordova.js#L119-L182 | train |
relution-io/relution-sdk | lib/push/cordova.js | configurePushDevice | function configurePushDevice(options) {
return Q.when(promiseRegistrationEventResponse, function (registrationEventResponse) {
if (!registrationEventResponse) {
// either there is no configuration or since this method was called,
// registration was canceled
return Q.resolve(undefined);
}
// remaining implementation in push.ts as this is independent of Cordova...
return push.registerPushDevice(registrationEventResponse.registrationId, options);
});
} | javascript | function configurePushDevice(options) {
return Q.when(promiseRegistrationEventResponse, function (registrationEventResponse) {
if (!registrationEventResponse) {
// either there is no configuration or since this method was called,
// registration was canceled
return Q.resolve(undefined);
}
// remaining implementation in push.ts as this is independent of Cordova...
return push.registerPushDevice(registrationEventResponse.registrationId, options);
});
} | [
"function",
"configurePushDevice",
"(",
"options",
")",
"{",
"return",
"Q",
".",
"when",
"(",
"promiseRegistrationEventResponse",
",",
"function",
"(",
"registrationEventResponse",
")",
"{",
"if",
"(",
"!",
"registrationEventResponse",
")",
"{",
"return",
"Q",
".",
"resolve",
"(",
"undefined",
")",
";",
"}",
"return",
"push",
".",
"registerPushDevice",
"(",
"registrationEventResponse",
".",
"registrationId",
",",
"options",
")",
";",
"}",
")",
";",
"}"
] | authorizes current Relution server logged onto to send push notifications by transmitting the
registration token. | [
"authorizes",
"current",
"Relution",
"server",
"logged",
"onto",
"to",
"send",
"push",
"notifications",
"by",
"transmitting",
"the",
"registration",
"token",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/lib/push/cordova.js#L188-L198 | train |
messagebot/ah-elasticsearch-orm | lib/instance/edit.js | function (k, v) {
checkJobs.push(function (checkDone) {
api.elasticsearch.search(self.alias, [k], [v], 0, 2, null, 1, function (error, results) {
if (error) { return checkDone(error) }
if (results.length === 0) { return checkDone() }
if (results.length === 1 && results[0].guid === self.data.guid) { return checkDone() }
return checkDone(new Error('uniqueFields:' + k + ' uniqueness violated via #' + results[0].guid))
})
})
} | javascript | function (k, v) {
checkJobs.push(function (checkDone) {
api.elasticsearch.search(self.alias, [k], [v], 0, 2, null, 1, function (error, results) {
if (error) { return checkDone(error) }
if (results.length === 0) { return checkDone() }
if (results.length === 1 && results[0].guid === self.data.guid) { return checkDone() }
return checkDone(new Error('uniqueFields:' + k + ' uniqueness violated via #' + results[0].guid))
})
})
} | [
"function",
"(",
"k",
",",
"v",
")",
"{",
"checkJobs",
".",
"push",
"(",
"function",
"(",
"checkDone",
")",
"{",
"api",
".",
"elasticsearch",
".",
"search",
"(",
"self",
".",
"alias",
",",
"[",
"k",
"]",
",",
"[",
"v",
"]",
",",
"0",
",",
"2",
",",
"null",
",",
"1",
",",
"function",
"(",
"error",
",",
"results",
")",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"checkDone",
"(",
"error",
")",
"}",
"if",
"(",
"results",
".",
"length",
"===",
"0",
")",
"{",
"return",
"checkDone",
"(",
")",
"}",
"if",
"(",
"results",
".",
"length",
"===",
"1",
"&&",
"results",
"[",
"0",
"]",
".",
"guid",
"===",
"self",
".",
"data",
".",
"guid",
")",
"{",
"return",
"checkDone",
"(",
")",
"}",
"return",
"checkDone",
"(",
"new",
"Error",
"(",
"'uniqueFields:'",
"+",
"k",
"+",
"' uniqueness violated via #'",
"+",
"results",
"[",
"0",
"]",
".",
"guid",
")",
")",
"}",
")",
"}",
")",
"}"
] | We need to ensure that none of the params this new instance has match an existing instance. | [
"We",
"need",
"to",
"ensure",
"that",
"none",
"of",
"the",
"params",
"this",
"new",
"instance",
"has",
"match",
"an",
"existing",
"instance",
"."
] | c559d688b8354288d678dcb9a2af41cee73c8b1e | https://github.com/messagebot/ah-elasticsearch-orm/blob/c559d688b8354288d678dcb9a2af41cee73c8b1e/lib/instance/edit.js#L54-L63 | train |
|
saneki-discontinued/node-toxcore | lib/tox_old.js | function(opts) {
this._emitter = new events.EventEmitter();
this._libpath = opts.path;
this._tox = opts.tox;
this._library = this.createLibrary(this._libpath);
this._initCallbacks();
} | javascript | function(opts) {
this._emitter = new events.EventEmitter();
this._libpath = opts.path;
this._tox = opts.tox;
this._library = this.createLibrary(this._libpath);
this._initCallbacks();
} | [
"function",
"(",
"opts",
")",
"{",
"this",
".",
"_emitter",
"=",
"new",
"events",
".",
"EventEmitter",
"(",
")",
";",
"this",
".",
"_libpath",
"=",
"opts",
".",
"path",
";",
"this",
".",
"_tox",
"=",
"opts",
".",
"tox",
";",
"this",
".",
"_library",
"=",
"this",
".",
"createLibrary",
"(",
"this",
".",
"_libpath",
")",
";",
"this",
".",
"_initCallbacks",
"(",
")",
";",
"}"
] | Construct a new ToxOld for using old groupchat functions.
@class
@param {String} opts.path - Path to libtoxcore
@param {Tox} opts.tox - Parent Tox instance
@todo Accept either tox option, options array, or both? | [
"Construct",
"a",
"new",
"ToxOld",
"for",
"using",
"old",
"groupchat",
"functions",
"."
] | 45dfb339f4e8a58888fca175528dee13f075824a | https://github.com/saneki-discontinued/node-toxcore/blob/45dfb339f4e8a58888fca175528dee13f075824a/lib/tox_old.js#L86-L92 | train |
|
wingbotai/wingbot | src/middlewares/callback.js | setCallback | function setCallback (action, callbackContext = null, callbackText = null) {
const callbackAction = this.toAbsoluteAction(action);
this.setState({
[ACTION]: callbackAction,
[CONTEXT]: callbackContext || DEFAULT,
[TEXT]: callbackText
});
return this;
} | javascript | function setCallback (action, callbackContext = null, callbackText = null) {
const callbackAction = this.toAbsoluteAction(action);
this.setState({
[ACTION]: callbackAction,
[CONTEXT]: callbackContext || DEFAULT,
[TEXT]: callbackText
});
return this;
} | [
"function",
"setCallback",
"(",
"action",
",",
"callbackContext",
"=",
"null",
",",
"callbackText",
"=",
"null",
")",
"{",
"const",
"callbackAction",
"=",
"this",
".",
"toAbsoluteAction",
"(",
"action",
")",
";",
"this",
".",
"setState",
"(",
"{",
"[",
"ACTION",
"]",
":",
"callbackAction",
",",
"[",
"CONTEXT",
"]",
":",
"callbackContext",
"||",
"DEFAULT",
",",
"[",
"TEXT",
"]",
":",
"callbackText",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Sets action, where to go back, when user responds with text
@param {string} action - relative or absolute action (usualy current action)
@param {string|null} [callbackContext] - context of callback
@param {string|null} [callbackText] - custom text response
@returns {this}
@alias module:callbackMiddleware
@deprecated - use res.runBookmark()
@typicalname res
@example
bot.use('myAction', (req, res) => {
res.setCallback('myAction'); // return back
}); | [
"Sets",
"action",
"where",
"to",
"go",
"back",
"when",
"user",
"responds",
"with",
"text"
] | 2a917d6a5798e6f3e2258ef445b600eddfd1961b | https://github.com/wingbotai/wingbot/blob/2a917d6a5798e6f3e2258ef445b600eddfd1961b/src/middlewares/callback.js#L91-L101 | train |
wingbotai/wingbot | src/middlewares/callback.js | hasCallback | function hasCallback (callbackContext = null) {
if (!this.state[ACTION]
|| callbackContext === this.state[CONTEXT]
|| !this.isText()) {
return false;
}
return true;
} | javascript | function hasCallback (callbackContext = null) {
if (!this.state[ACTION]
|| callbackContext === this.state[CONTEXT]
|| !this.isText()) {
return false;
}
return true;
} | [
"function",
"hasCallback",
"(",
"callbackContext",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"this",
".",
"state",
"[",
"ACTION",
"]",
"||",
"callbackContext",
"===",
"this",
".",
"state",
"[",
"CONTEXT",
"]",
"||",
"!",
"this",
".",
"isText",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Returns true, when callback has been prevously set.
It's usefull, when you don't want to bouce back the methods.
@param {string} [callbackContext]
@returns {boolean}
@alias module:callbackMiddleware
@deprecated - use res.runBookmark()
@example
bot.use(['fooRoute', /^foo$/], (req, res) => {
// set callback, only when this request does not have one
if (!req.hasCallback()) {
res.setCallback('fooRoute');
}
}); | [
"Returns",
"true",
"when",
"callback",
"has",
"been",
"prevously",
"set",
".",
"It",
"s",
"usefull",
"when",
"you",
"don",
"t",
"want",
"to",
"bouce",
"back",
"the",
"methods",
"."
] | 2a917d6a5798e6f3e2258ef445b600eddfd1961b | https://github.com/wingbotai/wingbot/blob/2a917d6a5798e6f3e2258ef445b600eddfd1961b/src/middlewares/callback.js#L119-L127 | train |
aMarCruz/react-native-google-places-ui | examples/placesuidemo/rn-rename.js | renameFilesIOS | function renameFilesIOS (oldPackageName, newPackageName) {
const filesAndFolders = [
`ios/${oldPackageName}.xcodeproj/xcshareddata/xcschemes/<?>-tvOS.xcscheme`,
`ios/${oldPackageName}.xcodeproj/xcshareddata/xcschemes/<?>.xcscheme`,
'ios/<?>.xcodeproj',
`ios/${oldPackageName}/<?>.entitlements`,
'ios/<?>',
'ios/<?>-tvOS',
'ios/<?>-tvOSTests',
`ios/${oldPackageName}Tests/<?>Tests.m`,
'ios/<?>Tests',
'ios/<?>.xcworkspace',
]
for (let i = 0; i < filesAndFolders.length; i++) {
const element = filesAndFolders[i]
const srcFile = fullPath(element.replace('<?>', oldPackageName))
console.log(`From ${relative(srcFile)}`)
if (fs.existsSync(srcFile)) {
const destFile = fullPath(element.replace('<?>', newPackageName))
fs.renameSync(srcFile, destFile)
console.log(` to ${relative(destFile)}`)
} else {
console.log(`${srcFile} does not exists.`)
}
}
} | javascript | function renameFilesIOS (oldPackageName, newPackageName) {
const filesAndFolders = [
`ios/${oldPackageName}.xcodeproj/xcshareddata/xcschemes/<?>-tvOS.xcscheme`,
`ios/${oldPackageName}.xcodeproj/xcshareddata/xcschemes/<?>.xcscheme`,
'ios/<?>.xcodeproj',
`ios/${oldPackageName}/<?>.entitlements`,
'ios/<?>',
'ios/<?>-tvOS',
'ios/<?>-tvOSTests',
`ios/${oldPackageName}Tests/<?>Tests.m`,
'ios/<?>Tests',
'ios/<?>.xcworkspace',
]
for (let i = 0; i < filesAndFolders.length; i++) {
const element = filesAndFolders[i]
const srcFile = fullPath(element.replace('<?>', oldPackageName))
console.log(`From ${relative(srcFile)}`)
if (fs.existsSync(srcFile)) {
const destFile = fullPath(element.replace('<?>', newPackageName))
fs.renameSync(srcFile, destFile)
console.log(` to ${relative(destFile)}`)
} else {
console.log(`${srcFile} does not exists.`)
}
}
} | [
"function",
"renameFilesIOS",
"(",
"oldPackageName",
",",
"newPackageName",
")",
"{",
"const",
"filesAndFolders",
"=",
"[",
"`",
"${",
"oldPackageName",
"}",
"`",
",",
"`",
"${",
"oldPackageName",
"}",
"`",
",",
"'ios/<?>.xcodeproj'",
",",
"`",
"${",
"oldPackageName",
"}",
"`",
",",
"'ios/<?>'",
",",
"'ios/<?>-tvOS'",
",",
"'ios/<?>-tvOSTests'",
",",
"`",
"${",
"oldPackageName",
"}",
"`",
",",
"'ios/<?>Tests'",
",",
"'ios/<?>.xcworkspace'",
",",
"]",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"filesAndFolders",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"element",
"=",
"filesAndFolders",
"[",
"i",
"]",
"const",
"srcFile",
"=",
"fullPath",
"(",
"element",
".",
"replace",
"(",
"'<?>'",
",",
"oldPackageName",
")",
")",
"console",
".",
"log",
"(",
"`",
"${",
"relative",
"(",
"srcFile",
")",
"}",
"`",
")",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"srcFile",
")",
")",
"{",
"const",
"destFile",
"=",
"fullPath",
"(",
"element",
".",
"replace",
"(",
"'<?>'",
",",
"newPackageName",
")",
")",
"fs",
".",
"renameSync",
"(",
"srcFile",
",",
"destFile",
")",
"console",
".",
"log",
"(",
"`",
"${",
"relative",
"(",
"destFile",
")",
"}",
"`",
")",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"srcFile",
"}",
"`",
")",
"}",
"}",
"}"
] | Move files and folders | [
"Move",
"files",
"and",
"folders"
] | 8f1da69819e1cea681f4ffba653ef19de5a3607d | https://github.com/aMarCruz/react-native-google-places-ui/blob/8f1da69819e1cea681f4ffba653ef19de5a3607d/examples/placesuidemo/rn-rename.js#L103-L131 | train |
aMarCruz/react-native-google-places-ui | examples/placesuidemo/rn-rename.js | updatePackageID | function updatePackageID () {
return new Promise((resolve) => {
const oldPackageID = oldInfo.packageID
const newPackageID = newInfo.packageID
const androidPath = newInfo.androidPathToModule
console.log(`Changing package ID from "${oldPackageID}" to "${newPackageID}"...`)
replaceInFiles(RegExp(`(?=([ "'])).${oldPackageID}(?=[;"'])`), `$1${newPackageID}`, [
'android/app/BUCK',
'android/app/build.gradle',
'android/app/src/main/AndroidManifest.xml',
`${androidPath}/MainActivity.java`,
`${androidPath}/MainApplication.java`,
])
console.log('Package ID is updated.\n')
resolve()
})
} | javascript | function updatePackageID () {
return new Promise((resolve) => {
const oldPackageID = oldInfo.packageID
const newPackageID = newInfo.packageID
const androidPath = newInfo.androidPathToModule
console.log(`Changing package ID from "${oldPackageID}" to "${newPackageID}"...`)
replaceInFiles(RegExp(`(?=([ "'])).${oldPackageID}(?=[;"'])`), `$1${newPackageID}`, [
'android/app/BUCK',
'android/app/build.gradle',
'android/app/src/main/AndroidManifest.xml',
`${androidPath}/MainActivity.java`,
`${androidPath}/MainApplication.java`,
])
console.log('Package ID is updated.\n')
resolve()
})
} | [
"function",
"updatePackageID",
"(",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
")",
"=>",
"{",
"const",
"oldPackageID",
"=",
"oldInfo",
".",
"packageID",
"const",
"newPackageID",
"=",
"newInfo",
".",
"packageID",
"const",
"androidPath",
"=",
"newInfo",
".",
"androidPathToModule",
"console",
".",
"log",
"(",
"`",
"${",
"oldPackageID",
"}",
"${",
"newPackageID",
"}",
"`",
")",
"replaceInFiles",
"(",
"RegExp",
"(",
"`",
"${",
"oldPackageID",
"}",
"`",
")",
",",
"`",
"${",
"newPackageID",
"}",
"`",
",",
"[",
"'android/app/BUCK'",
",",
"'android/app/build.gradle'",
",",
"'android/app/src/main/AndroidManifest.xml'",
",",
"`",
"${",
"androidPath",
"}",
"`",
",",
"`",
"${",
"androidPath",
"}",
"`",
",",
"]",
")",
"console",
".",
"log",
"(",
"'Package ID is updated.\\n'",
")",
"\\n",
"}",
")",
"}"
] | Replaces "com.placesuidemo" | [
"Replaces",
"com",
".",
"placesuidemo"
] | 8f1da69819e1cea681f4ffba653ef19de5a3607d | https://github.com/aMarCruz/react-native-google-places-ui/blob/8f1da69819e1cea681f4ffba653ef19de5a3607d/examples/placesuidemo/rn-rename.js#L253-L271 | train |
saneki-discontinued/node-toxcore | lib/old/toxav.js | function(tox, opts) {
if(!opts) opts = {};
var libpath = opts['path'];
this._tox = tox;
this._toxav = this.createLibrary(libpath);
} | javascript | function(tox, opts) {
if(!opts) opts = {};
var libpath = opts['path'];
this._tox = tox;
this._toxav = this.createLibrary(libpath);
} | [
"function",
"(",
"tox",
",",
"opts",
")",
"{",
"if",
"(",
"!",
"opts",
")",
"opts",
"=",
"{",
"}",
";",
"var",
"libpath",
"=",
"opts",
"[",
"'path'",
"]",
";",
"this",
".",
"_tox",
"=",
"tox",
";",
"this",
".",
"_toxav",
"=",
"this",
".",
"createLibrary",
"(",
"libpath",
")",
";",
"}"
] | Construct a new ToxAV.
@class
@param {Tox} tox - Tox instance
@param {Object} [opts] - Options
@param {String} [opts.path] toxav library path, will use the
default if not specified | [
"Construct",
"a",
"new",
"ToxAV",
"."
] | 45dfb339f4e8a58888fca175528dee13f075824a | https://github.com/saneki-discontinued/node-toxcore/blob/45dfb339f4e8a58888fca175528dee13f075824a/lib/old/toxav.js#L44-L50 | train |
|
mwittig/etherport-client | index.js | OpenEventObserver | function OpenEventObserver(clientPort, serverPort) {
events.EventEmitter.call(this);
this.isClientPortOpen = false;
this.isServerPortOpen = false;
clientPort.on('open', this._clientPortOpenHandler(this));
serverPort.on('open', this._serverPortOpenHandler(this));
} | javascript | function OpenEventObserver(clientPort, serverPort) {
events.EventEmitter.call(this);
this.isClientPortOpen = false;
this.isServerPortOpen = false;
clientPort.on('open', this._clientPortOpenHandler(this));
serverPort.on('open', this._serverPortOpenHandler(this));
} | [
"function",
"OpenEventObserver",
"(",
"clientPort",
",",
"serverPort",
")",
"{",
"events",
".",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"isClientPortOpen",
"=",
"false",
";",
"this",
".",
"isServerPortOpen",
"=",
"false",
";",
"clientPort",
".",
"on",
"(",
"'open'",
",",
"this",
".",
"_clientPortOpenHandler",
"(",
"this",
")",
")",
";",
"serverPort",
".",
"on",
"(",
"'open'",
",",
"this",
".",
"_serverPortOpenHandler",
"(",
"this",
")",
")",
";",
"}"
] | Local Helper Object to wait for the open event on two Serial Port objects | [
"Local",
"Helper",
"Object",
"to",
"wait",
"for",
"the",
"open",
"event",
"on",
"two",
"Serial",
"Port",
"objects"
] | 939cd5f24c397bc424cb1ab39d3c9df578e19dd6 | https://github.com/mwittig/etherport-client/blob/939cd5f24c397bc424cb1ab39d3c9df578e19dd6/index.js#L149-L157 | train |
mwittig/etherport-client | index.js | chainSerialPorts | function chainSerialPorts(clientPort, serverPort) {
var observer = new OpenEventObserver(clientPort, serverPort);
function serverPortWrite(data) {
try {
debug('writing to serverPort', data);
if (! Buffer.isBuffer(data)) {
data = new Buffer(data);
}
serverPort.write(data);
}
catch (ex) {
debug('error reading message', ex);
}
}
function clientPortWrite(data) {
try {
debug('writing to clientPort', data);
if (! Buffer.isBuffer(data)) {
data = new Buffer(data);
}
clientPort.write(data);
}
catch (ex) {
debug('error reading message', ex);
}
}
observer.once('open', function (data) {
serverPort.on('data', function (data) {
clientPortWrite(data);
});
clientPort.on('data', function (data) {
serverPortWrite(data);
});
});
} | javascript | function chainSerialPorts(clientPort, serverPort) {
var observer = new OpenEventObserver(clientPort, serverPort);
function serverPortWrite(data) {
try {
debug('writing to serverPort', data);
if (! Buffer.isBuffer(data)) {
data = new Buffer(data);
}
serverPort.write(data);
}
catch (ex) {
debug('error reading message', ex);
}
}
function clientPortWrite(data) {
try {
debug('writing to clientPort', data);
if (! Buffer.isBuffer(data)) {
data = new Buffer(data);
}
clientPort.write(data);
}
catch (ex) {
debug('error reading message', ex);
}
}
observer.once('open', function (data) {
serverPort.on('data', function (data) {
clientPortWrite(data);
});
clientPort.on('data', function (data) {
serverPortWrite(data);
});
});
} | [
"function",
"chainSerialPorts",
"(",
"clientPort",
",",
"serverPort",
")",
"{",
"var",
"observer",
"=",
"new",
"OpenEventObserver",
"(",
"clientPort",
",",
"serverPort",
")",
";",
"function",
"serverPortWrite",
"(",
"data",
")",
"{",
"try",
"{",
"debug",
"(",
"'writing to serverPort'",
",",
"data",
")",
";",
"if",
"(",
"!",
"Buffer",
".",
"isBuffer",
"(",
"data",
")",
")",
"{",
"data",
"=",
"new",
"Buffer",
"(",
"data",
")",
";",
"}",
"serverPort",
".",
"write",
"(",
"data",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"debug",
"(",
"'error reading message'",
",",
"ex",
")",
";",
"}",
"}",
"function",
"clientPortWrite",
"(",
"data",
")",
"{",
"try",
"{",
"debug",
"(",
"'writing to clientPort'",
",",
"data",
")",
";",
"if",
"(",
"!",
"Buffer",
".",
"isBuffer",
"(",
"data",
")",
")",
"{",
"data",
"=",
"new",
"Buffer",
"(",
"data",
")",
";",
"}",
"clientPort",
".",
"write",
"(",
"data",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"debug",
"(",
"'error reading message'",
",",
"ex",
")",
";",
"}",
"}",
"observer",
".",
"once",
"(",
"'open'",
",",
"function",
"(",
"data",
")",
"{",
"serverPort",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"clientPortWrite",
"(",
"data",
")",
";",
"}",
")",
";",
"clientPort",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"serverPortWrite",
"(",
"data",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Helper function to chain Serial Port objects | [
"Helper",
"function",
"to",
"chain",
"Serial",
"Port",
"objects"
] | 939cd5f24c397bc424cb1ab39d3c9df578e19dd6 | https://github.com/mwittig/etherport-client/blob/939cd5f24c397bc424cb1ab39d3c9df578e19dd6/index.js#L182-L220 | train |
relution-io/relution-sdk | lib/web/http.js | logout | function logout(logoutOptions) {
if (logoutOptions === void 0) { logoutOptions = {}; }
var serverUrl = urls.resolveServer('/', logoutOptions);
var serverObj = server.Server.getInstance(serverUrl);
// process options
var currentOptions = serverObj.applyOptions({
serverUrl: serverUrl,
agentOptions: logoutOptions.agentOptions || init.initOptions.agentOptions,
agentClass: logoutOptions.agentClass || init.initOptions.agentClass,
});
return ajax(_.defaults({
serverUrl: serverUrl,
method: 'POST',
url: '/gofer/security/rest/auth/logout',
body: {}
}, currentOptions)).catch(function (error) {
if (error.statusCode === 422) {
// REST-based logout URL currently is broken reporting a 422 in all cases
return ajax(_.defaults({
serverUrl: serverUrl,
method: 'GET',
url: '/gofer/security-logout'
}, currentOptions)).then(function (result) {
diag.debug.warn('BUG: resorted to classic PATH-based logout as REST-based logout failed:', error);
return result;
}, function (error2) {
return Q.reject(error2.statusCode === 422 ? error : error2);
});
}
return Q.reject(error);
}).catch(function (error) {
// ignore network failures on timeout, server forgets on session timeout anyways
if (!error.statusCode) {
return Q.resolve(undefined);
}
return Q.reject(error);
}).finally(function () {
// eventually erase offline login data
if (logoutOptions.offlineCapable) {
// requested to erase login data
return offline.clearOfflineLogin(serverObj.credentials, currentOptions).catch(function (offlineError) {
diag.debug.warn('failed erasing offline login data', offlineError);
return Q.resolve(undefined);
});
}
}).finally(function () {
// forget everything about it
serverObj.credentials = null;
serverObj.authorization = auth.ANONYMOUS_AUTHORIZATION;
serverObj.organization = null;
serverObj.user = null;
serverObj.sessionUserUuid = null;
});
} | javascript | function logout(logoutOptions) {
if (logoutOptions === void 0) { logoutOptions = {}; }
var serverUrl = urls.resolveServer('/', logoutOptions);
var serverObj = server.Server.getInstance(serverUrl);
// process options
var currentOptions = serverObj.applyOptions({
serverUrl: serverUrl,
agentOptions: logoutOptions.agentOptions || init.initOptions.agentOptions,
agentClass: logoutOptions.agentClass || init.initOptions.agentClass,
});
return ajax(_.defaults({
serverUrl: serverUrl,
method: 'POST',
url: '/gofer/security/rest/auth/logout',
body: {}
}, currentOptions)).catch(function (error) {
if (error.statusCode === 422) {
// REST-based logout URL currently is broken reporting a 422 in all cases
return ajax(_.defaults({
serverUrl: serverUrl,
method: 'GET',
url: '/gofer/security-logout'
}, currentOptions)).then(function (result) {
diag.debug.warn('BUG: resorted to classic PATH-based logout as REST-based logout failed:', error);
return result;
}, function (error2) {
return Q.reject(error2.statusCode === 422 ? error : error2);
});
}
return Q.reject(error);
}).catch(function (error) {
// ignore network failures on timeout, server forgets on session timeout anyways
if (!error.statusCode) {
return Q.resolve(undefined);
}
return Q.reject(error);
}).finally(function () {
// eventually erase offline login data
if (logoutOptions.offlineCapable) {
// requested to erase login data
return offline.clearOfflineLogin(serverObj.credentials, currentOptions).catch(function (offlineError) {
diag.debug.warn('failed erasing offline login data', offlineError);
return Q.resolve(undefined);
});
}
}).finally(function () {
// forget everything about it
serverObj.credentials = null;
serverObj.authorization = auth.ANONYMOUS_AUTHORIZATION;
serverObj.organization = null;
serverObj.user = null;
serverObj.sessionUserUuid = null;
});
} | [
"function",
"logout",
"(",
"logoutOptions",
")",
"{",
"if",
"(",
"logoutOptions",
"===",
"void",
"0",
")",
"{",
"logoutOptions",
"=",
"{",
"}",
";",
"}",
"var",
"serverUrl",
"=",
"urls",
".",
"resolveServer",
"(",
"'/'",
",",
"logoutOptions",
")",
";",
"var",
"serverObj",
"=",
"server",
".",
"Server",
".",
"getInstance",
"(",
"serverUrl",
")",
";",
"var",
"currentOptions",
"=",
"serverObj",
".",
"applyOptions",
"(",
"{",
"serverUrl",
":",
"serverUrl",
",",
"agentOptions",
":",
"logoutOptions",
".",
"agentOptions",
"||",
"init",
".",
"initOptions",
".",
"agentOptions",
",",
"agentClass",
":",
"logoutOptions",
".",
"agentClass",
"||",
"init",
".",
"initOptions",
".",
"agentClass",
",",
"}",
")",
";",
"return",
"ajax",
"(",
"_",
".",
"defaults",
"(",
"{",
"serverUrl",
":",
"serverUrl",
",",
"method",
":",
"'POST'",
",",
"url",
":",
"'/gofer/security/rest/auth/logout'",
",",
"body",
":",
"{",
"}",
"}",
",",
"currentOptions",
")",
")",
".",
"catch",
"(",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
".",
"statusCode",
"===",
"422",
")",
"{",
"return",
"ajax",
"(",
"_",
".",
"defaults",
"(",
"{",
"serverUrl",
":",
"serverUrl",
",",
"method",
":",
"'GET'",
",",
"url",
":",
"'/gofer/security-logout'",
"}",
",",
"currentOptions",
")",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"diag",
".",
"debug",
".",
"warn",
"(",
"'BUG: resorted to classic PATH-based logout as REST-based logout failed:'",
",",
"error",
")",
";",
"return",
"result",
";",
"}",
",",
"function",
"(",
"error2",
")",
"{",
"return",
"Q",
".",
"reject",
"(",
"error2",
".",
"statusCode",
"===",
"422",
"?",
"error",
":",
"error2",
")",
";",
"}",
")",
";",
"}",
"return",
"Q",
".",
"reject",
"(",
"error",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"!",
"error",
".",
"statusCode",
")",
"{",
"return",
"Q",
".",
"resolve",
"(",
"undefined",
")",
";",
"}",
"return",
"Q",
".",
"reject",
"(",
"error",
")",
";",
"}",
")",
".",
"finally",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"logoutOptions",
".",
"offlineCapable",
")",
"{",
"return",
"offline",
".",
"clearOfflineLogin",
"(",
"serverObj",
".",
"credentials",
",",
"currentOptions",
")",
".",
"catch",
"(",
"function",
"(",
"offlineError",
")",
"{",
"diag",
".",
"debug",
".",
"warn",
"(",
"'failed erasing offline login data'",
",",
"offlineError",
")",
";",
"return",
"Q",
".",
"resolve",
"(",
"undefined",
")",
";",
"}",
")",
";",
"}",
"}",
")",
".",
"finally",
"(",
"function",
"(",
")",
"{",
"serverObj",
".",
"credentials",
"=",
"null",
";",
"serverObj",
".",
"authorization",
"=",
"auth",
".",
"ANONYMOUS_AUTHORIZATION",
";",
"serverObj",
".",
"organization",
"=",
"null",
";",
"serverObj",
".",
"user",
"=",
"null",
";",
"serverObj",
".",
"sessionUserUuid",
"=",
"null",
";",
"}",
")",
";",
"}"
] | logs out of a Relution server.
For explicit logouts (trigger by app user pressing a logout button, for example) specifying
`offlineCapable = true` will drop any persisted offline login data for the server logging out
of.
@param logoutOptions overwriting [[init]] defaults.
@return {Q.Promise<void>} of logout response.
@example
```javascript
Relution.web.logout()
.then((resp) => console.log('resp', resp);)
.catch((e:Error) => console.error(e.message, e))
.finally(() => console.log('bye bye'));
//Observable
Observable.fromPromise(Relution.web.logout()).subscribe(
(resp: any) => console.log('resp', resp),
(e:Error) => console.error(e.message, e);,
() => console.log('bye bye')
)
``` | [
"logs",
"out",
"of",
"a",
"Relution",
"server",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/lib/web/http.js#L491-L544 | train |
relution-io/relution-sdk | lib/push/push.js | registerPushDevice | function registerPushDevice(registrationId, options) {
if (options === void 0) { options = {}; }
var user = server.getCurrentAuthorization().name;
var pushInitOptions = init.initOptions.push;
return device.ready.then(function (info) {
var providerType;
switch (info.platform.id) {
case 'android':
providerType = 'GCM';
break;
case 'ios':
// when a senderID is configured,
// iOS device is registered at APNS which generates a token registered in turn at GCM,
// so that pushes are send using GCM to either type of device.
providerType = pushInitOptions.ios.senderID ? 'GCM' : 'APNS';
break;
case 'windowsphone':
providerType = 'WNS';
break;
case 'blackberry':
providerType = 'PAP';
break;
default:
providerType = 'MCAP';
break;
}
diag.debug.assert(!!info.device, 'The current implementation supports mobile devices only!');
return {
uuid: null,
providerType: providerType,
token: registrationId,
user: user,
deviceIdentifier: info.uuid,
vendor: info.device.manufacturer,
name: info.device.name,
osVersion: info.device.version,
model: info.device.model,
type: info.device.name,
appPackageName: info.device.appIdentifier,
appVersion: info.device.appVersionCode || info.device.appVersionName,
attributes: options.attributes,
tags: options.tags,
badge: options.badge
};
}).then(function (device) {
diag.debug.assert(device.providerType !== 'PAP', 'Relution Server does not yet support this!');
diag.debug.assert(device.providerType !== 'MCAP', 'Relution SDK does not yet implement this!');
return web.post(pushUrl + '/registration', device);
});
} | javascript | function registerPushDevice(registrationId, options) {
if (options === void 0) { options = {}; }
var user = server.getCurrentAuthorization().name;
var pushInitOptions = init.initOptions.push;
return device.ready.then(function (info) {
var providerType;
switch (info.platform.id) {
case 'android':
providerType = 'GCM';
break;
case 'ios':
// when a senderID is configured,
// iOS device is registered at APNS which generates a token registered in turn at GCM,
// so that pushes are send using GCM to either type of device.
providerType = pushInitOptions.ios.senderID ? 'GCM' : 'APNS';
break;
case 'windowsphone':
providerType = 'WNS';
break;
case 'blackberry':
providerType = 'PAP';
break;
default:
providerType = 'MCAP';
break;
}
diag.debug.assert(!!info.device, 'The current implementation supports mobile devices only!');
return {
uuid: null,
providerType: providerType,
token: registrationId,
user: user,
deviceIdentifier: info.uuid,
vendor: info.device.manufacturer,
name: info.device.name,
osVersion: info.device.version,
model: info.device.model,
type: info.device.name,
appPackageName: info.device.appIdentifier,
appVersion: info.device.appVersionCode || info.device.appVersionName,
attributes: options.attributes,
tags: options.tags,
badge: options.badge
};
}).then(function (device) {
diag.debug.assert(device.providerType !== 'PAP', 'Relution Server does not yet support this!');
diag.debug.assert(device.providerType !== 'MCAP', 'Relution SDK does not yet implement this!');
return web.post(pushUrl + '/registration', device);
});
} | [
"function",
"registerPushDevice",
"(",
"registrationId",
",",
"options",
")",
"{",
"if",
"(",
"options",
"===",
"void",
"0",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"var",
"user",
"=",
"server",
".",
"getCurrentAuthorization",
"(",
")",
".",
"name",
";",
"var",
"pushInitOptions",
"=",
"init",
".",
"initOptions",
".",
"push",
";",
"return",
"device",
".",
"ready",
".",
"then",
"(",
"function",
"(",
"info",
")",
"{",
"var",
"providerType",
";",
"switch",
"(",
"info",
".",
"platform",
".",
"id",
")",
"{",
"case",
"'android'",
":",
"providerType",
"=",
"'GCM'",
";",
"break",
";",
"case",
"'ios'",
":",
"providerType",
"=",
"pushInitOptions",
".",
"ios",
".",
"senderID",
"?",
"'GCM'",
":",
"'APNS'",
";",
"break",
";",
"case",
"'windowsphone'",
":",
"providerType",
"=",
"'WNS'",
";",
"break",
";",
"case",
"'blackberry'",
":",
"providerType",
"=",
"'PAP'",
";",
"break",
";",
"default",
":",
"providerType",
"=",
"'MCAP'",
";",
"break",
";",
"}",
"diag",
".",
"debug",
".",
"assert",
"(",
"!",
"!",
"info",
".",
"device",
",",
"'The current implementation supports mobile devices only!'",
")",
";",
"return",
"{",
"uuid",
":",
"null",
",",
"providerType",
":",
"providerType",
",",
"token",
":",
"registrationId",
",",
"user",
":",
"user",
",",
"deviceIdentifier",
":",
"info",
".",
"uuid",
",",
"vendor",
":",
"info",
".",
"device",
".",
"manufacturer",
",",
"name",
":",
"info",
".",
"device",
".",
"name",
",",
"osVersion",
":",
"info",
".",
"device",
".",
"version",
",",
"model",
":",
"info",
".",
"device",
".",
"model",
",",
"type",
":",
"info",
".",
"device",
".",
"name",
",",
"appPackageName",
":",
"info",
".",
"device",
".",
"appIdentifier",
",",
"appVersion",
":",
"info",
".",
"device",
".",
"appVersionCode",
"||",
"info",
".",
"device",
".",
"appVersionName",
",",
"attributes",
":",
"options",
".",
"attributes",
",",
"tags",
":",
"options",
".",
"tags",
",",
"badge",
":",
"options",
".",
"badge",
"}",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"device",
")",
"{",
"diag",
".",
"debug",
".",
"assert",
"(",
"device",
".",
"providerType",
"!==",
"'PAP'",
",",
"'Relution Server does not yet support this!'",
")",
";",
"diag",
".",
"debug",
".",
"assert",
"(",
"device",
".",
"providerType",
"!==",
"'MCAP'",
",",
"'Relution SDK does not yet implement this!'",
")",
";",
"return",
"web",
".",
"post",
"(",
"pushUrl",
"+",
"'/registration'",
",",
"device",
")",
";",
"}",
")",
";",
"}"
] | registers a target device with the current Relution server.
The implementation relies on backend code generated by CLI. That code attempts fetching an
existing device using the metadata information send as request body data. If it finds one, that
device is updated. Otherwise a new device is created and stored in the database. The updated
device registration record then is sent as response body data.
@param registrationId to register.
@return promise of registered device.
@internal SDK client code must call configurePushDevice() which obtains the token. | [
"registers",
"a",
"target",
"device",
"with",
"the",
"current",
"Relution",
"server",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/lib/push/push.js#L52-L101 | train |
relution-io/relution-sdk | lib/push/push.js | pushDeviceFilterByUsers | function pushDeviceFilterByUsers() {
var users = [];
for (var _i = 0; _i < arguments.length; _i++) {
users[_i - 0] = arguments[_i];
}
if (users.length <= 0) {
return {
type: 'null',
fieldName: 'user',
isNull: true
};
}
else if (users.length === 1) {
return {
type: 'string',
fieldName: 'user',
value: domain.uuidOf(users[0])
};
}
else {
var uuids = users.map(function (user) { return domain.uuidOf(user); });
return {
type: 'stringEnum',
fieldName: 'user',
values: uuids
};
}
} | javascript | function pushDeviceFilterByUsers() {
var users = [];
for (var _i = 0; _i < arguments.length; _i++) {
users[_i - 0] = arguments[_i];
}
if (users.length <= 0) {
return {
type: 'null',
fieldName: 'user',
isNull: true
};
}
else if (users.length === 1) {
return {
type: 'string',
fieldName: 'user',
value: domain.uuidOf(users[0])
};
}
else {
var uuids = users.map(function (user) { return domain.uuidOf(user); });
return {
type: 'stringEnum',
fieldName: 'user',
values: uuids
};
}
} | [
"function",
"pushDeviceFilterByUsers",
"(",
")",
"{",
"var",
"users",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"_i",
"=",
"0",
";",
"_i",
"<",
"arguments",
".",
"length",
";",
"_i",
"++",
")",
"{",
"users",
"[",
"_i",
"-",
"0",
"]",
"=",
"arguments",
"[",
"_i",
"]",
";",
"}",
"if",
"(",
"users",
".",
"length",
"<=",
"0",
")",
"{",
"return",
"{",
"type",
":",
"'null'",
",",
"fieldName",
":",
"'user'",
",",
"isNull",
":",
"true",
"}",
";",
"}",
"else",
"if",
"(",
"users",
".",
"length",
"===",
"1",
")",
"{",
"return",
"{",
"type",
":",
"'string'",
",",
"fieldName",
":",
"'user'",
",",
"value",
":",
"domain",
".",
"uuidOf",
"(",
"users",
"[",
"0",
"]",
")",
"}",
";",
"}",
"else",
"{",
"var",
"uuids",
"=",
"users",
".",
"map",
"(",
"function",
"(",
"user",
")",
"{",
"return",
"domain",
".",
"uuidOf",
"(",
"user",
")",
";",
"}",
")",
";",
"return",
"{",
"type",
":",
"'stringEnum'",
",",
"fieldName",
":",
"'user'",
",",
"values",
":",
"uuids",
"}",
";",
"}",
"}"
] | creates a device filter for the user attribute of push devices matching any of a given set of
users.
@param users* to filter on.
@returns device filter matching devices of given users. | [
"creates",
"a",
"device",
"filter",
"for",
"the",
"user",
"attribute",
"of",
"push",
"devices",
"matching",
"any",
"of",
"a",
"given",
"set",
"of",
"users",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/lib/push/push.js#L129-L156 | train |
saneki-discontinued/node-toxcore | lib/tox.js | function(opts) {
if(!opts) opts = {};
var libpath = opts['path'];
this._emitter = new events.EventEmitter();
this._library = this.createLibrary(libpath);
this._initCrypto(opts);
this._options = this._createToxOptions(opts);
this._initNew(this._options);
this._initCallbacks();
// Create a child ToxOld if specified for old groupchat functionality
if(opts.old === true) {
this._toxold = new ToxOld({ path: libpath, tox: this });
}
} | javascript | function(opts) {
if(!opts) opts = {};
var libpath = opts['path'];
this._emitter = new events.EventEmitter();
this._library = this.createLibrary(libpath);
this._initCrypto(opts);
this._options = this._createToxOptions(opts);
this._initNew(this._options);
this._initCallbacks();
// Create a child ToxOld if specified for old groupchat functionality
if(opts.old === true) {
this._toxold = new ToxOld({ path: libpath, tox: this });
}
} | [
"function",
"(",
"opts",
")",
"{",
"if",
"(",
"!",
"opts",
")",
"opts",
"=",
"{",
"}",
";",
"var",
"libpath",
"=",
"opts",
"[",
"'path'",
"]",
";",
"this",
".",
"_emitter",
"=",
"new",
"events",
".",
"EventEmitter",
"(",
")",
";",
"this",
".",
"_library",
"=",
"this",
".",
"createLibrary",
"(",
"libpath",
")",
";",
"this",
".",
"_initCrypto",
"(",
"opts",
")",
";",
"this",
".",
"_options",
"=",
"this",
".",
"_createToxOptions",
"(",
"opts",
")",
";",
"this",
".",
"_initNew",
"(",
"this",
".",
"_options",
")",
";",
"this",
".",
"_initCallbacks",
"(",
")",
";",
"if",
"(",
"opts",
".",
"old",
"===",
"true",
")",
"{",
"this",
".",
"_toxold",
"=",
"new",
"ToxOld",
"(",
"{",
"path",
":",
"libpath",
",",
"tox",
":",
"this",
"}",
")",
";",
"}",
"}"
] | Creates a Tox instance.
@class
@param {Object} [opts] Options | [
"Creates",
"a",
"Tox",
"instance",
"."
] | 45dfb339f4e8a58888fca175528dee13f075824a | https://github.com/saneki-discontinued/node-toxcore/blob/45dfb339f4e8a58888fca175528dee13f075824a/lib/tox.js#L130-L145 | train |
|
wingbotai/wingbot | src/tools/bufferloader.js | bufferloader | function bufferloader (url, limit = 0, limitJustByBody = false, redirCount = 3) {
return new Promise((resolve, reject) => {
if (redirCount <= 0) {
reject(new Error('Too many redirects'));
}
let totalLength = 0;
let buf = Buffer.alloc(0);
const req = https.get(url, (res) => {
if (res.statusCode === 301 && res.headers && res.headers.location) {
// redirect
req.removeAllListeners();
resolve(bufferloader(res.headers.location, limit, limitJustByBody, redirCount - 1));
return;
}
if (res.statusCode !== 200) {
req.removeAllListeners();
reject(new Error(res.statusMessage || 'Cant load'));
return;
}
if (!limitJustByBody && limit > 0 && res.headers && res.headers['content-length']) {
const len = parseInt(res.headers['content-length'], 10);
if (!Number.isNaN(len) && len > limit) {
req.removeAllListeners();
reject(sizeLimitExceeded(limit, len));
return;
}
}
const cleanup = () => {
res.removeAllListeners();
req.removeAllListeners();
};
res.on('data', (data) => {
totalLength += data.length;
if (limit > 0 && totalLength > limit) {
cleanup();
res.destroy();
reject(sizeLimitExceeded(limit, totalLength));
return;
}
buf = Buffer.concat([
buf,
data
]);
});
res.on('end', () => {
cleanup();
resolve(buf);
});
});
req.on('error', (err) => {
req.removeAllListeners();
reject(err);
});
});
} | javascript | function bufferloader (url, limit = 0, limitJustByBody = false, redirCount = 3) {
return new Promise((resolve, reject) => {
if (redirCount <= 0) {
reject(new Error('Too many redirects'));
}
let totalLength = 0;
let buf = Buffer.alloc(0);
const req = https.get(url, (res) => {
if (res.statusCode === 301 && res.headers && res.headers.location) {
// redirect
req.removeAllListeners();
resolve(bufferloader(res.headers.location, limit, limitJustByBody, redirCount - 1));
return;
}
if (res.statusCode !== 200) {
req.removeAllListeners();
reject(new Error(res.statusMessage || 'Cant load'));
return;
}
if (!limitJustByBody && limit > 0 && res.headers && res.headers['content-length']) {
const len = parseInt(res.headers['content-length'], 10);
if (!Number.isNaN(len) && len > limit) {
req.removeAllListeners();
reject(sizeLimitExceeded(limit, len));
return;
}
}
const cleanup = () => {
res.removeAllListeners();
req.removeAllListeners();
};
res.on('data', (data) => {
totalLength += data.length;
if (limit > 0 && totalLength > limit) {
cleanup();
res.destroy();
reject(sizeLimitExceeded(limit, totalLength));
return;
}
buf = Buffer.concat([
buf,
data
]);
});
res.on('end', () => {
cleanup();
resolve(buf);
});
});
req.on('error', (err) => {
req.removeAllListeners();
reject(err);
});
});
} | [
"function",
"bufferloader",
"(",
"url",
",",
"limit",
"=",
"0",
",",
"limitJustByBody",
"=",
"false",
",",
"redirCount",
"=",
"3",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"if",
"(",
"redirCount",
"<=",
"0",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'Too many redirects'",
")",
")",
";",
"}",
"let",
"totalLength",
"=",
"0",
";",
"let",
"buf",
"=",
"Buffer",
".",
"alloc",
"(",
"0",
")",
";",
"const",
"req",
"=",
"https",
".",
"get",
"(",
"url",
",",
"(",
"res",
")",
"=>",
"{",
"if",
"(",
"res",
".",
"statusCode",
"===",
"301",
"&&",
"res",
".",
"headers",
"&&",
"res",
".",
"headers",
".",
"location",
")",
"{",
"req",
".",
"removeAllListeners",
"(",
")",
";",
"resolve",
"(",
"bufferloader",
"(",
"res",
".",
"headers",
".",
"location",
",",
"limit",
",",
"limitJustByBody",
",",
"redirCount",
"-",
"1",
")",
")",
";",
"return",
";",
"}",
"if",
"(",
"res",
".",
"statusCode",
"!==",
"200",
")",
"{",
"req",
".",
"removeAllListeners",
"(",
")",
";",
"reject",
"(",
"new",
"Error",
"(",
"res",
".",
"statusMessage",
"||",
"'Cant load'",
")",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"limitJustByBody",
"&&",
"limit",
">",
"0",
"&&",
"res",
".",
"headers",
"&&",
"res",
".",
"headers",
"[",
"'content-length'",
"]",
")",
"{",
"const",
"len",
"=",
"parseInt",
"(",
"res",
".",
"headers",
"[",
"'content-length'",
"]",
",",
"10",
")",
";",
"if",
"(",
"!",
"Number",
".",
"isNaN",
"(",
"len",
")",
"&&",
"len",
">",
"limit",
")",
"{",
"req",
".",
"removeAllListeners",
"(",
")",
";",
"reject",
"(",
"sizeLimitExceeded",
"(",
"limit",
",",
"len",
")",
")",
";",
"return",
";",
"}",
"}",
"const",
"cleanup",
"=",
"(",
")",
"=>",
"{",
"res",
".",
"removeAllListeners",
"(",
")",
";",
"req",
".",
"removeAllListeners",
"(",
")",
";",
"}",
";",
"res",
".",
"on",
"(",
"'data'",
",",
"(",
"data",
")",
"=>",
"{",
"totalLength",
"+=",
"data",
".",
"length",
";",
"if",
"(",
"limit",
">",
"0",
"&&",
"totalLength",
">",
"limit",
")",
"{",
"cleanup",
"(",
")",
";",
"res",
".",
"destroy",
"(",
")",
";",
"reject",
"(",
"sizeLimitExceeded",
"(",
"limit",
",",
"totalLength",
")",
")",
";",
"return",
";",
"}",
"buf",
"=",
"Buffer",
".",
"concat",
"(",
"[",
"buf",
",",
"data",
"]",
")",
";",
"}",
")",
";",
"res",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"{",
"cleanup",
"(",
")",
";",
"resolve",
"(",
"buf",
")",
";",
"}",
")",
";",
"}",
")",
";",
"req",
".",
"on",
"(",
"'error'",
",",
"(",
"err",
")",
"=>",
"{",
"req",
".",
"removeAllListeners",
"(",
")",
";",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Downloads a file from url into a buffer. Supports size limits and redirects.
@param {string} url
@param {number} [limit=0] - limit in bytes
@param {boolean} [limitJustByBody=false] - when true, content size in header is ignored
@param {number} [redirCount=3] - maximmum amount of redirects
@returns {Promise<Buffer>}
@example
router.use('*', (req, res, postBack) => {
if (req.isFile()) {
bufferloader(req.attachmentUrl())
.then(buffer => postBack('downloaded', { data: buffer }))
.catch(err => postBack('donwloaded', { err }))
}
}); | [
"Downloads",
"a",
"file",
"from",
"url",
"into",
"a",
"buffer",
".",
"Supports",
"size",
"limits",
"and",
"redirects",
"."
] | 2a917d6a5798e6f3e2258ef445b600eddfd1961b | https://github.com/wingbotai/wingbot/blob/2a917d6a5798e6f3e2258ef445b600eddfd1961b/src/tools/bufferloader.js#L33-L99 | train |
phase2/generator-gadget | generators/app/index.js | function () {
if (options['offline']) {
options.drupalDistroRelease = '0.0.0';
}
else {
// Find the latest stable release for the Drupal distro version.
var done = this.async();
options.drupalDistro.releaseVersion(options.drupalDistroVersion, done, function(err, version, done) {
if (err) {
this.env.error('Could not retrieve distribution project info: ' + err);
return done(err);
}
options.drupalDistroRelease = version;
done();
}.bind(this));
}
} | javascript | function () {
if (options['offline']) {
options.drupalDistroRelease = '0.0.0';
}
else {
// Find the latest stable release for the Drupal distro version.
var done = this.async();
options.drupalDistro.releaseVersion(options.drupalDistroVersion, done, function(err, version, done) {
if (err) {
this.env.error('Could not retrieve distribution project info: ' + err);
return done(err);
}
options.drupalDistroRelease = version;
done();
}.bind(this));
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"options",
"[",
"'offline'",
"]",
")",
"{",
"options",
".",
"drupalDistroRelease",
"=",
"'0.0.0'",
";",
"}",
"else",
"{",
"var",
"done",
"=",
"this",
".",
"async",
"(",
")",
";",
"options",
".",
"drupalDistro",
".",
"releaseVersion",
"(",
"options",
".",
"drupalDistroVersion",
",",
"done",
",",
"function",
"(",
"err",
",",
"version",
",",
"done",
")",
"{",
"if",
"(",
"err",
")",
"{",
"this",
".",
"env",
".",
"error",
"(",
"'Could not retrieve distribution project info: '",
"+",
"err",
")",
";",
"return",
"done",
"(",
"err",
")",
";",
"}",
"options",
".",
"drupalDistroRelease",
"=",
"version",
";",
"done",
"(",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
"}"
] | Determine the latest stable release for the requested Drupal core version. | [
"Determine",
"the",
"latest",
"stable",
"release",
"for",
"the",
"requested",
"Drupal",
"core",
"version",
"."
] | 8ebc9a6f7592ebc37844cd2aec346c2e00aaa91d | https://github.com/phase2/generator-gadget/blob/8ebc9a6f7592ebc37844cd2aec346c2e00aaa91d/generators/app/index.js#L59-L75 | train |
|
phase2/generator-gadget | generators/app/index.js | function () {
var srcFiles = path.resolve(
this.templatePath('drupal'),
options.drupalDistro.id,
options.drupalDistroVersion
);
if (gadget.fsExistsSync(srcFiles)) {
this.fs.copy(
path.resolve(srcFiles),
this.destinationRoot(),
{
globOptions: { dot: true }
}
);
}
this.composer = options.drupalDistro.loadComposer(this, options);
} | javascript | function () {
var srcFiles = path.resolve(
this.templatePath('drupal'),
options.drupalDistro.id,
options.drupalDistroVersion
);
if (gadget.fsExistsSync(srcFiles)) {
this.fs.copy(
path.resolve(srcFiles),
this.destinationRoot(),
{
globOptions: { dot: true }
}
);
}
this.composer = options.drupalDistro.loadComposer(this, options);
} | [
"function",
"(",
")",
"{",
"var",
"srcFiles",
"=",
"path",
".",
"resolve",
"(",
"this",
".",
"templatePath",
"(",
"'drupal'",
")",
",",
"options",
".",
"drupalDistro",
".",
"id",
",",
"options",
".",
"drupalDistroVersion",
")",
";",
"if",
"(",
"gadget",
".",
"fsExistsSync",
"(",
"srcFiles",
")",
")",
"{",
"this",
".",
"fs",
".",
"copy",
"(",
"path",
".",
"resolve",
"(",
"srcFiles",
")",
",",
"this",
".",
"destinationRoot",
"(",
")",
",",
"{",
"globOptions",
":",
"{",
"dot",
":",
"true",
"}",
"}",
")",
";",
"}",
"this",
".",
"composer",
"=",
"options",
".",
"drupalDistro",
".",
"loadComposer",
"(",
"this",
",",
"options",
")",
";",
"}"
] | This has been moved up from writing because the details of some of these files may need to be loaded as part of configuring other write operations, and the parallelization model for generator composition requires dependencies to be handled in an earlier priority context. | [
"This",
"has",
"been",
"moved",
"up",
"from",
"writing",
"because",
"the",
"details",
"of",
"some",
"of",
"these",
"files",
"may",
"need",
"to",
"be",
"loaded",
"as",
"part",
"of",
"configuring",
"other",
"write",
"operations",
"and",
"the",
"parallelization",
"model",
"for",
"generator",
"composition",
"requires",
"dependencies",
"to",
"be",
"handled",
"in",
"an",
"earlier",
"priority",
"context",
"."
] | 8ebc9a6f7592ebc37844cd2aec346c2e00aaa91d | https://github.com/phase2/generator-gadget/blob/8ebc9a6f7592ebc37844cd2aec346c2e00aaa91d/generators/app/index.js#L143-L161 | train |
|
phase2/generator-gadget | generators/app/index.js | function () {
var isNewProject = (this.composerOrig == undefined);
if (!isNewProject) {
// Use original composer file if project already generated.
this.composer = this.composerOrig;
}
this.composer.name = 'organization/' + options.projectName;
this.composer.description = options.projectDescription;
// Allow distros to modify the composer.json.
if (typeof options.drupalDistro.modifyComposer == 'function') {
var done = this.async();
options.drupalDistro.modifyComposer(options, this.composer, isNewProject, done, function(err, result, done) {
if (!err && result) {
this.composer = result;
}
else {
this.log.warning("Could not retrieve Octane's composer.json: " + err);
return done(err);
}
done();
}.bind(this));
}
} | javascript | function () {
var isNewProject = (this.composerOrig == undefined);
if (!isNewProject) {
// Use original composer file if project already generated.
this.composer = this.composerOrig;
}
this.composer.name = 'organization/' + options.projectName;
this.composer.description = options.projectDescription;
// Allow distros to modify the composer.json.
if (typeof options.drupalDistro.modifyComposer == 'function') {
var done = this.async();
options.drupalDistro.modifyComposer(options, this.composer, isNewProject, done, function(err, result, done) {
if (!err && result) {
this.composer = result;
}
else {
this.log.warning("Could not retrieve Octane's composer.json: " + err);
return done(err);
}
done();
}.bind(this));
}
} | [
"function",
"(",
")",
"{",
"var",
"isNewProject",
"=",
"(",
"this",
".",
"composerOrig",
"==",
"undefined",
")",
";",
"if",
"(",
"!",
"isNewProject",
")",
"{",
"this",
".",
"composer",
"=",
"this",
".",
"composerOrig",
";",
"}",
"this",
".",
"composer",
".",
"name",
"=",
"'organization/'",
"+",
"options",
".",
"projectName",
";",
"this",
".",
"composer",
".",
"description",
"=",
"options",
".",
"projectDescription",
";",
"if",
"(",
"typeof",
"options",
".",
"drupalDistro",
".",
"modifyComposer",
"==",
"'function'",
")",
"{",
"var",
"done",
"=",
"this",
".",
"async",
"(",
")",
";",
"options",
".",
"drupalDistro",
".",
"modifyComposer",
"(",
"options",
",",
"this",
".",
"composer",
",",
"isNewProject",
",",
"done",
",",
"function",
"(",
"err",
",",
"result",
",",
"done",
")",
"{",
"if",
"(",
"!",
"err",
"&&",
"result",
")",
"{",
"this",
".",
"composer",
"=",
"result",
";",
"}",
"else",
"{",
"this",
".",
"log",
".",
"warning",
"(",
"\"Could not retrieve Octane's composer.json: \"",
"+",
"err",
")",
";",
"return",
"done",
"(",
"err",
")",
";",
"}",
"done",
"(",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
"}"
] | While there are write operations in this, other write operations may need to examine the composer.json to determine their own configuration. | [
"While",
"there",
"are",
"write",
"operations",
"in",
"this",
"other",
"write",
"operations",
"may",
"need",
"to",
"examine",
"the",
"composer",
".",
"json",
"to",
"determine",
"their",
"own",
"configuration",
"."
] | 8ebc9a6f7592ebc37844cd2aec346c2e00aaa91d | https://github.com/phase2/generator-gadget/blob/8ebc9a6f7592ebc37844cd2aec346c2e00aaa91d/generators/app/index.js#L165-L188 | train |
|
relution-io/relution-sdk | lib/connector/connector.js | runCall | function runCall(name, call, input) {
return web.post(connectorsUrl + '/' + name + '/' + call, input);
} | javascript | function runCall(name, call, input) {
return web.post(connectorsUrl + '/' + name + '/' + call, input);
} | [
"function",
"runCall",
"(",
"name",
",",
"call",
",",
"input",
")",
"{",
"return",
"web",
".",
"post",
"(",
"connectorsUrl",
"+",
"'/'",
"+",
"name",
"+",
"'/'",
"+",
"call",
",",
"input",
")",
";",
"}"
] | executes a call on a connection.
@param name of connection.
@param call name.
@param input data, i.e. an instance of a model or object compatible to the
model in terms of attributes defined.
@returns promise providing output/error. | [
"executes",
"a",
"call",
"on",
"a",
"connection",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/lib/connector/connector.js#L59-L61 | train |
wingbotai/wingbot | src/graphApi/validateBotApi.js | validateBotApi | function validateBotApi (botFactory, postBackTest, textTest, acl) {
/** @deprecated way to validate bot */
if (postBackTest && typeof postBackTest === 'object') {
// @ts-ignore
return validate(botFactory, postBackTest, textTest, acl)
.then((res) => {
if (!res.ok) {
throw new Error(res.error);
}
});
}
return {
async validateBot (args, ctx) {
if (!apiAuthorizer(args, ctx, acl)) {
return null;
}
const validationRequestBody = args.bot;
const bot = botFactory();
return validate(bot, validationRequestBody, postBackTest, textTest);
}
};
} | javascript | function validateBotApi (botFactory, postBackTest, textTest, acl) {
/** @deprecated way to validate bot */
if (postBackTest && typeof postBackTest === 'object') {
// @ts-ignore
return validate(botFactory, postBackTest, textTest, acl)
.then((res) => {
if (!res.ok) {
throw new Error(res.error);
}
});
}
return {
async validateBot (args, ctx) {
if (!apiAuthorizer(args, ctx, acl)) {
return null;
}
const validationRequestBody = args.bot;
const bot = botFactory();
return validate(bot, validationRequestBody, postBackTest, textTest);
}
};
} | [
"function",
"validateBotApi",
"(",
"botFactory",
",",
"postBackTest",
",",
"textTest",
",",
"acl",
")",
"{",
"if",
"(",
"postBackTest",
"&&",
"typeof",
"postBackTest",
"===",
"'object'",
")",
"{",
"return",
"validate",
"(",
"botFactory",
",",
"postBackTest",
",",
"textTest",
",",
"acl",
")",
".",
"then",
"(",
"(",
"res",
")",
"=>",
"{",
"if",
"(",
"!",
"res",
".",
"ok",
")",
"{",
"throw",
"new",
"Error",
"(",
"res",
".",
"error",
")",
";",
"}",
"}",
")",
";",
"}",
"return",
"{",
"async",
"validateBot",
"(",
"args",
",",
"ctx",
")",
"{",
"if",
"(",
"!",
"apiAuthorizer",
"(",
"args",
",",
"ctx",
",",
"acl",
")",
")",
"{",
"return",
"null",
";",
"}",
"const",
"validationRequestBody",
"=",
"args",
".",
"bot",
";",
"const",
"bot",
"=",
"botFactory",
"(",
")",
";",
"return",
"validate",
"(",
"bot",
",",
"validationRequestBody",
",",
"postBackTest",
",",
"textTest",
")",
";",
"}",
"}",
";",
"}"
] | Test the bot configuration
@param {Function} botFactory - function, which returns a bot
@param {string|null} [postBackTest] - postback action to test
@param {string|null} [textTest] - random text to test
@param {string[]|Function} [acl] - limit api to array of groups or use auth function
@returns {ValidateBotAPI}
@example
const { GraphApi, validateBotApi } = require('wingbot');
const api = new GraphApi([
validateBotApi(botFactory, 'start', 'hello')
], {
token: 'wingbot-token'
}) | [
"Test",
"the",
"bot",
"configuration"
] | 2a917d6a5798e6f3e2258ef445b600eddfd1961b | https://github.com/wingbotai/wingbot/blob/2a917d6a5798e6f3e2258ef445b600eddfd1961b/src/graphApi/validateBotApi.js#L61-L87 | train |
relution-io/relution-sdk | lib/web/offline.js | clearOfflineLogin | function clearOfflineLogin(credentials, serverOptions) {
// simultaneous logins using different credentials is not realized so far,
// so that the credentials parameter is irrelevant, but provided for the
// sake of completeness...
try {
localStorage().removeItem(computeLocalStorageKey(serverOptions));
return Q.resolve(undefined);
}
catch (error) {
return Q.reject(error);
}
} | javascript | function clearOfflineLogin(credentials, serverOptions) {
// simultaneous logins using different credentials is not realized so far,
// so that the credentials parameter is irrelevant, but provided for the
// sake of completeness...
try {
localStorage().removeItem(computeLocalStorageKey(serverOptions));
return Q.resolve(undefined);
}
catch (error) {
return Q.reject(error);
}
} | [
"function",
"clearOfflineLogin",
"(",
"credentials",
",",
"serverOptions",
")",
"{",
"try",
"{",
"localStorage",
"(",
")",
".",
"removeItem",
"(",
"computeLocalStorageKey",
"(",
"serverOptions",
")",
")",
";",
"return",
"Q",
".",
"resolve",
"(",
"undefined",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"return",
"Q",
".",
"reject",
"(",
"error",
")",
";",
"}",
"}"
] | deletes stored login response of some server.
@param credentials allowing to differentiate when multiple logins are used simultaneously, may
be null to forget just anything.
@param serverOptions identifying the server.
@return {Promise<void>} indicating success or failure.
@internal Not part of public API, for library use only. | [
"deletes",
"stored",
"login",
"response",
"of",
"some",
"server",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/lib/web/offline.js#L58-L69 | train |
relution-io/relution-sdk | lib/web/offline.js | storeOfflineLogin | function storeOfflineLogin(credentials, serverOptions, loginResponse) {
return cipher.encryptJson(credentials['password'], loginResponse).then(function (value) {
localStorage().setItem(computeLocalStorageKey(serverOptions), JSON.stringify(value));
return loginResponse;
});
} | javascript | function storeOfflineLogin(credentials, serverOptions, loginResponse) {
return cipher.encryptJson(credentials['password'], loginResponse).then(function (value) {
localStorage().setItem(computeLocalStorageKey(serverOptions), JSON.stringify(value));
return loginResponse;
});
} | [
"function",
"storeOfflineLogin",
"(",
"credentials",
",",
"serverOptions",
",",
"loginResponse",
")",
"{",
"return",
"cipher",
".",
"encryptJson",
"(",
"credentials",
"[",
"'password'",
"]",
",",
"loginResponse",
")",
".",
"then",
"(",
"function",
"(",
"value",
")",
"{",
"localStorage",
"(",
")",
".",
"setItem",
"(",
"computeLocalStorageKey",
"(",
"serverOptions",
")",
",",
"JSON",
".",
"stringify",
"(",
"value",
")",
")",
";",
"return",
"loginResponse",
";",
"}",
")",
";",
"}"
] | writes response data to persistent storage for offline login purposes.
@param credentials required for encryption.
@param serverOptions identifying the server.
@param loginResponse permitted to durable storage.
@return {Promise<http.LoginResponse>} indicating success or failure.
@internal Not part of public API, for library use only. | [
"writes",
"response",
"data",
"to",
"persistent",
"storage",
"for",
"offline",
"login",
"purposes",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/lib/web/offline.js#L81-L86 | train |
relution-io/relution-sdk | lib/web/offline.js | fetchOfflineLogin | function fetchOfflineLogin(credentials, serverOptions) {
try {
var value = localStorage().getItem(computeLocalStorageKey(serverOptions));
if (!value) {
return Q.resolve(undefined);
}
return cipher.decryptJson(credentials['password'], JSON.parse(value));
}
catch (error) {
return Q.reject(error);
}
} | javascript | function fetchOfflineLogin(credentials, serverOptions) {
try {
var value = localStorage().getItem(computeLocalStorageKey(serverOptions));
if (!value) {
return Q.resolve(undefined);
}
return cipher.decryptJson(credentials['password'], JSON.parse(value));
}
catch (error) {
return Q.reject(error);
}
} | [
"function",
"fetchOfflineLogin",
"(",
"credentials",
",",
"serverOptions",
")",
"{",
"try",
"{",
"var",
"value",
"=",
"localStorage",
"(",
")",
".",
"getItem",
"(",
"computeLocalStorageKey",
"(",
"serverOptions",
")",
")",
";",
"if",
"(",
"!",
"value",
")",
"{",
"return",
"Q",
".",
"resolve",
"(",
"undefined",
")",
";",
"}",
"return",
"cipher",
".",
"decryptJson",
"(",
"credentials",
"[",
"'password'",
"]",
",",
"JSON",
".",
"parse",
"(",
"value",
")",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"return",
"Q",
".",
"reject",
"(",
"error",
")",
";",
"}",
"}"
] | reads response data from persistent storage.
When there is no data in persitent store, the operation does NOT fail. In this case the
resulting promise resolves to nil instead.
@param credentials required for decryption.
@param serverOptions identifying the server.
@return {Promise<http.LoginResponse>} read from store, resolves to nil when there is no data,
gets rejected when decryption fails.
@internal Not part of public API, for library use only. | [
"reads",
"response",
"data",
"from",
"persistent",
"storage",
"."
] | 776b8bd0c249428add03f97ba2d19092e709bc7b | https://github.com/relution-io/relution-sdk/blob/776b8bd0c249428add03f97ba2d19092e709bc7b/lib/web/offline.js#L101-L112 | train |
saneki-discontinued/node-toxcore | lib/toxencryptsave.js | function(opts) {
// If opts is a string, assume libpath
if(_.isString(opts)) {
opts = { path: opts }
}
if(!opts) opts = {};
var libpath = opts['path'];
this._library = this._createLibrary(libpath);
} | javascript | function(opts) {
// If opts is a string, assume libpath
if(_.isString(opts)) {
opts = { path: opts }
}
if(!opts) opts = {};
var libpath = opts['path'];
this._library = this._createLibrary(libpath);
} | [
"function",
"(",
"opts",
")",
"{",
"if",
"(",
"_",
".",
"isString",
"(",
"opts",
")",
")",
"{",
"opts",
"=",
"{",
"path",
":",
"opts",
"}",
"}",
"if",
"(",
"!",
"opts",
")",
"opts",
"=",
"{",
"}",
";",
"var",
"libpath",
"=",
"opts",
"[",
"'path'",
"]",
";",
"this",
".",
"_library",
"=",
"this",
".",
"_createLibrary",
"(",
"libpath",
")",
";",
"}"
] | Creates a ToxEncryptSave instance.
@class
@param {(Object|String)} [opts] Options | [
"Creates",
"a",
"ToxEncryptSave",
"instance",
"."
] | 45dfb339f4e8a58888fca175528dee13f075824a | https://github.com/saneki-discontinued/node-toxcore/blob/45dfb339f4e8a58888fca175528dee13f075824a/lib/toxencryptsave.js#L49-L59 | train |
|
canjs/can-query-logic | src/types/keys-and.js | KeysAnd | function KeysAnd(values) {
var vals = this.values = {};
canReflect.eachKey(values, function(value, key) {
if (canReflect.isPlainObject(value) && !set.isSpecial(value)) {
vals[key] = new KeysAnd(value);
} else {
vals[key] = value;
}
});
} | javascript | function KeysAnd(values) {
var vals = this.values = {};
canReflect.eachKey(values, function(value, key) {
if (canReflect.isPlainObject(value) && !set.isSpecial(value)) {
vals[key] = new KeysAnd(value);
} else {
vals[key] = value;
}
});
} | [
"function",
"KeysAnd",
"(",
"values",
")",
"{",
"var",
"vals",
"=",
"this",
".",
"values",
"=",
"{",
"}",
";",
"canReflect",
".",
"eachKey",
"(",
"values",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"if",
"(",
"canReflect",
".",
"isPlainObject",
"(",
"value",
")",
"&&",
"!",
"set",
".",
"isSpecial",
"(",
"value",
")",
")",
"{",
"vals",
"[",
"key",
"]",
"=",
"new",
"KeysAnd",
"(",
"value",
")",
";",
"}",
"else",
"{",
"vals",
"[",
"key",
"]",
"=",
"value",
";",
"}",
"}",
")",
";",
"}"
] | Define the sub-types that BasicQuery will use | [
"Define",
"the",
"sub",
"-",
"types",
"that",
"BasicQuery",
"will",
"use"
] | fe32908e7aa36853362fbc1a4df276193247f38d | https://github.com/canjs/can-query-logic/blob/fe32908e7aa36853362fbc1a4df276193247f38d/src/types/keys-and.js#L11-L20 | train |
Pajn/tscomp | config/paths.js | resolveAppBuild | function resolveAppBuild(appTsConfigPath) {
const outDir = getAppBuildFolder(appTsConfigPath);
const buildPath = path.join(path.dirname(appTsConfigPath), outDir);
return buildPath;
} | javascript | function resolveAppBuild(appTsConfigPath) {
const outDir = getAppBuildFolder(appTsConfigPath);
const buildPath = path.join(path.dirname(appTsConfigPath), outDir);
return buildPath;
} | [
"function",
"resolveAppBuild",
"(",
"appTsConfigPath",
")",
"{",
"const",
"outDir",
"=",
"getAppBuildFolder",
"(",
"appTsConfigPath",
")",
";",
"const",
"buildPath",
"=",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"appTsConfigPath",
")",
",",
"outDir",
")",
";",
"return",
"buildPath",
";",
"}"
] | The user may choose to change the tsconfig.json `outDir` property. | [
"The",
"user",
"may",
"choose",
"to",
"change",
"the",
"tsconfig",
".",
"json",
"outDir",
"property",
"."
] | 82ab5d2237a324ca0e2ef4c108611b9eb975f2e8 | https://github.com/Pajn/tscomp/blob/82ab5d2237a324ca0e2ef4c108611b9eb975f2e8/config/paths.js#L31-L35 | train |
soajs/soajs.urac.driver | index.js | initBLModel | function initBLModel(soajs, cb) {
let modelName = driverConfig.model;
if (soajs.servicesConfig && soajs.servicesConfig.model) {
modelName = soajs.servicesConfig.model;
}
if (process.env.SOAJS_TEST && soajs.inputmaskData && soajs.inputmaskData.model) {
modelName = soajs.inputmaskData.model;
}
let modelPath = __dirname + "/model/" + modelName + ".js";
return requireModel(modelPath, cb);
/**
* checks if model file exists, requires it and returns it.
* @param filePath
* @param cb
*/
function requireModel(filePath, cb) {
//check if file exist. if not return error
fs.exists(filePath, function (exists) {
if (!exists) {
soajs.log.error('Requested Model Not Found!');
return cb(601);
}
driver.model = require(filePath);
return cb();
});
}
} | javascript | function initBLModel(soajs, cb) {
let modelName = driverConfig.model;
if (soajs.servicesConfig && soajs.servicesConfig.model) {
modelName = soajs.servicesConfig.model;
}
if (process.env.SOAJS_TEST && soajs.inputmaskData && soajs.inputmaskData.model) {
modelName = soajs.inputmaskData.model;
}
let modelPath = __dirname + "/model/" + modelName + ".js";
return requireModel(modelPath, cb);
/**
* checks if model file exists, requires it and returns it.
* @param filePath
* @param cb
*/
function requireModel(filePath, cb) {
//check if file exist. if not return error
fs.exists(filePath, function (exists) {
if (!exists) {
soajs.log.error('Requested Model Not Found!');
return cb(601);
}
driver.model = require(filePath);
return cb();
});
}
} | [
"function",
"initBLModel",
"(",
"soajs",
",",
"cb",
")",
"{",
"let",
"modelName",
"=",
"driverConfig",
".",
"model",
";",
"if",
"(",
"soajs",
".",
"servicesConfig",
"&&",
"soajs",
".",
"servicesConfig",
".",
"model",
")",
"{",
"modelName",
"=",
"soajs",
".",
"servicesConfig",
".",
"model",
";",
"}",
"if",
"(",
"process",
".",
"env",
".",
"SOAJS_TEST",
"&&",
"soajs",
".",
"inputmaskData",
"&&",
"soajs",
".",
"inputmaskData",
".",
"model",
")",
"{",
"modelName",
"=",
"soajs",
".",
"inputmaskData",
".",
"model",
";",
"}",
"let",
"modelPath",
"=",
"__dirname",
"+",
"\"/model/\"",
"+",
"modelName",
"+",
"\".js\"",
";",
"return",
"requireModel",
"(",
"modelPath",
",",
"cb",
")",
";",
"function",
"requireModel",
"(",
"filePath",
",",
"cb",
")",
"{",
"fs",
".",
"exists",
"(",
"filePath",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"!",
"exists",
")",
"{",
"soajs",
".",
"log",
".",
"error",
"(",
"'Requested Model Not Found!'",
")",
";",
"return",
"cb",
"(",
"601",
")",
";",
"}",
"driver",
".",
"model",
"=",
"require",
"(",
"filePath",
")",
";",
"return",
"cb",
"(",
")",
";",
"}",
")",
";",
"}",
"}"
] | Initialize the Business Logic model and set it on driver | [
"Initialize",
"the",
"Business",
"Logic",
"model",
"and",
"set",
"it",
"on",
"driver"
] | b9b07dd5269b13d4fd5987ee2c5869d7eccba086 | https://github.com/soajs/soajs.urac.driver/blob/b9b07dd5269b13d4fd5987ee2c5869d7eccba086/index.js#L17-L47 | train |
soajs/soajs.urac.driver | index.js | requireModel | function requireModel(filePath, cb) {
//check if file exist. if not return error
fs.exists(filePath, function (exists) {
if (!exists) {
soajs.log.error('Requested Model Not Found!');
return cb(601);
}
driver.model = require(filePath);
return cb();
});
} | javascript | function requireModel(filePath, cb) {
//check if file exist. if not return error
fs.exists(filePath, function (exists) {
if (!exists) {
soajs.log.error('Requested Model Not Found!');
return cb(601);
}
driver.model = require(filePath);
return cb();
});
} | [
"function",
"requireModel",
"(",
"filePath",
",",
"cb",
")",
"{",
"fs",
".",
"exists",
"(",
"filePath",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"!",
"exists",
")",
"{",
"soajs",
".",
"log",
".",
"error",
"(",
"'Requested Model Not Found!'",
")",
";",
"return",
"cb",
"(",
"601",
")",
";",
"}",
"driver",
".",
"model",
"=",
"require",
"(",
"filePath",
")",
";",
"return",
"cb",
"(",
")",
";",
"}",
")",
";",
"}"
] | checks if model file exists, requires it and returns it.
@param filePath
@param cb | [
"checks",
"if",
"model",
"file",
"exists",
"requires",
"it",
"and",
"returns",
"it",
"."
] | b9b07dd5269b13d4fd5987ee2c5869d7eccba086 | https://github.com/soajs/soajs.urac.driver/blob/b9b07dd5269b13d4fd5987ee2c5869d7eccba086/index.js#L34-L45 | train |
soajs/soajs.urac.driver | index.js | function (req, res, passport, cb) {
let authentication = req.soajs.inputmaskData.strategy;
passportLib.getDriver(req, false, function (err, passportDriver) {
passportDriver.preAuthenticate(req, function () {
passport.authenticate(authentication, {session: false}, function (err, user) {
if (err) {
req.soajs.log.error(err);
return cb({"code": 499, "msg": err.toString()});
}
if (!user) {
cb({"code": 403, "msg": req.soajs.config.errors[403]});
}
req.soajs.inputmaskData.user = user;
initBLModel(req.soajs, function (err) {
if (err) {
return cb(err);
}
let mode = req.soajs.inputmaskData.strategy;
utilities.saveUser(req.soajs, driver.model, mode, user, function (error, data) {
cb(error, data);
});
});
})(req, res);
});
});
} | javascript | function (req, res, passport, cb) {
let authentication = req.soajs.inputmaskData.strategy;
passportLib.getDriver(req, false, function (err, passportDriver) {
passportDriver.preAuthenticate(req, function () {
passport.authenticate(authentication, {session: false}, function (err, user) {
if (err) {
req.soajs.log.error(err);
return cb({"code": 499, "msg": err.toString()});
}
if (!user) {
cb({"code": 403, "msg": req.soajs.config.errors[403]});
}
req.soajs.inputmaskData.user = user;
initBLModel(req.soajs, function (err) {
if (err) {
return cb(err);
}
let mode = req.soajs.inputmaskData.strategy;
utilities.saveUser(req.soajs, driver.model, mode, user, function (error, data) {
cb(error, data);
});
});
})(req, res);
});
});
} | [
"function",
"(",
"req",
",",
"res",
",",
"passport",
",",
"cb",
")",
"{",
"let",
"authentication",
"=",
"req",
".",
"soajs",
".",
"inputmaskData",
".",
"strategy",
";",
"passportLib",
".",
"getDriver",
"(",
"req",
",",
"false",
",",
"function",
"(",
"err",
",",
"passportDriver",
")",
"{",
"passportDriver",
".",
"preAuthenticate",
"(",
"req",
",",
"function",
"(",
")",
"{",
"passport",
".",
"authenticate",
"(",
"authentication",
",",
"{",
"session",
":",
"false",
"}",
",",
"function",
"(",
"err",
",",
"user",
")",
"{",
"if",
"(",
"err",
")",
"{",
"req",
".",
"soajs",
".",
"log",
".",
"error",
"(",
"err",
")",
";",
"return",
"cb",
"(",
"{",
"\"code\"",
":",
"499",
",",
"\"msg\"",
":",
"err",
".",
"toString",
"(",
")",
"}",
")",
";",
"}",
"if",
"(",
"!",
"user",
")",
"{",
"cb",
"(",
"{",
"\"code\"",
":",
"403",
",",
"\"msg\"",
":",
"req",
".",
"soajs",
".",
"config",
".",
"errors",
"[",
"403",
"]",
"}",
")",
";",
"}",
"req",
".",
"soajs",
".",
"inputmaskData",
".",
"user",
"=",
"user",
";",
"initBLModel",
"(",
"req",
".",
"soajs",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"let",
"mode",
"=",
"req",
".",
"soajs",
".",
"inputmaskData",
".",
"strategy",
";",
"utilities",
".",
"saveUser",
"(",
"req",
".",
"soajs",
",",
"driver",
".",
"model",
",",
"mode",
",",
"user",
",",
"function",
"(",
"error",
",",
"data",
")",
"{",
"cb",
"(",
"error",
",",
"data",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
"(",
"req",
",",
"res",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Get driver, do what is needed before authenticating, and authenticate | [
"Get",
"driver",
"do",
"what",
"is",
"needed",
"before",
"authenticating",
"and",
"authenticate"
] | b9b07dd5269b13d4fd5987ee2c5869d7eccba086 | https://github.com/soajs/soajs.urac.driver/blob/b9b07dd5269b13d4fd5987ee2c5869d7eccba086/index.js#L130-L159 | train |
|
soajs/soajs.urac.driver | index.js | function (soajs, data, cb) {
initBLModel(soajs, function (err) {
if (err) {
return cb(err);
}
driver.model.initConnection(soajs);
let criteria = null;
if (!(data.username || data.id)) {
return cb(411);
}
if (data.username) {
criteria = {
'username': data.username
};
}
else {
let id = null;
try {
id = driver.model.validateId(soajs, data.id);
criteria = {
'_id': id
};
}
catch (e) {
return cb(411);
}
}
if (!criteria)
return cb(403);
utilities.findRecord(soajs, driver.model, criteria, cb, function (record) {
delete record.password;
let groupInfo = checkUserTenantAccess(record, soajs.tenant);
if (groupInfo && groupInfo.groups && Array.isArray(groupInfo.groups) && groupInfo.groups.length !== 0) {
record.groups = groupInfo.groups;
record.tenant = groupInfo.tenant;
utilities.findGroups(soajs, driver.model, record, function (record) {
returnUser(record);
});
}
else {
returnUser(record);
}
function returnUser(record) {
utilities.assureConfig(soajs, record);
driver.model.closeConnection(soajs);
return cb(null, record);
}
});
});
} | javascript | function (soajs, data, cb) {
initBLModel(soajs, function (err) {
if (err) {
return cb(err);
}
driver.model.initConnection(soajs);
let criteria = null;
if (!(data.username || data.id)) {
return cb(411);
}
if (data.username) {
criteria = {
'username': data.username
};
}
else {
let id = null;
try {
id = driver.model.validateId(soajs, data.id);
criteria = {
'_id': id
};
}
catch (e) {
return cb(411);
}
}
if (!criteria)
return cb(403);
utilities.findRecord(soajs, driver.model, criteria, cb, function (record) {
delete record.password;
let groupInfo = checkUserTenantAccess(record, soajs.tenant);
if (groupInfo && groupInfo.groups && Array.isArray(groupInfo.groups) && groupInfo.groups.length !== 0) {
record.groups = groupInfo.groups;
record.tenant = groupInfo.tenant;
utilities.findGroups(soajs, driver.model, record, function (record) {
returnUser(record);
});
}
else {
returnUser(record);
}
function returnUser(record) {
utilities.assureConfig(soajs, record);
driver.model.closeConnection(soajs);
return cb(null, record);
}
});
});
} | [
"function",
"(",
"soajs",
",",
"data",
",",
"cb",
")",
"{",
"initBLModel",
"(",
"soajs",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"driver",
".",
"model",
".",
"initConnection",
"(",
"soajs",
")",
";",
"let",
"criteria",
"=",
"null",
";",
"if",
"(",
"!",
"(",
"data",
".",
"username",
"||",
"data",
".",
"id",
")",
")",
"{",
"return",
"cb",
"(",
"411",
")",
";",
"}",
"if",
"(",
"data",
".",
"username",
")",
"{",
"criteria",
"=",
"{",
"'username'",
":",
"data",
".",
"username",
"}",
";",
"}",
"else",
"{",
"let",
"id",
"=",
"null",
";",
"try",
"{",
"id",
"=",
"driver",
".",
"model",
".",
"validateId",
"(",
"soajs",
",",
"data",
".",
"id",
")",
";",
"criteria",
"=",
"{",
"'_id'",
":",
"id",
"}",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"cb",
"(",
"411",
")",
";",
"}",
"}",
"if",
"(",
"!",
"criteria",
")",
"return",
"cb",
"(",
"403",
")",
";",
"utilities",
".",
"findRecord",
"(",
"soajs",
",",
"driver",
".",
"model",
",",
"criteria",
",",
"cb",
",",
"function",
"(",
"record",
")",
"{",
"delete",
"record",
".",
"password",
";",
"let",
"groupInfo",
"=",
"checkUserTenantAccess",
"(",
"record",
",",
"soajs",
".",
"tenant",
")",
";",
"if",
"(",
"groupInfo",
"&&",
"groupInfo",
".",
"groups",
"&&",
"Array",
".",
"isArray",
"(",
"groupInfo",
".",
"groups",
")",
"&&",
"groupInfo",
".",
"groups",
".",
"length",
"!==",
"0",
")",
"{",
"record",
".",
"groups",
"=",
"groupInfo",
".",
"groups",
";",
"record",
".",
"tenant",
"=",
"groupInfo",
".",
"tenant",
";",
"utilities",
".",
"findGroups",
"(",
"soajs",
",",
"driver",
".",
"model",
",",
"record",
",",
"function",
"(",
"record",
")",
"{",
"returnUser",
"(",
"record",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"returnUser",
"(",
"record",
")",
";",
"}",
"function",
"returnUser",
"(",
"record",
")",
"{",
"utilities",
".",
"assureConfig",
"(",
"soajs",
",",
"record",
")",
";",
"driver",
".",
"model",
".",
"closeConnection",
"(",
"soajs",
")",
";",
"return",
"cb",
"(",
"null",
",",
"record",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] | Get logged in record from database | [
"Get",
"logged",
"in",
"record",
"from",
"database"
] | b9b07dd5269b13d4fd5987ee2c5869d7eccba086 | https://github.com/soajs/soajs.urac.driver/blob/b9b07dd5269b13d4fd5987ee2c5869d7eccba086/index.js#L287-L339 | train |
|
soajs/soajs.urac.driver | index.js | function (soajs, data, cb) {
let token = data.token;
let openam;
if (soajs.servicesConfig.urac && soajs.servicesConfig.urac.openam) {
openam = soajs.servicesConfig.urac.openam;
}
else {
return cb({"code": 712, "msg": soajs.config.errors[712]});
}
let openamAttributesURL = openam.attributesURL;
let openamAttributesMap = openam.attributesMap;
let openamTimeout = openam.timeout || 10000;
request.post(openamAttributesURL, {
form: {subjectid: token},
timeout: openamTimeout
}, function (error, response, body) {
let userRecord;
if (error) {
soajs.log.error(error);
return cb({"code": 710, "msg": soajs.config.errors[710]});
}
if (!response || response.statusCode !== 200) {
soajs.log.error("OpenAM token invalid!");
return cb({"code": 711, "msg": soajs.config.errors[711]});
}
try {
userRecord = JSON.parse(body);
} catch (err) {
soajs.log.error("OpenAM response invalid!");
return cb({"code": 712, "msg": soajs.config.errors[712]});
}
soajs.log.debug('Authenticated!');
initBLModel(soajs, function (err) {
if (err) {
return cb(err);
}
utilities.saveUser(soajs, driver.model, 'openam', {
userRecord: userRecord,
attributesMap: openamAttributesMap
}, function (error, record) {
return cb(null, record);
});
});
});
} | javascript | function (soajs, data, cb) {
let token = data.token;
let openam;
if (soajs.servicesConfig.urac && soajs.servicesConfig.urac.openam) {
openam = soajs.servicesConfig.urac.openam;
}
else {
return cb({"code": 712, "msg": soajs.config.errors[712]});
}
let openamAttributesURL = openam.attributesURL;
let openamAttributesMap = openam.attributesMap;
let openamTimeout = openam.timeout || 10000;
request.post(openamAttributesURL, {
form: {subjectid: token},
timeout: openamTimeout
}, function (error, response, body) {
let userRecord;
if (error) {
soajs.log.error(error);
return cb({"code": 710, "msg": soajs.config.errors[710]});
}
if (!response || response.statusCode !== 200) {
soajs.log.error("OpenAM token invalid!");
return cb({"code": 711, "msg": soajs.config.errors[711]});
}
try {
userRecord = JSON.parse(body);
} catch (err) {
soajs.log.error("OpenAM response invalid!");
return cb({"code": 712, "msg": soajs.config.errors[712]});
}
soajs.log.debug('Authenticated!');
initBLModel(soajs, function (err) {
if (err) {
return cb(err);
}
utilities.saveUser(soajs, driver.model, 'openam', {
userRecord: userRecord,
attributesMap: openamAttributesMap
}, function (error, record) {
return cb(null, record);
});
});
});
} | [
"function",
"(",
"soajs",
",",
"data",
",",
"cb",
")",
"{",
"let",
"token",
"=",
"data",
".",
"token",
";",
"let",
"openam",
";",
"if",
"(",
"soajs",
".",
"servicesConfig",
".",
"urac",
"&&",
"soajs",
".",
"servicesConfig",
".",
"urac",
".",
"openam",
")",
"{",
"openam",
"=",
"soajs",
".",
"servicesConfig",
".",
"urac",
".",
"openam",
";",
"}",
"else",
"{",
"return",
"cb",
"(",
"{",
"\"code\"",
":",
"712",
",",
"\"msg\"",
":",
"soajs",
".",
"config",
".",
"errors",
"[",
"712",
"]",
"}",
")",
";",
"}",
"let",
"openamAttributesURL",
"=",
"openam",
".",
"attributesURL",
";",
"let",
"openamAttributesMap",
"=",
"openam",
".",
"attributesMap",
";",
"let",
"openamTimeout",
"=",
"openam",
".",
"timeout",
"||",
"10000",
";",
"request",
".",
"post",
"(",
"openamAttributesURL",
",",
"{",
"form",
":",
"{",
"subjectid",
":",
"token",
"}",
",",
"timeout",
":",
"openamTimeout",
"}",
",",
"function",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"let",
"userRecord",
";",
"if",
"(",
"error",
")",
"{",
"soajs",
".",
"log",
".",
"error",
"(",
"error",
")",
";",
"return",
"cb",
"(",
"{",
"\"code\"",
":",
"710",
",",
"\"msg\"",
":",
"soajs",
".",
"config",
".",
"errors",
"[",
"710",
"]",
"}",
")",
";",
"}",
"if",
"(",
"!",
"response",
"||",
"response",
".",
"statusCode",
"!==",
"200",
")",
"{",
"soajs",
".",
"log",
".",
"error",
"(",
"\"OpenAM token invalid!\"",
")",
";",
"return",
"cb",
"(",
"{",
"\"code\"",
":",
"711",
",",
"\"msg\"",
":",
"soajs",
".",
"config",
".",
"errors",
"[",
"711",
"]",
"}",
")",
";",
"}",
"try",
"{",
"userRecord",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"soajs",
".",
"log",
".",
"error",
"(",
"\"OpenAM response invalid!\"",
")",
";",
"return",
"cb",
"(",
"{",
"\"code\"",
":",
"712",
",",
"\"msg\"",
":",
"soajs",
".",
"config",
".",
"errors",
"[",
"712",
"]",
"}",
")",
";",
"}",
"soajs",
".",
"log",
".",
"debug",
"(",
"'Authenticated!'",
")",
";",
"initBLModel",
"(",
"soajs",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"utilities",
".",
"saveUser",
"(",
"soajs",
",",
"driver",
".",
"model",
",",
"'openam'",
",",
"{",
"userRecord",
":",
"userRecord",
",",
"attributesMap",
":",
"openamAttributesMap",
"}",
",",
"function",
"(",
"error",
",",
"record",
")",
"{",
"return",
"cb",
"(",
"null",
",",
"record",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Login through OpenAM
Expects to have openam configuration object under soajs.servicesConfig.urac.
Example openam configuration object:
{
attributesURL: "https://test.com/openam/identity/json/attributes",
attributesMap: [
{ field: 'sAMAccountName', mapTo: 'id' },
{ field: 'sAMAccountName', mapTo: 'username' },
{ field: 'mail', mapTo: 'email' },
{ field: 'givenname', mapTo: 'firstName' },
{ field: 'sn', mapTo: 'lastName' }
],
timeout: 5000
} | [
"Login",
"through",
"OpenAM"
] | b9b07dd5269b13d4fd5987ee2c5869d7eccba086 | https://github.com/soajs/soajs.urac.driver/blob/b9b07dd5269b13d4fd5987ee2c5869d7eccba086/index.js#L359-L411 | train |
|
soajs/soajs.urac.driver | model/mongo.js | function (soajs) {
if (soajs.inputmaskData && soajs.inputmaskData.isOwner) {
soajs.mongoDb = new Mongo(soajs.meta.tenantDB(soajs.registry.tenantMetaDB, 'urac', soajs.inputmaskData.tCode));
}
else {
let tcode = soajs.tenant.code;
if (soajs.tenant.roaming && soajs.tenant.roaming.code) {
tcode = soajs.tenant.roaming.code;
}
let tenantMetaDB = soajs.registry.tenantMetaDB;
if (soajs.tenant.roaming && soajs.tenant.roaming.tenantMetaDB) {
tenantMetaDB = soajs.tenant.roaming.tenantMetaDB;
}
let config = soajs.meta.tenantDB(tenantMetaDB, 'urac', tcode);
soajs.mongoDb = new Mongo(config);
}
} | javascript | function (soajs) {
if (soajs.inputmaskData && soajs.inputmaskData.isOwner) {
soajs.mongoDb = new Mongo(soajs.meta.tenantDB(soajs.registry.tenantMetaDB, 'urac', soajs.inputmaskData.tCode));
}
else {
let tcode = soajs.tenant.code;
if (soajs.tenant.roaming && soajs.tenant.roaming.code) {
tcode = soajs.tenant.roaming.code;
}
let tenantMetaDB = soajs.registry.tenantMetaDB;
if (soajs.tenant.roaming && soajs.tenant.roaming.tenantMetaDB) {
tenantMetaDB = soajs.tenant.roaming.tenantMetaDB;
}
let config = soajs.meta.tenantDB(tenantMetaDB, 'urac', tcode);
soajs.mongoDb = new Mongo(config);
}
} | [
"function",
"(",
"soajs",
")",
"{",
"if",
"(",
"soajs",
".",
"inputmaskData",
"&&",
"soajs",
".",
"inputmaskData",
".",
"isOwner",
")",
"{",
"soajs",
".",
"mongoDb",
"=",
"new",
"Mongo",
"(",
"soajs",
".",
"meta",
".",
"tenantDB",
"(",
"soajs",
".",
"registry",
".",
"tenantMetaDB",
",",
"'urac'",
",",
"soajs",
".",
"inputmaskData",
".",
"tCode",
")",
")",
";",
"}",
"else",
"{",
"let",
"tcode",
"=",
"soajs",
".",
"tenant",
".",
"code",
";",
"if",
"(",
"soajs",
".",
"tenant",
".",
"roaming",
"&&",
"soajs",
".",
"tenant",
".",
"roaming",
".",
"code",
")",
"{",
"tcode",
"=",
"soajs",
".",
"tenant",
".",
"roaming",
".",
"code",
";",
"}",
"let",
"tenantMetaDB",
"=",
"soajs",
".",
"registry",
".",
"tenantMetaDB",
";",
"if",
"(",
"soajs",
".",
"tenant",
".",
"roaming",
"&&",
"soajs",
".",
"tenant",
".",
"roaming",
".",
"tenantMetaDB",
")",
"{",
"tenantMetaDB",
"=",
"soajs",
".",
"tenant",
".",
"roaming",
".",
"tenantMetaDB",
";",
"}",
"let",
"config",
"=",
"soajs",
".",
"meta",
".",
"tenantDB",
"(",
"tenantMetaDB",
",",
"'urac'",
",",
"tcode",
")",
";",
"soajs",
".",
"mongoDb",
"=",
"new",
"Mongo",
"(",
"config",
")",
";",
"}",
"}"
] | Initialize the mongo connection | [
"Initialize",
"the",
"mongo",
"connection"
] | b9b07dd5269b13d4fd5987ee2c5869d7eccba086 | https://github.com/soajs/soajs.urac.driver/blob/b9b07dd5269b13d4fd5987ee2c5869d7eccba086/model/mongo.js#L8-L25 | train |
|
soajs/soajs.urac.driver | model/mongo.js | function (soajs, id) {
let id1;
try {
id1 = soajs.mongoDb.ObjectId(id.toString());
return id1;
}
catch (e) {
soajs.log.error(e);
throw e;
}
} | javascript | function (soajs, id) {
let id1;
try {
id1 = soajs.mongoDb.ObjectId(id.toString());
return id1;
}
catch (e) {
soajs.log.error(e);
throw e;
}
} | [
"function",
"(",
"soajs",
",",
"id",
")",
"{",
"let",
"id1",
";",
"try",
"{",
"id1",
"=",
"soajs",
".",
"mongoDb",
".",
"ObjectId",
"(",
"id",
".",
"toString",
"(",
")",
")",
";",
"return",
"id1",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"soajs",
".",
"log",
".",
"error",
"(",
"e",
")",
";",
"throw",
"e",
";",
"}",
"}"
] | Validates the mongo object ID | [
"Validates",
"the",
"mongo",
"object",
"ID"
] | b9b07dd5269b13d4fd5987ee2c5869d7eccba086 | https://github.com/soajs/soajs.urac.driver/blob/b9b07dd5269b13d4fd5987ee2c5869d7eccba086/model/mongo.js#L37-L47 | train |
|
soajs/soajs.urac.driver | model/mongo.js | function (soajs, combo, cb) {
soajs.mongoDb.find(combo.collection, combo.condition || {}, combo.fields || null, combo.options || null, cb);
} | javascript | function (soajs, combo, cb) {
soajs.mongoDb.find(combo.collection, combo.condition || {}, combo.fields || null, combo.options || null, cb);
} | [
"function",
"(",
"soajs",
",",
"combo",
",",
"cb",
")",
"{",
"soajs",
".",
"mongoDb",
".",
"find",
"(",
"combo",
".",
"collection",
",",
"combo",
".",
"condition",
"||",
"{",
"}",
",",
"combo",
".",
"fields",
"||",
"null",
",",
"combo",
".",
"options",
"||",
"null",
",",
"cb",
")",
";",
"}"
] | Find multiple entries based on a condition | [
"Find",
"multiple",
"entries",
"based",
"on",
"a",
"condition"
] | b9b07dd5269b13d4fd5987ee2c5869d7eccba086 | https://github.com/soajs/soajs.urac.driver/blob/b9b07dd5269b13d4fd5987ee2c5869d7eccba086/model/mongo.js#L52-L54 | train |
|
soajs/soajs.urac.driver | model/mongo.js | function (soajs, combo, cb) {
soajs.mongoDb.insert(combo.collection, combo.record, cb);
} | javascript | function (soajs, combo, cb) {
soajs.mongoDb.insert(combo.collection, combo.record, cb);
} | [
"function",
"(",
"soajs",
",",
"combo",
",",
"cb",
")",
"{",
"soajs",
".",
"mongoDb",
".",
"insert",
"(",
"combo",
".",
"collection",
",",
"combo",
".",
"record",
",",
"cb",
")",
";",
"}"
] | Insert a new entry in the database | [
"Insert",
"a",
"new",
"entry",
"in",
"the",
"database"
] | b9b07dd5269b13d4fd5987ee2c5869d7eccba086 | https://github.com/soajs/soajs.urac.driver/blob/b9b07dd5269b13d4fd5987ee2c5869d7eccba086/model/mongo.js#L80-L82 | train |
|
duniter/duniter-ui | public/libraries.js | configFromRFC2822 | function configFromRFC2822(config) {
var string, match, dayFormat,
dateFormat, timeFormat, tzFormat;
var timezones = {
' GMT': ' +0000',
' EDT': ' -0400',
' EST': ' -0500',
' CDT': ' -0500',
' CST': ' -0600',
' MDT': ' -0600',
' MST': ' -0700',
' PDT': ' -0700',
' PST': ' -0800'
};
var military = 'YXWVUTSRQPONZABCDEFGHIKLM';
var timezone, timezoneIndex;
string = config._i
.replace(/\([^\)]*\)|[\n\t]/g, ' ') // Remove comments and folding whitespace
.replace(/(\s\s+)/g, ' ') // Replace multiple-spaces with a single space
.replace(/^\s|\s$/g, ''); // Remove leading and trailing spaces
match = basicRfcRegex.exec(string);
if (match) {
dayFormat = match[1] ? 'ddd' + ((match[1].length === 5) ? ', ' : ' ') : '';
dateFormat = 'D MMM ' + ((match[2].length > 10) ? 'YYYY ' : 'YY ');
timeFormat = 'HH:mm' + (match[4] ? ':ss' : '');
// TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
if (match[1]) { // day of week given
var momentDate = new Date(match[2]);
var momentDay = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][momentDate.getDay()];
if (match[1].substr(0,3) !== momentDay) {
getParsingFlags(config).weekdayMismatch = true;
config._isValid = false;
return;
}
}
switch (match[5].length) {
case 2: // military
if (timezoneIndex === 0) {
timezone = ' +0000';
} else {
timezoneIndex = military.indexOf(match[5][1].toUpperCase()) - 12;
timezone = ((timezoneIndex < 0) ? ' -' : ' +') +
(('' + timezoneIndex).replace(/^-?/, '0')).match(/..$/)[0] + '00';
}
break;
case 4: // Zone
timezone = timezones[match[5]];
break;
default: // UT or +/-9999
timezone = timezones[' GMT'];
}
match[5] = timezone;
config._i = match.splice(1).join('');
tzFormat = ' ZZ';
config._f = dayFormat + dateFormat + timeFormat + tzFormat;
configFromStringAndFormat(config);
getParsingFlags(config).rfc2822 = true;
} else {
config._isValid = false;
}
} | javascript | function configFromRFC2822(config) {
var string, match, dayFormat,
dateFormat, timeFormat, tzFormat;
var timezones = {
' GMT': ' +0000',
' EDT': ' -0400',
' EST': ' -0500',
' CDT': ' -0500',
' CST': ' -0600',
' MDT': ' -0600',
' MST': ' -0700',
' PDT': ' -0700',
' PST': ' -0800'
};
var military = 'YXWVUTSRQPONZABCDEFGHIKLM';
var timezone, timezoneIndex;
string = config._i
.replace(/\([^\)]*\)|[\n\t]/g, ' ') // Remove comments and folding whitespace
.replace(/(\s\s+)/g, ' ') // Replace multiple-spaces with a single space
.replace(/^\s|\s$/g, ''); // Remove leading and trailing spaces
match = basicRfcRegex.exec(string);
if (match) {
dayFormat = match[1] ? 'ddd' + ((match[1].length === 5) ? ', ' : ' ') : '';
dateFormat = 'D MMM ' + ((match[2].length > 10) ? 'YYYY ' : 'YY ');
timeFormat = 'HH:mm' + (match[4] ? ':ss' : '');
// TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
if (match[1]) { // day of week given
var momentDate = new Date(match[2]);
var momentDay = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][momentDate.getDay()];
if (match[1].substr(0,3) !== momentDay) {
getParsingFlags(config).weekdayMismatch = true;
config._isValid = false;
return;
}
}
switch (match[5].length) {
case 2: // military
if (timezoneIndex === 0) {
timezone = ' +0000';
} else {
timezoneIndex = military.indexOf(match[5][1].toUpperCase()) - 12;
timezone = ((timezoneIndex < 0) ? ' -' : ' +') +
(('' + timezoneIndex).replace(/^-?/, '0')).match(/..$/)[0] + '00';
}
break;
case 4: // Zone
timezone = timezones[match[5]];
break;
default: // UT or +/-9999
timezone = timezones[' GMT'];
}
match[5] = timezone;
config._i = match.splice(1).join('');
tzFormat = ' ZZ';
config._f = dayFormat + dateFormat + timeFormat + tzFormat;
configFromStringAndFormat(config);
getParsingFlags(config).rfc2822 = true;
} else {
config._isValid = false;
}
} | [
"function",
"configFromRFC2822",
"(",
"config",
")",
"{",
"var",
"string",
",",
"match",
",",
"dayFormat",
",",
"dateFormat",
",",
"timeFormat",
",",
"tzFormat",
";",
"var",
"timezones",
"=",
"{",
"' GMT'",
":",
"' +0000'",
",",
"' EDT'",
":",
"' -0400'",
",",
"' EST'",
":",
"' -0500'",
",",
"' CDT'",
":",
"' -0500'",
",",
"' CST'",
":",
"' -0600'",
",",
"' MDT'",
":",
"' -0600'",
",",
"' MST'",
":",
"' -0700'",
",",
"' PDT'",
":",
"' -0700'",
",",
"' PST'",
":",
"' -0800'",
"}",
";",
"var",
"military",
"=",
"'YXWVUTSRQPONZABCDEFGHIKLM'",
";",
"var",
"timezone",
",",
"timezoneIndex",
";",
"string",
"=",
"config",
".",
"_i",
".",
"replace",
"(",
"/",
"\\([^\\)]*\\)|[\\n\\t]",
"/",
"g",
",",
"' '",
")",
".",
"replace",
"(",
"/",
"(\\s\\s+)",
"/",
"g",
",",
"' '",
")",
".",
"replace",
"(",
"/",
"^\\s|\\s$",
"/",
"g",
",",
"''",
")",
";",
"match",
"=",
"basicRfcRegex",
".",
"exec",
"(",
"string",
")",
";",
"if",
"(",
"match",
")",
"{",
"dayFormat",
"=",
"match",
"[",
"1",
"]",
"?",
"'ddd'",
"+",
"(",
"(",
"match",
"[",
"1",
"]",
".",
"length",
"===",
"5",
")",
"?",
"', '",
":",
"' '",
")",
":",
"''",
";",
"dateFormat",
"=",
"'D MMM '",
"+",
"(",
"(",
"match",
"[",
"2",
"]",
".",
"length",
">",
"10",
")",
"?",
"'YYYY '",
":",
"'YY '",
")",
";",
"timeFormat",
"=",
"'HH:mm'",
"+",
"(",
"match",
"[",
"4",
"]",
"?",
"':ss'",
":",
"''",
")",
";",
"if",
"(",
"match",
"[",
"1",
"]",
")",
"{",
"var",
"momentDate",
"=",
"new",
"Date",
"(",
"match",
"[",
"2",
"]",
")",
";",
"var",
"momentDay",
"=",
"[",
"'Sun'",
",",
"'Mon'",
",",
"'Tue'",
",",
"'Wed'",
",",
"'Thu'",
",",
"'Fri'",
",",
"'Sat'",
"]",
"[",
"momentDate",
".",
"getDay",
"(",
")",
"]",
";",
"if",
"(",
"match",
"[",
"1",
"]",
".",
"substr",
"(",
"0",
",",
"3",
")",
"!==",
"momentDay",
")",
"{",
"getParsingFlags",
"(",
"config",
")",
".",
"weekdayMismatch",
"=",
"true",
";",
"config",
".",
"_isValid",
"=",
"false",
";",
"return",
";",
"}",
"}",
"switch",
"(",
"match",
"[",
"5",
"]",
".",
"length",
")",
"{",
"case",
"2",
":",
"if",
"(",
"timezoneIndex",
"===",
"0",
")",
"{",
"timezone",
"=",
"' +0000'",
";",
"}",
"else",
"{",
"timezoneIndex",
"=",
"military",
".",
"indexOf",
"(",
"match",
"[",
"5",
"]",
"[",
"1",
"]",
".",
"toUpperCase",
"(",
")",
")",
"-",
"12",
";",
"timezone",
"=",
"(",
"(",
"timezoneIndex",
"<",
"0",
")",
"?",
"' -'",
":",
"' +'",
")",
"+",
"(",
"(",
"''",
"+",
"timezoneIndex",
")",
".",
"replace",
"(",
"/",
"^-?",
"/",
",",
"'0'",
")",
")",
".",
"match",
"(",
"/",
"..$",
"/",
")",
"[",
"0",
"]",
"+",
"'00'",
";",
"}",
"break",
";",
"case",
"4",
":",
"timezone",
"=",
"timezones",
"[",
"match",
"[",
"5",
"]",
"]",
";",
"break",
";",
"default",
":",
"timezone",
"=",
"timezones",
"[",
"' GMT'",
"]",
";",
"}",
"match",
"[",
"5",
"]",
"=",
"timezone",
";",
"config",
".",
"_i",
"=",
"match",
".",
"splice",
"(",
"1",
")",
".",
"join",
"(",
"''",
")",
";",
"tzFormat",
"=",
"' ZZ'",
";",
"config",
".",
"_f",
"=",
"dayFormat",
"+",
"dateFormat",
"+",
"timeFormat",
"+",
"tzFormat",
";",
"configFromStringAndFormat",
"(",
"config",
")",
";",
"getParsingFlags",
"(",
"config",
")",
".",
"rfc2822",
"=",
"true",
";",
"}",
"else",
"{",
"config",
".",
"_isValid",
"=",
"false",
";",
"}",
"}"
] | date and time from ref 2822 format | [
"date",
"and",
"time",
"from",
"ref",
"2822",
"format"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L2482-L2547 | train |
duniter/duniter-ui | public/libraries.js | matchDetails | function matchDetails(m, isSearch) {
var id, regexp, segment, type, cfg, arrayMode;
id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null
cfg = config.params[id];
segment = pattern.substring(last, m.index);
regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);
if (regexp) {
type = $$UMFP.type(regexp) || inherit($$UMFP.type("string"), { pattern: new RegExp(regexp, config.caseInsensitive ? 'i' : undefined) });
}
return {
id: id, regexp: regexp, segment: segment, type: type, cfg: cfg
};
} | javascript | function matchDetails(m, isSearch) {
var id, regexp, segment, type, cfg, arrayMode;
id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null
cfg = config.params[id];
segment = pattern.substring(last, m.index);
regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);
if (regexp) {
type = $$UMFP.type(regexp) || inherit($$UMFP.type("string"), { pattern: new RegExp(regexp, config.caseInsensitive ? 'i' : undefined) });
}
return {
id: id, regexp: regexp, segment: segment, type: type, cfg: cfg
};
} | [
"function",
"matchDetails",
"(",
"m",
",",
"isSearch",
")",
"{",
"var",
"id",
",",
"regexp",
",",
"segment",
",",
"type",
",",
"cfg",
",",
"arrayMode",
";",
"id",
"=",
"m",
"[",
"2",
"]",
"||",
"m",
"[",
"3",
"]",
";",
"cfg",
"=",
"config",
".",
"params",
"[",
"id",
"]",
";",
"segment",
"=",
"pattern",
".",
"substring",
"(",
"last",
",",
"m",
".",
"index",
")",
";",
"regexp",
"=",
"isSearch",
"?",
"m",
"[",
"4",
"]",
":",
"m",
"[",
"4",
"]",
"||",
"(",
"m",
"[",
"1",
"]",
"==",
"'*'",
"?",
"'.*'",
":",
"null",
")",
";",
"if",
"(",
"regexp",
")",
"{",
"type",
"=",
"$$UMFP",
".",
"type",
"(",
"regexp",
")",
"||",
"inherit",
"(",
"$$UMFP",
".",
"type",
"(",
"\"string\"",
")",
",",
"{",
"pattern",
":",
"new",
"RegExp",
"(",
"regexp",
",",
"config",
".",
"caseInsensitive",
"?",
"'i'",
":",
"undefined",
")",
"}",
")",
";",
"}",
"return",
"{",
"id",
":",
"id",
",",
"regexp",
":",
"regexp",
",",
"segment",
":",
"segment",
",",
"type",
":",
"type",
",",
"cfg",
":",
"cfg",
"}",
";",
"}"
] | Split into static segments separated by path parameter placeholders. The number of segments is always 1 more than the number of parameters. | [
"Split",
"into",
"static",
"segments",
"separated",
"by",
"path",
"parameter",
"placeholders",
".",
"The",
"number",
"of",
"segments",
"is",
"always",
"1",
"more",
"than",
"the",
"number",
"of",
"parameters",
"."
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L32234-L32248 | train |
duniter/duniter-ui | public/libraries.js | update | function update() {
for (var i = 0; i < states.length; i++) {
if (anyMatch(states[i].state, states[i].params)) {
addClass($element, activeClasses[states[i].hash]);
} else {
removeClass($element, activeClasses[states[i].hash]);
}
if (exactMatch(states[i].state, states[i].params)) {
addClass($element, activeEqClass);
} else {
removeClass($element, activeEqClass);
}
}
} | javascript | function update() {
for (var i = 0; i < states.length; i++) {
if (anyMatch(states[i].state, states[i].params)) {
addClass($element, activeClasses[states[i].hash]);
} else {
removeClass($element, activeClasses[states[i].hash]);
}
if (exactMatch(states[i].state, states[i].params)) {
addClass($element, activeEqClass);
} else {
removeClass($element, activeEqClass);
}
}
} | [
"function",
"update",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"states",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"anyMatch",
"(",
"states",
"[",
"i",
"]",
".",
"state",
",",
"states",
"[",
"i",
"]",
".",
"params",
")",
")",
"{",
"addClass",
"(",
"$element",
",",
"activeClasses",
"[",
"states",
"[",
"i",
"]",
".",
"hash",
"]",
")",
";",
"}",
"else",
"{",
"removeClass",
"(",
"$element",
",",
"activeClasses",
"[",
"states",
"[",
"i",
"]",
".",
"hash",
"]",
")",
";",
"}",
"if",
"(",
"exactMatch",
"(",
"states",
"[",
"i",
"]",
".",
"state",
",",
"states",
"[",
"i",
"]",
".",
"params",
")",
")",
"{",
"addClass",
"(",
"$element",
",",
"activeEqClass",
")",
";",
"}",
"else",
"{",
"removeClass",
"(",
"$element",
",",
"activeEqClass",
")",
";",
"}",
"}",
"}"
] | Update route state | [
"Update",
"route",
"state"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L35912-L35926 | train |
duniter/duniter-ui | public/libraries.js | extendClass | function extendClass(parent, members) {
var object = function () { return UNDEFINED; };
object.prototype = new parent();
extend(object.prototype, members);
return object;
} | javascript | function extendClass(parent, members) {
var object = function () { return UNDEFINED; };
object.prototype = new parent();
extend(object.prototype, members);
return object;
} | [
"function",
"extendClass",
"(",
"parent",
",",
"members",
")",
"{",
"var",
"object",
"=",
"function",
"(",
")",
"{",
"return",
"UNDEFINED",
";",
"}",
";",
"object",
".",
"prototype",
"=",
"new",
"parent",
"(",
")",
";",
"extend",
"(",
"object",
".",
"prototype",
",",
"members",
")",
";",
"return",
"object",
";",
"}"
] | Extend a prototyped class by new members
@param {Object} parent
@param {Object} members | [
"Extend",
"a",
"prototyped",
"class",
"by",
"new",
"members"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L52189-L52194 | train |
duniter/duniter-ui | public/libraries.js | numberFormat | function numberFormat(number, decimals, decPoint, thousandsSep) {
var externalFn = Highcharts.numberFormat,
lang = defaultOptions.lang,
// http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
n = +number || 0,
c = decimals === -1 ?
(n.toString().split('.')[1] || '').length : // preserve decimals
(isNaN(decimals = mathAbs(decimals)) ? 2 : decimals),
d = decPoint === undefined ? lang.decimalPoint : decPoint,
t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep,
s = n < 0 ? "-" : "",
i = String(pInt(n = mathAbs(n).toFixed(c))),
j = i.length > 3 ? i.length % 3 : 0;
return externalFn !== numberFormat ?
externalFn(number, decimals, decPoint, thousandsSep) :
(s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
(c ? d + mathAbs(n - i).toFixed(c).slice(2) : ""));
} | javascript | function numberFormat(number, decimals, decPoint, thousandsSep) {
var externalFn = Highcharts.numberFormat,
lang = defaultOptions.lang,
// http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
n = +number || 0,
c = decimals === -1 ?
(n.toString().split('.')[1] || '').length : // preserve decimals
(isNaN(decimals = mathAbs(decimals)) ? 2 : decimals),
d = decPoint === undefined ? lang.decimalPoint : decPoint,
t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep,
s = n < 0 ? "-" : "",
i = String(pInt(n = mathAbs(n).toFixed(c))),
j = i.length > 3 ? i.length % 3 : 0;
return externalFn !== numberFormat ?
externalFn(number, decimals, decPoint, thousandsSep) :
(s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
(c ? d + mathAbs(n - i).toFixed(c).slice(2) : ""));
} | [
"function",
"numberFormat",
"(",
"number",
",",
"decimals",
",",
"decPoint",
",",
"thousandsSep",
")",
"{",
"var",
"externalFn",
"=",
"Highcharts",
".",
"numberFormat",
",",
"lang",
"=",
"defaultOptions",
".",
"lang",
",",
"n",
"=",
"+",
"number",
"||",
"0",
",",
"c",
"=",
"decimals",
"===",
"-",
"1",
"?",
"(",
"n",
".",
"toString",
"(",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
"]",
"||",
"''",
")",
".",
"length",
":",
"(",
"isNaN",
"(",
"decimals",
"=",
"mathAbs",
"(",
"decimals",
")",
")",
"?",
"2",
":",
"decimals",
")",
",",
"d",
"=",
"decPoint",
"===",
"undefined",
"?",
"lang",
".",
"decimalPoint",
":",
"decPoint",
",",
"t",
"=",
"thousandsSep",
"===",
"undefined",
"?",
"lang",
".",
"thousandsSep",
":",
"thousandsSep",
",",
"s",
"=",
"n",
"<",
"0",
"?",
"\"-\"",
":",
"\"\"",
",",
"i",
"=",
"String",
"(",
"pInt",
"(",
"n",
"=",
"mathAbs",
"(",
"n",
")",
".",
"toFixed",
"(",
"c",
")",
")",
")",
",",
"j",
"=",
"i",
".",
"length",
">",
"3",
"?",
"i",
".",
"length",
"%",
"3",
":",
"0",
";",
"return",
"externalFn",
"!==",
"numberFormat",
"?",
"externalFn",
"(",
"number",
",",
"decimals",
",",
"decPoint",
",",
"thousandsSep",
")",
":",
"(",
"s",
"+",
"(",
"j",
"?",
"i",
".",
"substr",
"(",
"0",
",",
"j",
")",
"+",
"t",
":",
"\"\"",
")",
"+",
"i",
".",
"substr",
"(",
"j",
")",
".",
"replace",
"(",
"/",
"(\\d{3})(?=\\d)",
"/",
"g",
",",
"\"$1\"",
"+",
"t",
")",
"+",
"(",
"c",
"?",
"d",
"+",
"mathAbs",
"(",
"n",
"-",
"i",
")",
".",
"toFixed",
"(",
"c",
")",
".",
"slice",
"(",
"2",
")",
":",
"\"\"",
")",
")",
";",
"}"
] | Format a number and return a string based on input settings
@param {Number} number The input number to format
@param {Number} decimals The amount of decimals
@param {String} decPoint The decimal point, defaults to the one given in the lang options
@param {String} thousandsSep The thousands separator, defaults to the one given in the lang options | [
"Format",
"a",
"number",
"and",
"return",
"a",
"string",
"based",
"on",
"input",
"settings"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L52203-L52221 | train |
duniter/duniter-ui | public/libraries.js | formatSingle | function formatSingle(format, val) {
var floatRegex = /f$/,
decRegex = /\.([0-9])/,
lang = defaultOptions.lang,
decimals;
if (floatRegex.test(format)) { // float
decimals = format.match(decRegex);
decimals = decimals ? decimals[1] : -1;
if (val !== null) {
val = numberFormat(
val,
decimals,
lang.decimalPoint,
format.indexOf(',') > -1 ? lang.thousandsSep : ''
);
}
} else {
val = dateFormat(format, val);
}
return val;
} | javascript | function formatSingle(format, val) {
var floatRegex = /f$/,
decRegex = /\.([0-9])/,
lang = defaultOptions.lang,
decimals;
if (floatRegex.test(format)) { // float
decimals = format.match(decRegex);
decimals = decimals ? decimals[1] : -1;
if (val !== null) {
val = numberFormat(
val,
decimals,
lang.decimalPoint,
format.indexOf(',') > -1 ? lang.thousandsSep : ''
);
}
} else {
val = dateFormat(format, val);
}
return val;
} | [
"function",
"formatSingle",
"(",
"format",
",",
"val",
")",
"{",
"var",
"floatRegex",
"=",
"/",
"f$",
"/",
",",
"decRegex",
"=",
"/",
"\\.([0-9])",
"/",
",",
"lang",
"=",
"defaultOptions",
".",
"lang",
",",
"decimals",
";",
"if",
"(",
"floatRegex",
".",
"test",
"(",
"format",
")",
")",
"{",
"decimals",
"=",
"format",
".",
"match",
"(",
"decRegex",
")",
";",
"decimals",
"=",
"decimals",
"?",
"decimals",
"[",
"1",
"]",
":",
"-",
"1",
";",
"if",
"(",
"val",
"!==",
"null",
")",
"{",
"val",
"=",
"numberFormat",
"(",
"val",
",",
"decimals",
",",
"lang",
".",
"decimalPoint",
",",
"format",
".",
"indexOf",
"(",
"','",
")",
">",
"-",
"1",
"?",
"lang",
".",
"thousandsSep",
":",
"''",
")",
";",
"}",
"}",
"else",
"{",
"val",
"=",
"dateFormat",
"(",
"format",
",",
"val",
")",
";",
"}",
"return",
"val",
";",
"}"
] | Format a single variable. Similar to sprintf, without the % prefix. | [
"Format",
"a",
"single",
"variable",
".",
"Similar",
"to",
"sprintf",
"without",
"the",
"%",
"prefix",
"."
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L52320-L52341 | train |
duniter/duniter-ui | public/libraries.js | function (prop, setter) {
// jQuery 1.8 style
if ($.Tween) {
$.Tween.propHooks[prop] = {
set: setter
};
// pre 1.8
} else {
$.fx.step[prop] = setter;
}
} | javascript | function (prop, setter) {
// jQuery 1.8 style
if ($.Tween) {
$.Tween.propHooks[prop] = {
set: setter
};
// pre 1.8
} else {
$.fx.step[prop] = setter;
}
} | [
"function",
"(",
"prop",
",",
"setter",
")",
"{",
"if",
"(",
"$",
".",
"Tween",
")",
"{",
"$",
".",
"Tween",
".",
"propHooks",
"[",
"prop",
"]",
"=",
"{",
"set",
":",
"setter",
"}",
";",
"}",
"else",
"{",
"$",
".",
"fx",
".",
"step",
"[",
"prop",
"]",
"=",
"setter",
";",
"}",
"}"
] | Add an animation setter for a specific property | [
"Add",
"an",
"animation",
"setter",
"for",
"a",
"specific",
"property"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L52835-L52845 | train |
|
duniter/duniter-ui | public/libraries.js | function (inherit) {
// IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881)
if (inherit && this.element.namespaceURI === SVG_NS) {
this.element.removeAttribute('visibility');
} else {
this.attr({ visibility: inherit ? 'inherit' : VISIBLE });
}
return this;
} | javascript | function (inherit) {
// IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881)
if (inherit && this.element.namespaceURI === SVG_NS) {
this.element.removeAttribute('visibility');
} else {
this.attr({ visibility: inherit ? 'inherit' : VISIBLE });
}
return this;
} | [
"function",
"(",
"inherit",
")",
"{",
"if",
"(",
"inherit",
"&&",
"this",
".",
"element",
".",
"namespaceURI",
"===",
"SVG_NS",
")",
"{",
"this",
".",
"element",
".",
"removeAttribute",
"(",
"'visibility'",
")",
";",
"}",
"else",
"{",
"this",
".",
"attr",
"(",
"{",
"visibility",
":",
"inherit",
"?",
"'inherit'",
":",
"VISIBLE",
"}",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Show the element | [
"Show",
"the",
"element"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L54276-L54284 | train |
|
duniter/duniter-ui | public/libraries.js | function (parent) {
var renderer = this.renderer,
parentWrapper = parent || renderer,
parentNode = parentWrapper.element || renderer.box,
childNodes,
element = this.element,
zIndex = this.zIndex,
otherElement,
otherZIndex,
i,
inserted;
if (parent) {
this.parentGroup = parent;
}
// mark as inverted
this.parentInverted = parent && parent.inverted;
// build formatted text
if (this.textStr !== undefined) {
renderer.buildText(this);
}
// mark the container as having z indexed children
if (zIndex) {
parentWrapper.handleZ = true;
zIndex = pInt(zIndex);
}
// insert according to this and other elements' zIndex
if (parentWrapper.handleZ) { // this element or any of its siblings has a z index
childNodes = parentNode.childNodes;
for (i = 0; i < childNodes.length; i++) {
otherElement = childNodes[i];
otherZIndex = attr(otherElement, 'zIndex');
if (otherElement !== element && (
// insert before the first element with a higher zIndex
pInt(otherZIndex) > zIndex ||
// if no zIndex given, insert before the first element with a zIndex
(!defined(zIndex) && defined(otherZIndex))
)) {
parentNode.insertBefore(element, otherElement);
inserted = true;
break;
}
}
}
// default: append at the end
if (!inserted) {
parentNode.appendChild(element);
}
// mark as added
this.added = true;
// fire an event for internal hooks
if (this.onAdd) {
this.onAdd();
}
return this;
} | javascript | function (parent) {
var renderer = this.renderer,
parentWrapper = parent || renderer,
parentNode = parentWrapper.element || renderer.box,
childNodes,
element = this.element,
zIndex = this.zIndex,
otherElement,
otherZIndex,
i,
inserted;
if (parent) {
this.parentGroup = parent;
}
// mark as inverted
this.parentInverted = parent && parent.inverted;
// build formatted text
if (this.textStr !== undefined) {
renderer.buildText(this);
}
// mark the container as having z indexed children
if (zIndex) {
parentWrapper.handleZ = true;
zIndex = pInt(zIndex);
}
// insert according to this and other elements' zIndex
if (parentWrapper.handleZ) { // this element or any of its siblings has a z index
childNodes = parentNode.childNodes;
for (i = 0; i < childNodes.length; i++) {
otherElement = childNodes[i];
otherZIndex = attr(otherElement, 'zIndex');
if (otherElement !== element && (
// insert before the first element with a higher zIndex
pInt(otherZIndex) > zIndex ||
// if no zIndex given, insert before the first element with a zIndex
(!defined(zIndex) && defined(otherZIndex))
)) {
parentNode.insertBefore(element, otherElement);
inserted = true;
break;
}
}
}
// default: append at the end
if (!inserted) {
parentNode.appendChild(element);
}
// mark as added
this.added = true;
// fire an event for internal hooks
if (this.onAdd) {
this.onAdd();
}
return this;
} | [
"function",
"(",
"parent",
")",
"{",
"var",
"renderer",
"=",
"this",
".",
"renderer",
",",
"parentWrapper",
"=",
"parent",
"||",
"renderer",
",",
"parentNode",
"=",
"parentWrapper",
".",
"element",
"||",
"renderer",
".",
"box",
",",
"childNodes",
",",
"element",
"=",
"this",
".",
"element",
",",
"zIndex",
"=",
"this",
".",
"zIndex",
",",
"otherElement",
",",
"otherZIndex",
",",
"i",
",",
"inserted",
";",
"if",
"(",
"parent",
")",
"{",
"this",
".",
"parentGroup",
"=",
"parent",
";",
"}",
"this",
".",
"parentInverted",
"=",
"parent",
"&&",
"parent",
".",
"inverted",
";",
"if",
"(",
"this",
".",
"textStr",
"!==",
"undefined",
")",
"{",
"renderer",
".",
"buildText",
"(",
"this",
")",
";",
"}",
"if",
"(",
"zIndex",
")",
"{",
"parentWrapper",
".",
"handleZ",
"=",
"true",
";",
"zIndex",
"=",
"pInt",
"(",
"zIndex",
")",
";",
"}",
"if",
"(",
"parentWrapper",
".",
"handleZ",
")",
"{",
"childNodes",
"=",
"parentNode",
".",
"childNodes",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"childNodes",
".",
"length",
";",
"i",
"++",
")",
"{",
"otherElement",
"=",
"childNodes",
"[",
"i",
"]",
";",
"otherZIndex",
"=",
"attr",
"(",
"otherElement",
",",
"'zIndex'",
")",
";",
"if",
"(",
"otherElement",
"!==",
"element",
"&&",
"(",
"pInt",
"(",
"otherZIndex",
")",
">",
"zIndex",
"||",
"(",
"!",
"defined",
"(",
"zIndex",
")",
"&&",
"defined",
"(",
"otherZIndex",
")",
")",
")",
")",
"{",
"parentNode",
".",
"insertBefore",
"(",
"element",
",",
"otherElement",
")",
";",
"inserted",
"=",
"true",
";",
"break",
";",
"}",
"}",
"}",
"if",
"(",
"!",
"inserted",
")",
"{",
"parentNode",
".",
"appendChild",
"(",
"element",
")",
";",
"}",
"this",
".",
"added",
"=",
"true",
";",
"if",
"(",
"this",
".",
"onAdd",
")",
"{",
"this",
".",
"onAdd",
"(",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Add the element
@param {Object|Undefined} parent Can be an element, an element wrapper or undefined
to append the element to the renderer.box. | [
"Add",
"the",
"element"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L54310-L54375 | train |
|
duniter/duniter-ui | public/libraries.js | function (key) {
var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0);
if (/^[\-0-9\.]+$/.test(ret)) { // is numerical
ret = parseFloat(ret);
}
return ret;
} | javascript | function (key) {
var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0);
if (/^[\-0-9\.]+$/.test(ret)) { // is numerical
ret = parseFloat(ret);
}
return ret;
} | [
"function",
"(",
"key",
")",
"{",
"var",
"ret",
"=",
"pick",
"(",
"this",
"[",
"key",
"]",
",",
"this",
".",
"element",
"?",
"this",
".",
"element",
".",
"getAttribute",
"(",
"key",
")",
":",
"null",
",",
"0",
")",
";",
"if",
"(",
"/",
"^[\\-0-9\\.]+$",
"/",
".",
"test",
"(",
"ret",
")",
")",
"{",
"ret",
"=",
"parseFloat",
"(",
"ret",
")",
";",
"}",
"return",
"ret",
";",
"}"
] | Get the current value of an attribute or pseudo attribute, used mainly
for animation. | [
"Get",
"the",
"current",
"value",
"of",
"an",
"attribute",
"or",
"pseudo",
"attribute",
"used",
"mainly",
"for",
"animation",
"."
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L54511-L54518 | train |
|
duniter/duniter-ui | public/libraries.js | function (x, y, w, h, options) {
var arrowLength = 6,
halfDistance = 6,
r = mathMin((options && options.r) || 0, w, h),
safeDistance = r + halfDistance,
anchorX = options && options.anchorX,
anchorY = options && options.anchorY,
path,
normalizer = mathRound(options.strokeWidth || 0) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors;
x += normalizer;
y += normalizer;
path = [
'M', x + r, y,
'L', x + w - r, y, // top side
'C', x + w, y, x + w, y, x + w, y + r, // top-right corner
'L', x + w, y + h - r, // right side
'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner
'L', x + r, y + h, // bottom side
'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner
'L', x, y + r, // left side
'C', x, y, x, y, x + r, y // top-right corner
];
if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side
path.splice(13, 3,
'L', x + w, anchorY - halfDistance,
x + w + arrowLength, anchorY,
x + w, anchorY + halfDistance,
x + w, y + h - r
);
} else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side
path.splice(33, 3,
'L', x, anchorY + halfDistance,
x - arrowLength, anchorY,
x, anchorY - halfDistance,
x, y + r
);
} else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom
path.splice(23, 3,
'L', anchorX + halfDistance, y + h,
anchorX, y + h + arrowLength,
anchorX - halfDistance, y + h,
x + r, y + h
);
} else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top
path.splice(3, 3,
'L', anchorX - halfDistance, y,
anchorX, y - arrowLength,
anchorX + halfDistance, y,
w - r, y
);
}
return path;
} | javascript | function (x, y, w, h, options) {
var arrowLength = 6,
halfDistance = 6,
r = mathMin((options && options.r) || 0, w, h),
safeDistance = r + halfDistance,
anchorX = options && options.anchorX,
anchorY = options && options.anchorY,
path,
normalizer = mathRound(options.strokeWidth || 0) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors;
x += normalizer;
y += normalizer;
path = [
'M', x + r, y,
'L', x + w - r, y, // top side
'C', x + w, y, x + w, y, x + w, y + r, // top-right corner
'L', x + w, y + h - r, // right side
'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner
'L', x + r, y + h, // bottom side
'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner
'L', x, y + r, // left side
'C', x, y, x, y, x + r, y // top-right corner
];
if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side
path.splice(13, 3,
'L', x + w, anchorY - halfDistance,
x + w + arrowLength, anchorY,
x + w, anchorY + halfDistance,
x + w, y + h - r
);
} else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side
path.splice(33, 3,
'L', x, anchorY + halfDistance,
x - arrowLength, anchorY,
x, anchorY - halfDistance,
x, y + r
);
} else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom
path.splice(23, 3,
'L', anchorX + halfDistance, y + h,
anchorX, y + h + arrowLength,
anchorX - halfDistance, y + h,
x + r, y + h
);
} else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top
path.splice(3, 3,
'L', anchorX - halfDistance, y,
anchorX, y - arrowLength,
anchorX + halfDistance, y,
w - r, y
);
}
return path;
} | [
"function",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"options",
")",
"{",
"var",
"arrowLength",
"=",
"6",
",",
"halfDistance",
"=",
"6",
",",
"r",
"=",
"mathMin",
"(",
"(",
"options",
"&&",
"options",
".",
"r",
")",
"||",
"0",
",",
"w",
",",
"h",
")",
",",
"safeDistance",
"=",
"r",
"+",
"halfDistance",
",",
"anchorX",
"=",
"options",
"&&",
"options",
".",
"anchorX",
",",
"anchorY",
"=",
"options",
"&&",
"options",
".",
"anchorY",
",",
"path",
",",
"normalizer",
"=",
"mathRound",
"(",
"options",
".",
"strokeWidth",
"||",
"0",
")",
"%",
"2",
"/",
"2",
";",
"x",
"+=",
"normalizer",
";",
"y",
"+=",
"normalizer",
";",
"path",
"=",
"[",
"'M'",
",",
"x",
"+",
"r",
",",
"y",
",",
"'L'",
",",
"x",
"+",
"w",
"-",
"r",
",",
"y",
",",
"'C'",
",",
"x",
"+",
"w",
",",
"y",
",",
"x",
"+",
"w",
",",
"y",
",",
"x",
"+",
"w",
",",
"y",
"+",
"r",
",",
"'L'",
",",
"x",
"+",
"w",
",",
"y",
"+",
"h",
"-",
"r",
",",
"'C'",
",",
"x",
"+",
"w",
",",
"y",
"+",
"h",
",",
"x",
"+",
"w",
",",
"y",
"+",
"h",
",",
"x",
"+",
"w",
"-",
"r",
",",
"y",
"+",
"h",
",",
"'L'",
",",
"x",
"+",
"r",
",",
"y",
"+",
"h",
",",
"'C'",
",",
"x",
",",
"y",
"+",
"h",
",",
"x",
",",
"y",
"+",
"h",
",",
"x",
",",
"y",
"+",
"h",
"-",
"r",
",",
"'L'",
",",
"x",
",",
"y",
"+",
"r",
",",
"'C'",
",",
"x",
",",
"y",
",",
"x",
",",
"y",
",",
"x",
"+",
"r",
",",
"y",
"]",
";",
"if",
"(",
"anchorX",
"&&",
"anchorX",
">",
"w",
"&&",
"anchorY",
">",
"y",
"+",
"safeDistance",
"&&",
"anchorY",
"<",
"y",
"+",
"h",
"-",
"safeDistance",
")",
"{",
"path",
".",
"splice",
"(",
"13",
",",
"3",
",",
"'L'",
",",
"x",
"+",
"w",
",",
"anchorY",
"-",
"halfDistance",
",",
"x",
"+",
"w",
"+",
"arrowLength",
",",
"anchorY",
",",
"x",
"+",
"w",
",",
"anchorY",
"+",
"halfDistance",
",",
"x",
"+",
"w",
",",
"y",
"+",
"h",
"-",
"r",
")",
";",
"}",
"else",
"if",
"(",
"anchorX",
"&&",
"anchorX",
"<",
"0",
"&&",
"anchorY",
">",
"y",
"+",
"safeDistance",
"&&",
"anchorY",
"<",
"y",
"+",
"h",
"-",
"safeDistance",
")",
"{",
"path",
".",
"splice",
"(",
"33",
",",
"3",
",",
"'L'",
",",
"x",
",",
"anchorY",
"+",
"halfDistance",
",",
"x",
"-",
"arrowLength",
",",
"anchorY",
",",
"x",
",",
"anchorY",
"-",
"halfDistance",
",",
"x",
",",
"y",
"+",
"r",
")",
";",
"}",
"else",
"if",
"(",
"anchorY",
"&&",
"anchorY",
">",
"h",
"&&",
"anchorX",
">",
"x",
"+",
"safeDistance",
"&&",
"anchorX",
"<",
"x",
"+",
"w",
"-",
"safeDistance",
")",
"{",
"path",
".",
"splice",
"(",
"23",
",",
"3",
",",
"'L'",
",",
"anchorX",
"+",
"halfDistance",
",",
"y",
"+",
"h",
",",
"anchorX",
",",
"y",
"+",
"h",
"+",
"arrowLength",
",",
"anchorX",
"-",
"halfDistance",
",",
"y",
"+",
"h",
",",
"x",
"+",
"r",
",",
"y",
"+",
"h",
")",
";",
"}",
"else",
"if",
"(",
"anchorY",
"&&",
"anchorY",
"<",
"0",
"&&",
"anchorX",
">",
"x",
"+",
"safeDistance",
"&&",
"anchorX",
"<",
"x",
"+",
"w",
"-",
"safeDistance",
")",
"{",
"path",
".",
"splice",
"(",
"3",
",",
"3",
",",
"'L'",
",",
"anchorX",
"-",
"halfDistance",
",",
"y",
",",
"anchorX",
",",
"y",
"-",
"arrowLength",
",",
"anchorX",
"+",
"halfDistance",
",",
"y",
",",
"w",
"-",
"r",
",",
"y",
")",
";",
"}",
"return",
"path",
";",
"}"
] | Callout shape used for default tooltips, also used for rounded rectangles in VML | [
"Callout",
"shape",
"used",
"for",
"default",
"tooltips",
"also",
"used",
"for",
"rounded",
"rectangles",
"in",
"VML"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L55487-L55541 | train |
|
duniter/duniter-ui | public/libraries.js | function () {
// Added by button implementation
removeEvent(wrapper.element, 'mouseenter');
removeEvent(wrapper.element, 'mouseleave');
if (text) {
text = text.destroy();
}
if (box) {
box = box.destroy();
}
// Call base implementation to destroy the rest
SVGElement.prototype.destroy.call(wrapper);
// Release local pointers (#1298)
wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null;
} | javascript | function () {
// Added by button implementation
removeEvent(wrapper.element, 'mouseenter');
removeEvent(wrapper.element, 'mouseleave');
if (text) {
text = text.destroy();
}
if (box) {
box = box.destroy();
}
// Call base implementation to destroy the rest
SVGElement.prototype.destroy.call(wrapper);
// Release local pointers (#1298)
wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null;
} | [
"function",
"(",
")",
"{",
"removeEvent",
"(",
"wrapper",
".",
"element",
",",
"'mouseenter'",
")",
";",
"removeEvent",
"(",
"wrapper",
".",
"element",
",",
"'mouseleave'",
")",
";",
"if",
"(",
"text",
")",
"{",
"text",
"=",
"text",
".",
"destroy",
"(",
")",
";",
"}",
"if",
"(",
"box",
")",
"{",
"box",
"=",
"box",
".",
"destroy",
"(",
")",
";",
"}",
"SVGElement",
".",
"prototype",
".",
"destroy",
".",
"call",
"(",
"wrapper",
")",
";",
"wrapper",
"=",
"renderer",
"=",
"updateBoxSize",
"=",
"updateTextPadding",
"=",
"boxAttr",
"=",
"null",
";",
"}"
] | Destroy and release memory. | [
"Destroy",
"and",
"release",
"memory",
"."
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L55913-L55930 | train |
|
duniter/duniter-ui | public/libraries.js | function (width, baseline, alignCorrection, rotation, align) {
var costheta = rotation ? mathCos(rotation * deg2rad) : 1,
sintheta = rotation ? mathSin(rotation * deg2rad) : 0,
height = pick(this.elemHeight, this.element.offsetHeight),
quad,
nonLeft = align && align !== 'left';
// correct x and y
this.xCorr = costheta < 0 && -width;
this.yCorr = sintheta < 0 && -height;
// correct for baseline and corners spilling out after rotation
quad = costheta * sintheta < 0;
this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection);
this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1);
// correct for the length/height of the text
if (nonLeft) {
this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1);
if (rotation) {
this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1);
}
css(this.element, {
textAlign: align
});
}
} | javascript | function (width, baseline, alignCorrection, rotation, align) {
var costheta = rotation ? mathCos(rotation * deg2rad) : 1,
sintheta = rotation ? mathSin(rotation * deg2rad) : 0,
height = pick(this.elemHeight, this.element.offsetHeight),
quad,
nonLeft = align && align !== 'left';
// correct x and y
this.xCorr = costheta < 0 && -width;
this.yCorr = sintheta < 0 && -height;
// correct for baseline and corners spilling out after rotation
quad = costheta * sintheta < 0;
this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection);
this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1);
// correct for the length/height of the text
if (nonLeft) {
this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1);
if (rotation) {
this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1);
}
css(this.element, {
textAlign: align
});
}
} | [
"function",
"(",
"width",
",",
"baseline",
",",
"alignCorrection",
",",
"rotation",
",",
"align",
")",
"{",
"var",
"costheta",
"=",
"rotation",
"?",
"mathCos",
"(",
"rotation",
"*",
"deg2rad",
")",
":",
"1",
",",
"sintheta",
"=",
"rotation",
"?",
"mathSin",
"(",
"rotation",
"*",
"deg2rad",
")",
":",
"0",
",",
"height",
"=",
"pick",
"(",
"this",
".",
"elemHeight",
",",
"this",
".",
"element",
".",
"offsetHeight",
")",
",",
"quad",
",",
"nonLeft",
"=",
"align",
"&&",
"align",
"!==",
"'left'",
";",
"this",
".",
"xCorr",
"=",
"costheta",
"<",
"0",
"&&",
"-",
"width",
";",
"this",
".",
"yCorr",
"=",
"sintheta",
"<",
"0",
"&&",
"-",
"height",
";",
"quad",
"=",
"costheta",
"*",
"sintheta",
"<",
"0",
";",
"this",
".",
"xCorr",
"+=",
"sintheta",
"*",
"baseline",
"*",
"(",
"quad",
"?",
"1",
"-",
"alignCorrection",
":",
"alignCorrection",
")",
";",
"this",
".",
"yCorr",
"-=",
"costheta",
"*",
"baseline",
"*",
"(",
"rotation",
"?",
"(",
"quad",
"?",
"alignCorrection",
":",
"1",
"-",
"alignCorrection",
")",
":",
"1",
")",
";",
"if",
"(",
"nonLeft",
")",
"{",
"this",
".",
"xCorr",
"-=",
"width",
"*",
"alignCorrection",
"*",
"(",
"costheta",
"<",
"0",
"?",
"-",
"1",
":",
"1",
")",
";",
"if",
"(",
"rotation",
")",
"{",
"this",
".",
"yCorr",
"-=",
"height",
"*",
"alignCorrection",
"*",
"(",
"sintheta",
"<",
"0",
"?",
"-",
"1",
":",
"1",
")",
";",
"}",
"css",
"(",
"this",
".",
"element",
",",
"{",
"textAlign",
":",
"align",
"}",
")",
";",
"}",
"}"
] | Get the positioning correction for the span after rotating. | [
"Get",
"the",
"positioning",
"correction",
"for",
"the",
"span",
"after",
"rotating",
"."
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L56354-L56380 | train |
|
duniter/duniter-ui | public/libraries.js | function (key, value) {
if (docMode8) { // IE8 setAttribute bug
this.element[key] = value;
} else {
this.element.setAttribute(key, value);
}
} | javascript | function (key, value) {
if (docMode8) { // IE8 setAttribute bug
this.element[key] = value;
} else {
this.element.setAttribute(key, value);
}
} | [
"function",
"(",
"key",
",",
"value",
")",
"{",
"if",
"(",
"docMode8",
")",
"{",
"this",
".",
"element",
"[",
"key",
"]",
"=",
"value",
";",
"}",
"else",
"{",
"this",
".",
"element",
".",
"setAttribute",
"(",
"key",
",",
"value",
")",
";",
"}",
"}"
] | Used in SVG only | [
"Used",
"in",
"SVG",
"only"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L56596-L56602 | train |
|
duniter/duniter-ui | public/libraries.js | function (value, key, element) {
var style = element.style;
this[key] = style[key] = value; // style is for #1873
// Correction for the 1x1 size of the shape container. Used in gauge needles.
style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX;
style.top = mathRound(mathCos(value * deg2rad)) + PX;
} | javascript | function (value, key, element) {
var style = element.style;
this[key] = style[key] = value; // style is for #1873
// Correction for the 1x1 size of the shape container. Used in gauge needles.
style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX;
style.top = mathRound(mathCos(value * deg2rad)) + PX;
} | [
"function",
"(",
"value",
",",
"key",
",",
"element",
")",
"{",
"var",
"style",
"=",
"element",
".",
"style",
";",
"this",
"[",
"key",
"]",
"=",
"style",
"[",
"key",
"]",
"=",
"value",
";",
"style",
".",
"left",
"=",
"-",
"mathRound",
"(",
"mathSin",
"(",
"value",
"*",
"deg2rad",
")",
"+",
"1",
")",
"+",
"PX",
";",
"style",
".",
"top",
"=",
"mathRound",
"(",
"mathCos",
"(",
"value",
"*",
"deg2rad",
")",
")",
"+",
"PX",
";",
"}"
] | Don't bother - animation is too slow and filters introduce artifacts | [
"Don",
"t",
"bother",
"-",
"animation",
"is",
"too",
"slow",
"and",
"filters",
"introduce",
"artifacts"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L56641-L56648 | train |
|
duniter/duniter-ui | public/libraries.js | function (x, y, w, h, options) {
return SVGRenderer.prototype.symbols[
!defined(options) || !options.r ? 'square' : 'callout'
].call(0, x, y, w, h, options);
} | javascript | function (x, y, w, h, options) {
return SVGRenderer.prototype.symbols[
!defined(options) || !options.r ? 'square' : 'callout'
].call(0, x, y, w, h, options);
} | [
"function",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"options",
")",
"{",
"return",
"SVGRenderer",
".",
"prototype",
".",
"symbols",
"[",
"!",
"defined",
"(",
"options",
")",
"||",
"!",
"options",
".",
"r",
"?",
"'square'",
":",
"'callout'",
"]",
".",
"call",
"(",
"0",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"options",
")",
";",
"}"
] | Add rectangle symbol path which eases rotation and omits arcsize problems
compared to the built-in VML roundrect shape. When borders are not rounded,
use the simpler square path, else use the callout path without the arrow. | [
"Add",
"rectangle",
"symbol",
"path",
"which",
"eases",
"rotation",
"and",
"omits",
"arcsize",
"problems",
"compared",
"to",
"the",
"built",
"-",
"in",
"VML",
"roundrect",
"shape",
".",
"When",
"borders",
"are",
"not",
"rounded",
"use",
"the",
"simpler",
"square",
"path",
"else",
"use",
"the",
"callout",
"path",
"without",
"the",
"arrow",
"."
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L57265-L57269 | train |
|
duniter/duniter-ui | public/libraries.js | function () {
var axis = this.axis,
value = this.value,
categories = axis.categories,
dateTimeLabelFormat = this.dateTimeLabelFormat,
numericSymbols = defaultOptions.lang.numericSymbols,
i = numericSymbols && numericSymbols.length,
multi,
ret,
formatOption = axis.options.labels.format,
// make sure the same symbol is added for all labels on a linear axis
numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
if (formatOption) {
ret = format(formatOption, this);
} else if (categories) {
ret = value;
} else if (dateTimeLabelFormat) { // datetime axis
ret = dateFormat(dateTimeLabelFormat, value);
} else if (i && numericSymbolDetector >= 1000) {
// Decide whether we should add a numeric symbol like k (thousands) or M (millions).
// If we are to enable this in tooltip or other places as well, we can move this
// logic to the numberFormatter and enable it by a parameter.
while (i-- && ret === UNDEFINED) {
multi = Math.pow(1000, i + 1);
if (numericSymbolDetector >= multi && numericSymbols[i] !== null) {
ret = numberFormat(value / multi, -1) + numericSymbols[i];
}
}
}
if (ret === UNDEFINED) {
if (mathAbs(value) >= 10000) { // add thousands separators
ret = numberFormat(value, 0);
} else { // small numbers
ret = numberFormat(value, -1, UNDEFINED, ''); // #2466
}
}
return ret;
} | javascript | function () {
var axis = this.axis,
value = this.value,
categories = axis.categories,
dateTimeLabelFormat = this.dateTimeLabelFormat,
numericSymbols = defaultOptions.lang.numericSymbols,
i = numericSymbols && numericSymbols.length,
multi,
ret,
formatOption = axis.options.labels.format,
// make sure the same symbol is added for all labels on a linear axis
numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
if (formatOption) {
ret = format(formatOption, this);
} else if (categories) {
ret = value;
} else if (dateTimeLabelFormat) { // datetime axis
ret = dateFormat(dateTimeLabelFormat, value);
} else if (i && numericSymbolDetector >= 1000) {
// Decide whether we should add a numeric symbol like k (thousands) or M (millions).
// If we are to enable this in tooltip or other places as well, we can move this
// logic to the numberFormatter and enable it by a parameter.
while (i-- && ret === UNDEFINED) {
multi = Math.pow(1000, i + 1);
if (numericSymbolDetector >= multi && numericSymbols[i] !== null) {
ret = numberFormat(value / multi, -1) + numericSymbols[i];
}
}
}
if (ret === UNDEFINED) {
if (mathAbs(value) >= 10000) { // add thousands separators
ret = numberFormat(value, 0);
} else { // small numbers
ret = numberFormat(value, -1, UNDEFINED, ''); // #2466
}
}
return ret;
} | [
"function",
"(",
")",
"{",
"var",
"axis",
"=",
"this",
".",
"axis",
",",
"value",
"=",
"this",
".",
"value",
",",
"categories",
"=",
"axis",
".",
"categories",
",",
"dateTimeLabelFormat",
"=",
"this",
".",
"dateTimeLabelFormat",
",",
"numericSymbols",
"=",
"defaultOptions",
".",
"lang",
".",
"numericSymbols",
",",
"i",
"=",
"numericSymbols",
"&&",
"numericSymbols",
".",
"length",
",",
"multi",
",",
"ret",
",",
"formatOption",
"=",
"axis",
".",
"options",
".",
"labels",
".",
"format",
",",
"numericSymbolDetector",
"=",
"axis",
".",
"isLog",
"?",
"value",
":",
"axis",
".",
"tickInterval",
";",
"if",
"(",
"formatOption",
")",
"{",
"ret",
"=",
"format",
"(",
"formatOption",
",",
"this",
")",
";",
"}",
"else",
"if",
"(",
"categories",
")",
"{",
"ret",
"=",
"value",
";",
"}",
"else",
"if",
"(",
"dateTimeLabelFormat",
")",
"{",
"ret",
"=",
"dateFormat",
"(",
"dateTimeLabelFormat",
",",
"value",
")",
";",
"}",
"else",
"if",
"(",
"i",
"&&",
"numericSymbolDetector",
">=",
"1000",
")",
"{",
"while",
"(",
"i",
"--",
"&&",
"ret",
"===",
"UNDEFINED",
")",
"{",
"multi",
"=",
"Math",
".",
"pow",
"(",
"1000",
",",
"i",
"+",
"1",
")",
";",
"if",
"(",
"numericSymbolDetector",
">=",
"multi",
"&&",
"numericSymbols",
"[",
"i",
"]",
"!==",
"null",
")",
"{",
"ret",
"=",
"numberFormat",
"(",
"value",
"/",
"multi",
",",
"-",
"1",
")",
"+",
"numericSymbols",
"[",
"i",
"]",
";",
"}",
"}",
"}",
"if",
"(",
"ret",
"===",
"UNDEFINED",
")",
"{",
"if",
"(",
"mathAbs",
"(",
"value",
")",
">=",
"10000",
")",
"{",
"ret",
"=",
"numberFormat",
"(",
"value",
",",
"0",
")",
";",
"}",
"else",
"{",
"ret",
"=",
"numberFormat",
"(",
"value",
",",
"-",
"1",
",",
"UNDEFINED",
",",
"''",
")",
";",
"}",
"}",
"return",
"ret",
";",
"}"
] | The default label formatter. The context is a special config object for the label. | [
"The",
"default",
"label",
"formatter",
".",
"The",
"context",
"is",
"a",
"special",
"config",
"object",
"for",
"the",
"label",
"."
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L58429-L58474 | train |
|
duniter/duniter-ui | public/libraries.js | function (val, backwards, cvsCoord, old, handleLog, pointPlacement) {
var axis = this,
sign = 1,
cvsOffset = 0,
localA = old ? axis.oldTransA : axis.transA,
localMin = old ? axis.oldMin : axis.min,
returnValue,
minPixelPadding = axis.minPixelPadding,
postTranslate = (axis.options.ordinal || (axis.isLog && handleLog)) && axis.lin2val;
if (!localA) {
localA = axis.transA;
}
// In vertical axes, the canvas coordinates start from 0 at the top like in
// SVG.
if (cvsCoord) {
sign *= -1; // canvas coordinates inverts the value
cvsOffset = axis.len;
}
// Handle reversed axis
if (axis.reversed) {
sign *= -1;
cvsOffset -= sign * (axis.sector || axis.len);
}
// From pixels to value
if (backwards) { // reverse translation
val = val * sign + cvsOffset;
val -= minPixelPadding;
returnValue = val / localA + localMin; // from chart pixel to value
if (postTranslate) { // log and ordinal axes
returnValue = axis.lin2val(returnValue);
}
// From value to pixels
} else {
if (postTranslate) { // log and ordinal axes
val = axis.val2lin(val);
}
if (pointPlacement === 'between') {
pointPlacement = 0.5;
}
returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) +
(isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0);
}
return returnValue;
} | javascript | function (val, backwards, cvsCoord, old, handleLog, pointPlacement) {
var axis = this,
sign = 1,
cvsOffset = 0,
localA = old ? axis.oldTransA : axis.transA,
localMin = old ? axis.oldMin : axis.min,
returnValue,
minPixelPadding = axis.minPixelPadding,
postTranslate = (axis.options.ordinal || (axis.isLog && handleLog)) && axis.lin2val;
if (!localA) {
localA = axis.transA;
}
// In vertical axes, the canvas coordinates start from 0 at the top like in
// SVG.
if (cvsCoord) {
sign *= -1; // canvas coordinates inverts the value
cvsOffset = axis.len;
}
// Handle reversed axis
if (axis.reversed) {
sign *= -1;
cvsOffset -= sign * (axis.sector || axis.len);
}
// From pixels to value
if (backwards) { // reverse translation
val = val * sign + cvsOffset;
val -= minPixelPadding;
returnValue = val / localA + localMin; // from chart pixel to value
if (postTranslate) { // log and ordinal axes
returnValue = axis.lin2val(returnValue);
}
// From value to pixels
} else {
if (postTranslate) { // log and ordinal axes
val = axis.val2lin(val);
}
if (pointPlacement === 'between') {
pointPlacement = 0.5;
}
returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) +
(isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0);
}
return returnValue;
} | [
"function",
"(",
"val",
",",
"backwards",
",",
"cvsCoord",
",",
"old",
",",
"handleLog",
",",
"pointPlacement",
")",
"{",
"var",
"axis",
"=",
"this",
",",
"sign",
"=",
"1",
",",
"cvsOffset",
"=",
"0",
",",
"localA",
"=",
"old",
"?",
"axis",
".",
"oldTransA",
":",
"axis",
".",
"transA",
",",
"localMin",
"=",
"old",
"?",
"axis",
".",
"oldMin",
":",
"axis",
".",
"min",
",",
"returnValue",
",",
"minPixelPadding",
"=",
"axis",
".",
"minPixelPadding",
",",
"postTranslate",
"=",
"(",
"axis",
".",
"options",
".",
"ordinal",
"||",
"(",
"axis",
".",
"isLog",
"&&",
"handleLog",
")",
")",
"&&",
"axis",
".",
"lin2val",
";",
"if",
"(",
"!",
"localA",
")",
"{",
"localA",
"=",
"axis",
".",
"transA",
";",
"}",
"if",
"(",
"cvsCoord",
")",
"{",
"sign",
"*=",
"-",
"1",
";",
"cvsOffset",
"=",
"axis",
".",
"len",
";",
"}",
"if",
"(",
"axis",
".",
"reversed",
")",
"{",
"sign",
"*=",
"-",
"1",
";",
"cvsOffset",
"-=",
"sign",
"*",
"(",
"axis",
".",
"sector",
"||",
"axis",
".",
"len",
")",
";",
"}",
"if",
"(",
"backwards",
")",
"{",
"val",
"=",
"val",
"*",
"sign",
"+",
"cvsOffset",
";",
"val",
"-=",
"minPixelPadding",
";",
"returnValue",
"=",
"val",
"/",
"localA",
"+",
"localMin",
";",
"if",
"(",
"postTranslate",
")",
"{",
"returnValue",
"=",
"axis",
".",
"lin2val",
"(",
"returnValue",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"postTranslate",
")",
"{",
"val",
"=",
"axis",
".",
"val2lin",
"(",
"val",
")",
";",
"}",
"if",
"(",
"pointPlacement",
"===",
"'between'",
")",
"{",
"pointPlacement",
"=",
"0.5",
";",
"}",
"returnValue",
"=",
"sign",
"*",
"(",
"val",
"-",
"localMin",
")",
"*",
"localA",
"+",
"cvsOffset",
"+",
"(",
"sign",
"*",
"minPixelPadding",
")",
"+",
"(",
"isNumber",
"(",
"pointPlacement",
")",
"?",
"localA",
"*",
"pointPlacement",
"*",
"axis",
".",
"pointRange",
":",
"0",
")",
";",
"}",
"return",
"returnValue",
";",
"}"
] | Translate from axis value to pixel position on the chart, or back | [
"Translate",
"from",
"axis",
"value",
"to",
"pixel",
"position",
"on",
"the",
"chart",
"or",
"back"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L58553-L58603 | train |
|
duniter/duniter-ui | public/libraries.js | function (value, lineWidth, old, force, translatedValue) {
var axis = this,
chart = axis.chart,
axisLeft = axis.left,
axisTop = axis.top,
x1,
y1,
x2,
y2,
cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
skip,
transB = axis.transB;
translatedValue = pick(translatedValue, axis.translate(value, null, null, old));
x1 = x2 = mathRound(translatedValue + transB);
y1 = y2 = mathRound(cHeight - translatedValue - transB);
if (isNaN(translatedValue)) { // no min or max
skip = true;
} else if (axis.horiz) {
y1 = axisTop;
y2 = cHeight - axis.bottom;
if (x1 < axisLeft || x1 > axisLeft + axis.width) {
skip = true;
}
} else {
x1 = axisLeft;
x2 = cWidth - axis.right;
if (y1 < axisTop || y1 > axisTop + axis.height) {
skip = true;
}
}
return skip && !force ?
null :
chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1);
} | javascript | function (value, lineWidth, old, force, translatedValue) {
var axis = this,
chart = axis.chart,
axisLeft = axis.left,
axisTop = axis.top,
x1,
y1,
x2,
y2,
cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
skip,
transB = axis.transB;
translatedValue = pick(translatedValue, axis.translate(value, null, null, old));
x1 = x2 = mathRound(translatedValue + transB);
y1 = y2 = mathRound(cHeight - translatedValue - transB);
if (isNaN(translatedValue)) { // no min or max
skip = true;
} else if (axis.horiz) {
y1 = axisTop;
y2 = cHeight - axis.bottom;
if (x1 < axisLeft || x1 > axisLeft + axis.width) {
skip = true;
}
} else {
x1 = axisLeft;
x2 = cWidth - axis.right;
if (y1 < axisTop || y1 > axisTop + axis.height) {
skip = true;
}
}
return skip && !force ?
null :
chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1);
} | [
"function",
"(",
"value",
",",
"lineWidth",
",",
"old",
",",
"force",
",",
"translatedValue",
")",
"{",
"var",
"axis",
"=",
"this",
",",
"chart",
"=",
"axis",
".",
"chart",
",",
"axisLeft",
"=",
"axis",
".",
"left",
",",
"axisTop",
"=",
"axis",
".",
"top",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"cHeight",
"=",
"(",
"old",
"&&",
"chart",
".",
"oldChartHeight",
")",
"||",
"chart",
".",
"chartHeight",
",",
"cWidth",
"=",
"(",
"old",
"&&",
"chart",
".",
"oldChartWidth",
")",
"||",
"chart",
".",
"chartWidth",
",",
"skip",
",",
"transB",
"=",
"axis",
".",
"transB",
";",
"translatedValue",
"=",
"pick",
"(",
"translatedValue",
",",
"axis",
".",
"translate",
"(",
"value",
",",
"null",
",",
"null",
",",
"old",
")",
")",
";",
"x1",
"=",
"x2",
"=",
"mathRound",
"(",
"translatedValue",
"+",
"transB",
")",
";",
"y1",
"=",
"y2",
"=",
"mathRound",
"(",
"cHeight",
"-",
"translatedValue",
"-",
"transB",
")",
";",
"if",
"(",
"isNaN",
"(",
"translatedValue",
")",
")",
"{",
"skip",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"axis",
".",
"horiz",
")",
"{",
"y1",
"=",
"axisTop",
";",
"y2",
"=",
"cHeight",
"-",
"axis",
".",
"bottom",
";",
"if",
"(",
"x1",
"<",
"axisLeft",
"||",
"x1",
">",
"axisLeft",
"+",
"axis",
".",
"width",
")",
"{",
"skip",
"=",
"true",
";",
"}",
"}",
"else",
"{",
"x1",
"=",
"axisLeft",
";",
"x2",
"=",
"cWidth",
"-",
"axis",
".",
"right",
";",
"if",
"(",
"y1",
"<",
"axisTop",
"||",
"y1",
">",
"axisTop",
"+",
"axis",
".",
"height",
")",
"{",
"skip",
"=",
"true",
";",
"}",
"}",
"return",
"skip",
"&&",
"!",
"force",
"?",
"null",
":",
"chart",
".",
"renderer",
".",
"crispLine",
"(",
"[",
"M",
",",
"x1",
",",
"y1",
",",
"L",
",",
"x2",
",",
"y2",
"]",
",",
"lineWidth",
"||",
"1",
")",
";",
"}"
] | Create the path for a plot line that goes from the given value on
this axis, across the plot to the opposite side
@param {Number} value
@param {Number} lineWidth Used for calculation crisp line
@param {Number] old Use old coordinates (for resizing and rescaling) | [
"Create",
"the",
"path",
"for",
"a",
"plot",
"line",
"that",
"goes",
"from",
"the",
"given",
"value",
"on",
"this",
"axis",
"across",
"the",
"plot",
"to",
"the",
"opposite",
"side"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L58632-L58670 | train |
|
duniter/duniter-ui | public/libraries.js | function () {
var chart = this.chart,
maxTicks = chart.maxTicks || {},
tickPositions = this.tickPositions,
key = this._maxTicksKey = [this.coll, this.pos, this.len].join('-');
if (!this.isLinked && !this.isDatetimeAxis && tickPositions && tickPositions.length > (maxTicks[key] || 0) && this.options.alignTicks !== false) {
maxTicks[key] = tickPositions.length;
}
chart.maxTicks = maxTicks;
} | javascript | function () {
var chart = this.chart,
maxTicks = chart.maxTicks || {},
tickPositions = this.tickPositions,
key = this._maxTicksKey = [this.coll, this.pos, this.len].join('-');
if (!this.isLinked && !this.isDatetimeAxis && tickPositions && tickPositions.length > (maxTicks[key] || 0) && this.options.alignTicks !== false) {
maxTicks[key] = tickPositions.length;
}
chart.maxTicks = maxTicks;
} | [
"function",
"(",
")",
"{",
"var",
"chart",
"=",
"this",
".",
"chart",
",",
"maxTicks",
"=",
"chart",
".",
"maxTicks",
"||",
"{",
"}",
",",
"tickPositions",
"=",
"this",
".",
"tickPositions",
",",
"key",
"=",
"this",
".",
"_maxTicksKey",
"=",
"[",
"this",
".",
"coll",
",",
"this",
".",
"pos",
",",
"this",
".",
"len",
"]",
".",
"join",
"(",
"'-'",
")",
";",
"if",
"(",
"!",
"this",
".",
"isLinked",
"&&",
"!",
"this",
".",
"isDatetimeAxis",
"&&",
"tickPositions",
"&&",
"tickPositions",
".",
"length",
">",
"(",
"maxTicks",
"[",
"key",
"]",
"||",
"0",
")",
"&&",
"this",
".",
"options",
".",
"alignTicks",
"!==",
"false",
")",
"{",
"maxTicks",
"[",
"key",
"]",
"=",
"tickPositions",
".",
"length",
";",
"}",
"chart",
".",
"maxTicks",
"=",
"maxTicks",
";",
"}"
] | Set the max ticks of either the x and y axis collection | [
"Set",
"the",
"max",
"ticks",
"of",
"either",
"the",
"x",
"and",
"y",
"axis",
"collection"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L59136-L59147 | train |
|
duniter/duniter-ui | public/libraries.js | function (e, point) {
if (!this.crosshair) { return; }// Do not draw crosshairs if you don't have too.
if ((defined(point) || !pick(this.crosshair.snap, true)) === false) {
this.hideCrosshair();
return;
}
var path,
options = this.crosshair,
animation = options.animation,
pos;
// Get the path
if (!pick(options.snap, true)) {
pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos);
} else if (defined(point)) {
/*jslint eqeq: true*/
pos = (this.chart.inverted != this.horiz) ? point.plotX : this.len - point.plotY;
/*jslint eqeq: false*/
}
if (this.isRadial) {
path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y));
} else {
path = this.getPlotLinePath(null, null, null, null, pos);
}
if (path === null) {
this.hideCrosshair();
return;
}
// Draw the cross
if (this.cross) {
this.cross
.attr({ visibility: VISIBLE })[animation ? 'animate' : 'attr']({ d: path }, animation);
} else {
var attribs = {
'stroke-width': options.width || 1,
stroke: options.color || '#C0C0C0',
zIndex: options.zIndex || 2
};
if (options.dashStyle) {
attribs.dashstyle = options.dashStyle;
}
this.cross = this.chart.renderer.path(path).attr(attribs).add();
}
} | javascript | function (e, point) {
if (!this.crosshair) { return; }// Do not draw crosshairs if you don't have too.
if ((defined(point) || !pick(this.crosshair.snap, true)) === false) {
this.hideCrosshair();
return;
}
var path,
options = this.crosshair,
animation = options.animation,
pos;
// Get the path
if (!pick(options.snap, true)) {
pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos);
} else if (defined(point)) {
/*jslint eqeq: true*/
pos = (this.chart.inverted != this.horiz) ? point.plotX : this.len - point.plotY;
/*jslint eqeq: false*/
}
if (this.isRadial) {
path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y));
} else {
path = this.getPlotLinePath(null, null, null, null, pos);
}
if (path === null) {
this.hideCrosshair();
return;
}
// Draw the cross
if (this.cross) {
this.cross
.attr({ visibility: VISIBLE })[animation ? 'animate' : 'attr']({ d: path }, animation);
} else {
var attribs = {
'stroke-width': options.width || 1,
stroke: options.color || '#C0C0C0',
zIndex: options.zIndex || 2
};
if (options.dashStyle) {
attribs.dashstyle = options.dashStyle;
}
this.cross = this.chart.renderer.path(path).attr(attribs).add();
}
} | [
"function",
"(",
"e",
",",
"point",
")",
"{",
"if",
"(",
"!",
"this",
".",
"crosshair",
")",
"{",
"return",
";",
"}",
"if",
"(",
"(",
"defined",
"(",
"point",
")",
"||",
"!",
"pick",
"(",
"this",
".",
"crosshair",
".",
"snap",
",",
"true",
")",
")",
"===",
"false",
")",
"{",
"this",
".",
"hideCrosshair",
"(",
")",
";",
"return",
";",
"}",
"var",
"path",
",",
"options",
"=",
"this",
".",
"crosshair",
",",
"animation",
"=",
"options",
".",
"animation",
",",
"pos",
";",
"if",
"(",
"!",
"pick",
"(",
"options",
".",
"snap",
",",
"true",
")",
")",
"{",
"pos",
"=",
"(",
"this",
".",
"horiz",
"?",
"e",
".",
"chartX",
"-",
"this",
".",
"pos",
":",
"this",
".",
"len",
"-",
"e",
".",
"chartY",
"+",
"this",
".",
"pos",
")",
";",
"}",
"else",
"if",
"(",
"defined",
"(",
"point",
")",
")",
"{",
"pos",
"=",
"(",
"this",
".",
"chart",
".",
"inverted",
"!=",
"this",
".",
"horiz",
")",
"?",
"point",
".",
"plotX",
":",
"this",
".",
"len",
"-",
"point",
".",
"plotY",
";",
"}",
"if",
"(",
"this",
".",
"isRadial",
")",
"{",
"path",
"=",
"this",
".",
"getPlotLinePath",
"(",
"this",
".",
"isXAxis",
"?",
"point",
".",
"x",
":",
"pick",
"(",
"point",
".",
"stackY",
",",
"point",
".",
"y",
")",
")",
";",
"}",
"else",
"{",
"path",
"=",
"this",
".",
"getPlotLinePath",
"(",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"pos",
")",
";",
"}",
"if",
"(",
"path",
"===",
"null",
")",
"{",
"this",
".",
"hideCrosshair",
"(",
")",
";",
"return",
";",
"}",
"if",
"(",
"this",
".",
"cross",
")",
"{",
"this",
".",
"cross",
".",
"attr",
"(",
"{",
"visibility",
":",
"VISIBLE",
"}",
")",
"[",
"animation",
"?",
"'animate'",
":",
"'attr'",
"]",
"(",
"{",
"d",
":",
"path",
"}",
",",
"animation",
")",
";",
"}",
"else",
"{",
"var",
"attribs",
"=",
"{",
"'stroke-width'",
":",
"options",
".",
"width",
"||",
"1",
",",
"stroke",
":",
"options",
".",
"color",
"||",
"'#C0C0C0'",
",",
"zIndex",
":",
"options",
".",
"zIndex",
"||",
"2",
"}",
";",
"if",
"(",
"options",
".",
"dashStyle",
")",
"{",
"attribs",
".",
"dashstyle",
"=",
"options",
".",
"dashStyle",
";",
"}",
"this",
".",
"cross",
"=",
"this",
".",
"chart",
".",
"renderer",
".",
"path",
"(",
"path",
")",
".",
"attr",
"(",
"attribs",
")",
".",
"add",
"(",
")",
";",
"}",
"}"
] | Draw the crosshair | [
"Draw",
"the",
"crosshair"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L59956-L60004 | train |
|
duniter/duniter-ui | public/libraries.js | function (tooltip) {
var items = this.points || splat(this),
series = items[0].series,
s;
// build the header
s = [tooltip.tooltipHeaderFormatter(items[0])];
// build the values
each(items, function (item) {
series = item.series;
s.push((series.tooltipFormatter && series.tooltipFormatter(item)) ||
item.point.tooltipFormatter(series.tooltipOptions.pointFormat));
});
// footer
s.push(tooltip.options.footerFormat || '');
return s.join('');
} | javascript | function (tooltip) {
var items = this.points || splat(this),
series = items[0].series,
s;
// build the header
s = [tooltip.tooltipHeaderFormatter(items[0])];
// build the values
each(items, function (item) {
series = item.series;
s.push((series.tooltipFormatter && series.tooltipFormatter(item)) ||
item.point.tooltipFormatter(series.tooltipOptions.pointFormat));
});
// footer
s.push(tooltip.options.footerFormat || '');
return s.join('');
} | [
"function",
"(",
"tooltip",
")",
"{",
"var",
"items",
"=",
"this",
".",
"points",
"||",
"splat",
"(",
"this",
")",
",",
"series",
"=",
"items",
"[",
"0",
"]",
".",
"series",
",",
"s",
";",
"s",
"=",
"[",
"tooltip",
".",
"tooltipHeaderFormatter",
"(",
"items",
"[",
"0",
"]",
")",
"]",
";",
"each",
"(",
"items",
",",
"function",
"(",
"item",
")",
"{",
"series",
"=",
"item",
".",
"series",
";",
"s",
".",
"push",
"(",
"(",
"series",
".",
"tooltipFormatter",
"&&",
"series",
".",
"tooltipFormatter",
"(",
"item",
")",
")",
"||",
"item",
".",
"point",
".",
"tooltipFormatter",
"(",
"series",
".",
"tooltipOptions",
".",
"pointFormat",
")",
")",
";",
"}",
")",
";",
"s",
".",
"push",
"(",
"tooltip",
".",
"options",
".",
"footerFormat",
"||",
"''",
")",
";",
"return",
"s",
".",
"join",
"(",
"''",
")",
";",
"}"
] | In case no user defined formatter is given, this will be used. Note that the context
here is an object holding point, series, x, y etc. | [
"In",
"case",
"no",
"user",
"defined",
"formatter",
"is",
"given",
"this",
"will",
"be",
"used",
".",
"Note",
"that",
"the",
"context",
"here",
"is",
"an",
"object",
"holding",
"point",
"series",
"x",
"y",
"etc",
"."
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L60603-L60622 | train |
|
duniter/duniter-ui | public/libraries.js | function (e) {
var chart = this.chart,
hasPinched = this.hasPinched;
if (this.selectionMarker) {
var selectionData = {
xAxis: [],
yAxis: [],
originalEvent: e.originalEvent || e
},
selectionBox = this.selectionMarker,
selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x,
selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y,
selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width,
selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height,
runZoom;
// a selection has been made
if (this.hasDragged || hasPinched) {
// record each axis' min and max
each(chart.axes, function (axis) {
if (axis.zoomEnabled) {
var horiz = axis.horiz,
minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding: 0, // #1207, #3075
selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding),
selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding);
if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859
selectionData[axis.coll].push({
axis: axis,
min: mathMin(selectionMin, selectionMax), // for reversed axes,
max: mathMax(selectionMin, selectionMax)
});
runZoom = true;
}
}
});
if (runZoom) {
fireEvent(chart, 'selection', selectionData, function (args) {
chart.zoom(extend(args, hasPinched ? { animation: false } : null));
});
}
}
this.selectionMarker = this.selectionMarker.destroy();
// Reset scaling preview
if (hasPinched) {
this.scaleGroups();
}
}
// Reset all
if (chart) { // it may be destroyed on mouse up - #877
css(chart.container, { cursor: chart._cursor });
chart.cancelClick = this.hasDragged > 10; // #370
chart.mouseIsDown = this.hasDragged = this.hasPinched = false;
this.pinchDown = [];
}
} | javascript | function (e) {
var chart = this.chart,
hasPinched = this.hasPinched;
if (this.selectionMarker) {
var selectionData = {
xAxis: [],
yAxis: [],
originalEvent: e.originalEvent || e
},
selectionBox = this.selectionMarker,
selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x,
selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y,
selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width,
selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height,
runZoom;
// a selection has been made
if (this.hasDragged || hasPinched) {
// record each axis' min and max
each(chart.axes, function (axis) {
if (axis.zoomEnabled) {
var horiz = axis.horiz,
minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding: 0, // #1207, #3075
selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding),
selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding);
if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859
selectionData[axis.coll].push({
axis: axis,
min: mathMin(selectionMin, selectionMax), // for reversed axes,
max: mathMax(selectionMin, selectionMax)
});
runZoom = true;
}
}
});
if (runZoom) {
fireEvent(chart, 'selection', selectionData, function (args) {
chart.zoom(extend(args, hasPinched ? { animation: false } : null));
});
}
}
this.selectionMarker = this.selectionMarker.destroy();
// Reset scaling preview
if (hasPinched) {
this.scaleGroups();
}
}
// Reset all
if (chart) { // it may be destroyed on mouse up - #877
css(chart.container, { cursor: chart._cursor });
chart.cancelClick = this.hasDragged > 10; // #370
chart.mouseIsDown = this.hasDragged = this.hasPinched = false;
this.pinchDown = [];
}
} | [
"function",
"(",
"e",
")",
"{",
"var",
"chart",
"=",
"this",
".",
"chart",
",",
"hasPinched",
"=",
"this",
".",
"hasPinched",
";",
"if",
"(",
"this",
".",
"selectionMarker",
")",
"{",
"var",
"selectionData",
"=",
"{",
"xAxis",
":",
"[",
"]",
",",
"yAxis",
":",
"[",
"]",
",",
"originalEvent",
":",
"e",
".",
"originalEvent",
"||",
"e",
"}",
",",
"selectionBox",
"=",
"this",
".",
"selectionMarker",
",",
"selectionLeft",
"=",
"selectionBox",
".",
"attr",
"?",
"selectionBox",
".",
"attr",
"(",
"'x'",
")",
":",
"selectionBox",
".",
"x",
",",
"selectionTop",
"=",
"selectionBox",
".",
"attr",
"?",
"selectionBox",
".",
"attr",
"(",
"'y'",
")",
":",
"selectionBox",
".",
"y",
",",
"selectionWidth",
"=",
"selectionBox",
".",
"attr",
"?",
"selectionBox",
".",
"attr",
"(",
"'width'",
")",
":",
"selectionBox",
".",
"width",
",",
"selectionHeight",
"=",
"selectionBox",
".",
"attr",
"?",
"selectionBox",
".",
"attr",
"(",
"'height'",
")",
":",
"selectionBox",
".",
"height",
",",
"runZoom",
";",
"if",
"(",
"this",
".",
"hasDragged",
"||",
"hasPinched",
")",
"{",
"each",
"(",
"chart",
".",
"axes",
",",
"function",
"(",
"axis",
")",
"{",
"if",
"(",
"axis",
".",
"zoomEnabled",
")",
"{",
"var",
"horiz",
"=",
"axis",
".",
"horiz",
",",
"minPixelPadding",
"=",
"e",
".",
"type",
"===",
"'touchend'",
"?",
"axis",
".",
"minPixelPadding",
":",
"0",
",",
"selectionMin",
"=",
"axis",
".",
"toValue",
"(",
"(",
"horiz",
"?",
"selectionLeft",
":",
"selectionTop",
")",
"+",
"minPixelPadding",
")",
",",
"selectionMax",
"=",
"axis",
".",
"toValue",
"(",
"(",
"horiz",
"?",
"selectionLeft",
"+",
"selectionWidth",
":",
"selectionTop",
"+",
"selectionHeight",
")",
"-",
"minPixelPadding",
")",
";",
"if",
"(",
"!",
"isNaN",
"(",
"selectionMin",
")",
"&&",
"!",
"isNaN",
"(",
"selectionMax",
")",
")",
"{",
"selectionData",
"[",
"axis",
".",
"coll",
"]",
".",
"push",
"(",
"{",
"axis",
":",
"axis",
",",
"min",
":",
"mathMin",
"(",
"selectionMin",
",",
"selectionMax",
")",
",",
"max",
":",
"mathMax",
"(",
"selectionMin",
",",
"selectionMax",
")",
"}",
")",
";",
"runZoom",
"=",
"true",
";",
"}",
"}",
"}",
")",
";",
"if",
"(",
"runZoom",
")",
"{",
"fireEvent",
"(",
"chart",
",",
"'selection'",
",",
"selectionData",
",",
"function",
"(",
"args",
")",
"{",
"chart",
".",
"zoom",
"(",
"extend",
"(",
"args",
",",
"hasPinched",
"?",
"{",
"animation",
":",
"false",
"}",
":",
"null",
")",
")",
";",
"}",
")",
";",
"}",
"}",
"this",
".",
"selectionMarker",
"=",
"this",
".",
"selectionMarker",
".",
"destroy",
"(",
")",
";",
"if",
"(",
"hasPinched",
")",
"{",
"this",
".",
"scaleGroups",
"(",
")",
";",
"}",
"}",
"if",
"(",
"chart",
")",
"{",
"css",
"(",
"chart",
".",
"container",
",",
"{",
"cursor",
":",
"chart",
".",
"_cursor",
"}",
")",
";",
"chart",
".",
"cancelClick",
"=",
"this",
".",
"hasDragged",
">",
"10",
";",
"chart",
".",
"mouseIsDown",
"=",
"this",
".",
"hasDragged",
"=",
"this",
".",
"hasPinched",
"=",
"false",
";",
"this",
".",
"pinchDown",
"=",
"[",
"]",
";",
"}",
"}"
] | On mouse up or touch end across the entire document, drop the selection. | [
"On",
"mouse",
"up",
"or",
"touch",
"end",
"across",
"the",
"entire",
"document",
"drop",
"the",
"selection",
"."
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L61198-L61258 | train |
|
duniter/duniter-ui | public/libraries.js | function () {
var chart = charts[hoverChartIndex];
if (chart) {
chart.pointer.reset();
chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix
}
} | javascript | function () {
var chart = charts[hoverChartIndex];
if (chart) {
chart.pointer.reset();
chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix
}
} | [
"function",
"(",
")",
"{",
"var",
"chart",
"=",
"charts",
"[",
"hoverChartIndex",
"]",
";",
"if",
"(",
"chart",
")",
"{",
"chart",
".",
"pointer",
".",
"reset",
"(",
")",
";",
"chart",
".",
"pointer",
".",
"chartPosition",
"=",
"null",
";",
"}",
"}"
] | When mouse leaves the container, hide the tooltip. | [
"When",
"mouse",
"leaves",
"the",
"container",
"hide",
"the",
"tooltip",
"."
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L61301-L61307 | train |
|
duniter/duniter-ui | public/libraries.js | function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
if (this.zoomHor || this.pinchHor) {
this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
if (this.zoomVert || this.pinchVert) {
this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
} | javascript | function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
if (this.zoomHor || this.pinchHor) {
this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
if (this.zoomVert || this.pinchVert) {
this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
} | [
"function",
"(",
"pinchDown",
",",
"touches",
",",
"transform",
",",
"selectionMarker",
",",
"clip",
",",
"lastValidTouch",
")",
"{",
"if",
"(",
"this",
".",
"zoomHor",
"||",
"this",
".",
"pinchHor",
")",
"{",
"this",
".",
"pinchTranslateDirection",
"(",
"true",
",",
"pinchDown",
",",
"touches",
",",
"transform",
",",
"selectionMarker",
",",
"clip",
",",
"lastValidTouch",
")",
";",
"}",
"if",
"(",
"this",
".",
"zoomVert",
"||",
"this",
".",
"pinchVert",
")",
"{",
"this",
".",
"pinchTranslateDirection",
"(",
"false",
",",
"pinchDown",
",",
"touches",
",",
"transform",
",",
"selectionMarker",
",",
"clip",
",",
"lastValidTouch",
")",
";",
"}",
"}"
] | Run translation operations | [
"Run",
"translation",
"operations"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L61464-L61471 | train |
|
duniter/duniter-ui | public/libraries.js | function (fn) {
fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown);
fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove);
fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp);
} | javascript | function (fn) {
fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown);
fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove);
fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp);
} | [
"function",
"(",
"fn",
")",
"{",
"fn",
"(",
"this",
".",
"chart",
".",
"container",
",",
"hasPointerEvent",
"?",
"'pointerdown'",
":",
"'MSPointerDown'",
",",
"this",
".",
"onContainerPointerDown",
")",
";",
"fn",
"(",
"this",
".",
"chart",
".",
"container",
",",
"hasPointerEvent",
"?",
"'pointermove'",
":",
"'MSPointerMove'",
",",
"this",
".",
"onContainerPointerMove",
")",
";",
"fn",
"(",
"doc",
",",
"hasPointerEvent",
"?",
"'pointerup'",
":",
"'MSPointerUp'",
",",
"this",
".",
"onDocumentPointerUp",
")",
";",
"}"
] | Add or remove the MS Pointer specific events | [
"Add",
"or",
"remove",
"the",
"MS",
"Pointer",
"specific",
"events"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L61732-L61736 | train |
|
duniter/duniter-ui | public/libraries.js | function (scrollOffset) {
var alignAttr = this.group.alignAttr,
translateY,
clipHeight = this.clipHeight || this.legendHeight;
if (alignAttr) {
translateY = alignAttr.translateY;
each(this.allItems, function (item) {
var checkbox = item.checkbox,
top;
if (checkbox) {
top = (translateY + checkbox.y + (scrollOffset || 0) + 3);
css(checkbox, {
left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX,
top: top + PX,
display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE
});
}
});
}
} | javascript | function (scrollOffset) {
var alignAttr = this.group.alignAttr,
translateY,
clipHeight = this.clipHeight || this.legendHeight;
if (alignAttr) {
translateY = alignAttr.translateY;
each(this.allItems, function (item) {
var checkbox = item.checkbox,
top;
if (checkbox) {
top = (translateY + checkbox.y + (scrollOffset || 0) + 3);
css(checkbox, {
left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX,
top: top + PX,
display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE
});
}
});
}
} | [
"function",
"(",
"scrollOffset",
")",
"{",
"var",
"alignAttr",
"=",
"this",
".",
"group",
".",
"alignAttr",
",",
"translateY",
",",
"clipHeight",
"=",
"this",
".",
"clipHeight",
"||",
"this",
".",
"legendHeight",
";",
"if",
"(",
"alignAttr",
")",
"{",
"translateY",
"=",
"alignAttr",
".",
"translateY",
";",
"each",
"(",
"this",
".",
"allItems",
",",
"function",
"(",
"item",
")",
"{",
"var",
"checkbox",
"=",
"item",
".",
"checkbox",
",",
"top",
";",
"if",
"(",
"checkbox",
")",
"{",
"top",
"=",
"(",
"translateY",
"+",
"checkbox",
".",
"y",
"+",
"(",
"scrollOffset",
"||",
"0",
")",
"+",
"3",
")",
";",
"css",
"(",
"checkbox",
",",
"{",
"left",
":",
"(",
"alignAttr",
".",
"translateX",
"+",
"item",
".",
"checkboxOffset",
"+",
"checkbox",
".",
"x",
"-",
"20",
")",
"+",
"PX",
",",
"top",
":",
"top",
"+",
"PX",
",",
"display",
":",
"top",
">",
"translateY",
"-",
"6",
"&&",
"top",
"<",
"translateY",
"+",
"clipHeight",
"-",
"6",
"?",
"''",
":",
"NONE",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | Position the checkboxes after the width is determined | [
"Position",
"the",
"checkboxes",
"after",
"the",
"width",
"is",
"determined"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L61922-L61943 | train |
|
duniter/duniter-ui | public/libraries.js | function () {
var allItems = [];
each(this.chart.series, function (series) {
var seriesOptions = series.options;
// Handle showInLegend. If the series is linked to another series, defaults to false.
if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) {
return;
}
// use points or series for the legend item depending on legendType
allItems = allItems.concat(
series.legendItems ||
(seriesOptions.legendType === 'point' ?
series.data :
series)
);
});
return allItems;
} | javascript | function () {
var allItems = [];
each(this.chart.series, function (series) {
var seriesOptions = series.options;
// Handle showInLegend. If the series is linked to another series, defaults to false.
if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) {
return;
}
// use points or series for the legend item depending on legendType
allItems = allItems.concat(
series.legendItems ||
(seriesOptions.legendType === 'point' ?
series.data :
series)
);
});
return allItems;
} | [
"function",
"(",
")",
"{",
"var",
"allItems",
"=",
"[",
"]",
";",
"each",
"(",
"this",
".",
"chart",
".",
"series",
",",
"function",
"(",
"series",
")",
"{",
"var",
"seriesOptions",
"=",
"series",
".",
"options",
";",
"if",
"(",
"!",
"pick",
"(",
"seriesOptions",
".",
"showInLegend",
",",
"!",
"defined",
"(",
"seriesOptions",
".",
"linkedTo",
")",
"?",
"UNDEFINED",
":",
"false",
",",
"true",
")",
")",
"{",
"return",
";",
"}",
"allItems",
"=",
"allItems",
".",
"concat",
"(",
"series",
".",
"legendItems",
"||",
"(",
"seriesOptions",
".",
"legendType",
"===",
"'point'",
"?",
"series",
".",
"data",
":",
"series",
")",
")",
";",
"}",
")",
";",
"return",
"allItems",
";",
"}"
] | Get all items, which is one item per series for normal series and one item per point
for pie series. | [
"Get",
"all",
"items",
"which",
"is",
"one",
"item",
"per",
"series",
"for",
"normal",
"series",
"and",
"one",
"item",
"per",
"point",
"for",
"pie",
"series",
"."
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L62096-L62115 | train |
|
duniter/duniter-ui | public/libraries.js | function (scrollBy, animation) {
var pages = this.pages,
pageCount = pages.length,
currentPage = this.currentPage + scrollBy,
clipHeight = this.clipHeight,
navOptions = this.options.navigation,
activeColor = navOptions.activeColor,
inactiveColor = navOptions.inactiveColor,
pager = this.pager,
padding = this.padding,
scrollOffset;
// When resizing while looking at the last page
if (currentPage > pageCount) {
currentPage = pageCount;
}
if (currentPage > 0) {
if (animation !== UNDEFINED) {
setAnimation(animation, this.chart);
}
this.nav.attr({
translateX: padding,
translateY: clipHeight + this.padding + 7 + this.titleHeight,
visibility: VISIBLE
});
this.up.attr({
fill: currentPage === 1 ? inactiveColor : activeColor
})
.css({
cursor: currentPage === 1 ? 'default' : 'pointer'
});
pager.attr({
text: currentPage + '/' + pageCount
});
this.down.attr({
x: 18 + this.pager.getBBox().width, // adjust to text width
fill: currentPage === pageCount ? inactiveColor : activeColor
})
.css({
cursor: currentPage === pageCount ? 'default' : 'pointer'
});
scrollOffset = -pages[currentPage - 1] + this.initialItemY;
this.scrollGroup.animate({
translateY: scrollOffset
});
this.currentPage = currentPage;
this.positionCheckboxes(scrollOffset);
}
} | javascript | function (scrollBy, animation) {
var pages = this.pages,
pageCount = pages.length,
currentPage = this.currentPage + scrollBy,
clipHeight = this.clipHeight,
navOptions = this.options.navigation,
activeColor = navOptions.activeColor,
inactiveColor = navOptions.inactiveColor,
pager = this.pager,
padding = this.padding,
scrollOffset;
// When resizing while looking at the last page
if (currentPage > pageCount) {
currentPage = pageCount;
}
if (currentPage > 0) {
if (animation !== UNDEFINED) {
setAnimation(animation, this.chart);
}
this.nav.attr({
translateX: padding,
translateY: clipHeight + this.padding + 7 + this.titleHeight,
visibility: VISIBLE
});
this.up.attr({
fill: currentPage === 1 ? inactiveColor : activeColor
})
.css({
cursor: currentPage === 1 ? 'default' : 'pointer'
});
pager.attr({
text: currentPage + '/' + pageCount
});
this.down.attr({
x: 18 + this.pager.getBBox().width, // adjust to text width
fill: currentPage === pageCount ? inactiveColor : activeColor
})
.css({
cursor: currentPage === pageCount ? 'default' : 'pointer'
});
scrollOffset = -pages[currentPage - 1] + this.initialItemY;
this.scrollGroup.animate({
translateY: scrollOffset
});
this.currentPage = currentPage;
this.positionCheckboxes(scrollOffset);
}
} | [
"function",
"(",
"scrollBy",
",",
"animation",
")",
"{",
"var",
"pages",
"=",
"this",
".",
"pages",
",",
"pageCount",
"=",
"pages",
".",
"length",
",",
"currentPage",
"=",
"this",
".",
"currentPage",
"+",
"scrollBy",
",",
"clipHeight",
"=",
"this",
".",
"clipHeight",
",",
"navOptions",
"=",
"this",
".",
"options",
".",
"navigation",
",",
"activeColor",
"=",
"navOptions",
".",
"activeColor",
",",
"inactiveColor",
"=",
"navOptions",
".",
"inactiveColor",
",",
"pager",
"=",
"this",
".",
"pager",
",",
"padding",
"=",
"this",
".",
"padding",
",",
"scrollOffset",
";",
"if",
"(",
"currentPage",
">",
"pageCount",
")",
"{",
"currentPage",
"=",
"pageCount",
";",
"}",
"if",
"(",
"currentPage",
">",
"0",
")",
"{",
"if",
"(",
"animation",
"!==",
"UNDEFINED",
")",
"{",
"setAnimation",
"(",
"animation",
",",
"this",
".",
"chart",
")",
";",
"}",
"this",
".",
"nav",
".",
"attr",
"(",
"{",
"translateX",
":",
"padding",
",",
"translateY",
":",
"clipHeight",
"+",
"this",
".",
"padding",
"+",
"7",
"+",
"this",
".",
"titleHeight",
",",
"visibility",
":",
"VISIBLE",
"}",
")",
";",
"this",
".",
"up",
".",
"attr",
"(",
"{",
"fill",
":",
"currentPage",
"===",
"1",
"?",
"inactiveColor",
":",
"activeColor",
"}",
")",
".",
"css",
"(",
"{",
"cursor",
":",
"currentPage",
"===",
"1",
"?",
"'default'",
":",
"'pointer'",
"}",
")",
";",
"pager",
".",
"attr",
"(",
"{",
"text",
":",
"currentPage",
"+",
"'/'",
"+",
"pageCount",
"}",
")",
";",
"this",
".",
"down",
".",
"attr",
"(",
"{",
"x",
":",
"18",
"+",
"this",
".",
"pager",
".",
"getBBox",
"(",
")",
".",
"width",
",",
"fill",
":",
"currentPage",
"===",
"pageCount",
"?",
"inactiveColor",
":",
"activeColor",
"}",
")",
".",
"css",
"(",
"{",
"cursor",
":",
"currentPage",
"===",
"pageCount",
"?",
"'default'",
":",
"'pointer'",
"}",
")",
";",
"scrollOffset",
"=",
"-",
"pages",
"[",
"currentPage",
"-",
"1",
"]",
"+",
"this",
".",
"initialItemY",
";",
"this",
".",
"scrollGroup",
".",
"animate",
"(",
"{",
"translateY",
":",
"scrollOffset",
"}",
")",
";",
"this",
".",
"currentPage",
"=",
"currentPage",
";",
"this",
".",
"positionCheckboxes",
"(",
"scrollOffset",
")",
";",
"}",
"}"
] | Scroll the legend by a number of pages
@param {Object} scrollBy
@param {Object} animation | [
"Scroll",
"the",
"legend",
"by",
"a",
"number",
"of",
"pages"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L62358-L62413 | train |
|
duniter/duniter-ui | public/libraries.js | function (titleOptions, subtitleOptions, redraw) {
var chart = this,
options = chart.options,
chartTitleOptions,
chartSubtitleOptions;
chartTitleOptions = options.title = merge(options.title, titleOptions);
chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
// add title and subtitle
each([
['title', titleOptions, chartTitleOptions],
['subtitle', subtitleOptions, chartSubtitleOptions]
], function (arr) {
var name = arr[0],
title = chart[name],
titleOptions = arr[1],
chartTitleOptions = arr[2];
if (title && titleOptions) {
chart[name] = title = title.destroy(); // remove old
}
if (chartTitleOptions && chartTitleOptions.text && !title) {
chart[name] = chart.renderer.text(
chartTitleOptions.text,
0,
0,
chartTitleOptions.useHTML
)
.attr({
align: chartTitleOptions.align,
'class': PREFIX + name,
zIndex: chartTitleOptions.zIndex || 4
})
.css(chartTitleOptions.style)
.add();
}
});
chart.layOutTitles(redraw);
} | javascript | function (titleOptions, subtitleOptions, redraw) {
var chart = this,
options = chart.options,
chartTitleOptions,
chartSubtitleOptions;
chartTitleOptions = options.title = merge(options.title, titleOptions);
chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
// add title and subtitle
each([
['title', titleOptions, chartTitleOptions],
['subtitle', subtitleOptions, chartSubtitleOptions]
], function (arr) {
var name = arr[0],
title = chart[name],
titleOptions = arr[1],
chartTitleOptions = arr[2];
if (title && titleOptions) {
chart[name] = title = title.destroy(); // remove old
}
if (chartTitleOptions && chartTitleOptions.text && !title) {
chart[name] = chart.renderer.text(
chartTitleOptions.text,
0,
0,
chartTitleOptions.useHTML
)
.attr({
align: chartTitleOptions.align,
'class': PREFIX + name,
zIndex: chartTitleOptions.zIndex || 4
})
.css(chartTitleOptions.style)
.add();
}
});
chart.layOutTitles(redraw);
} | [
"function",
"(",
"titleOptions",
",",
"subtitleOptions",
",",
"redraw",
")",
"{",
"var",
"chart",
"=",
"this",
",",
"options",
"=",
"chart",
".",
"options",
",",
"chartTitleOptions",
",",
"chartSubtitleOptions",
";",
"chartTitleOptions",
"=",
"options",
".",
"title",
"=",
"merge",
"(",
"options",
".",
"title",
",",
"titleOptions",
")",
";",
"chartSubtitleOptions",
"=",
"options",
".",
"subtitle",
"=",
"merge",
"(",
"options",
".",
"subtitle",
",",
"subtitleOptions",
")",
";",
"each",
"(",
"[",
"[",
"'title'",
",",
"titleOptions",
",",
"chartTitleOptions",
"]",
",",
"[",
"'subtitle'",
",",
"subtitleOptions",
",",
"chartSubtitleOptions",
"]",
"]",
",",
"function",
"(",
"arr",
")",
"{",
"var",
"name",
"=",
"arr",
"[",
"0",
"]",
",",
"title",
"=",
"chart",
"[",
"name",
"]",
",",
"titleOptions",
"=",
"arr",
"[",
"1",
"]",
",",
"chartTitleOptions",
"=",
"arr",
"[",
"2",
"]",
";",
"if",
"(",
"title",
"&&",
"titleOptions",
")",
"{",
"chart",
"[",
"name",
"]",
"=",
"title",
"=",
"title",
".",
"destroy",
"(",
")",
";",
"}",
"if",
"(",
"chartTitleOptions",
"&&",
"chartTitleOptions",
".",
"text",
"&&",
"!",
"title",
")",
"{",
"chart",
"[",
"name",
"]",
"=",
"chart",
".",
"renderer",
".",
"text",
"(",
"chartTitleOptions",
".",
"text",
",",
"0",
",",
"0",
",",
"chartTitleOptions",
".",
"useHTML",
")",
".",
"attr",
"(",
"{",
"align",
":",
"chartTitleOptions",
".",
"align",
",",
"'class'",
":",
"PREFIX",
"+",
"name",
",",
"zIndex",
":",
"chartTitleOptions",
".",
"zIndex",
"||",
"4",
"}",
")",
".",
"css",
"(",
"chartTitleOptions",
".",
"style",
")",
".",
"add",
"(",
")",
";",
"}",
"}",
")",
";",
"chart",
".",
"layOutTitles",
"(",
"redraw",
")",
";",
"}"
] | Show the title and subtitle of the chart
@param titleOptions {Object} New title options
@param subtitleOptions {Object} New subtitle options | [
"Show",
"the",
"title",
"and",
"subtitle",
"of",
"the",
"chart"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L62951-L62991 | train |
|
duniter/duniter-ui | public/libraries.js | function (width, height, animation) {
var chart = this,
chartWidth,
chartHeight,
fireEndResize;
// Handle the isResizing counter
chart.isResizing += 1;
fireEndResize = function () {
if (chart) {
fireEvent(chart, 'endResize', null, function () {
chart.isResizing -= 1;
});
}
};
// set the animation for the current process
setAnimation(animation, chart);
chart.oldChartHeight = chart.chartHeight;
chart.oldChartWidth = chart.chartWidth;
if (defined(width)) {
chart.chartWidth = chartWidth = mathMax(0, mathRound(width));
chart.hasUserSize = !!chartWidth;
}
if (defined(height)) {
chart.chartHeight = chartHeight = mathMax(0, mathRound(height));
}
// Resize the container with the global animation applied if enabled (#2503)
(globalAnimation ? animate : css)(chart.container, {
width: chartWidth + PX,
height: chartHeight + PX
}, globalAnimation);
chart.setChartSize(true);
chart.renderer.setSize(chartWidth, chartHeight, animation);
// handle axes
chart.maxTicks = null;
each(chart.axes, function (axis) {
axis.isDirty = true;
axis.setScale();
});
// make sure non-cartesian series are also handled
each(chart.series, function (serie) {
serie.isDirty = true;
});
chart.isDirtyLegend = true; // force legend redraw
chart.isDirtyBox = true; // force redraw of plot and chart border
chart.layOutTitles(); // #2857
chart.getMargins();
chart.redraw(animation);
chart.oldChartHeight = null;
fireEvent(chart, 'resize');
// fire endResize and set isResizing back
// If animation is disabled, fire without delay
if (globalAnimation === false) {
fireEndResize();
} else { // else set a timeout with the animation duration
setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500);
}
} | javascript | function (width, height, animation) {
var chart = this,
chartWidth,
chartHeight,
fireEndResize;
// Handle the isResizing counter
chart.isResizing += 1;
fireEndResize = function () {
if (chart) {
fireEvent(chart, 'endResize', null, function () {
chart.isResizing -= 1;
});
}
};
// set the animation for the current process
setAnimation(animation, chart);
chart.oldChartHeight = chart.chartHeight;
chart.oldChartWidth = chart.chartWidth;
if (defined(width)) {
chart.chartWidth = chartWidth = mathMax(0, mathRound(width));
chart.hasUserSize = !!chartWidth;
}
if (defined(height)) {
chart.chartHeight = chartHeight = mathMax(0, mathRound(height));
}
// Resize the container with the global animation applied if enabled (#2503)
(globalAnimation ? animate : css)(chart.container, {
width: chartWidth + PX,
height: chartHeight + PX
}, globalAnimation);
chart.setChartSize(true);
chart.renderer.setSize(chartWidth, chartHeight, animation);
// handle axes
chart.maxTicks = null;
each(chart.axes, function (axis) {
axis.isDirty = true;
axis.setScale();
});
// make sure non-cartesian series are also handled
each(chart.series, function (serie) {
serie.isDirty = true;
});
chart.isDirtyLegend = true; // force legend redraw
chart.isDirtyBox = true; // force redraw of plot and chart border
chart.layOutTitles(); // #2857
chart.getMargins();
chart.redraw(animation);
chart.oldChartHeight = null;
fireEvent(chart, 'resize');
// fire endResize and set isResizing back
// If animation is disabled, fire without delay
if (globalAnimation === false) {
fireEndResize();
} else { // else set a timeout with the animation duration
setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500);
}
} | [
"function",
"(",
"width",
",",
"height",
",",
"animation",
")",
"{",
"var",
"chart",
"=",
"this",
",",
"chartWidth",
",",
"chartHeight",
",",
"fireEndResize",
";",
"chart",
".",
"isResizing",
"+=",
"1",
";",
"fireEndResize",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"chart",
")",
"{",
"fireEvent",
"(",
"chart",
",",
"'endResize'",
",",
"null",
",",
"function",
"(",
")",
"{",
"chart",
".",
"isResizing",
"-=",
"1",
";",
"}",
")",
";",
"}",
"}",
";",
"setAnimation",
"(",
"animation",
",",
"chart",
")",
";",
"chart",
".",
"oldChartHeight",
"=",
"chart",
".",
"chartHeight",
";",
"chart",
".",
"oldChartWidth",
"=",
"chart",
".",
"chartWidth",
";",
"if",
"(",
"defined",
"(",
"width",
")",
")",
"{",
"chart",
".",
"chartWidth",
"=",
"chartWidth",
"=",
"mathMax",
"(",
"0",
",",
"mathRound",
"(",
"width",
")",
")",
";",
"chart",
".",
"hasUserSize",
"=",
"!",
"!",
"chartWidth",
";",
"}",
"if",
"(",
"defined",
"(",
"height",
")",
")",
"{",
"chart",
".",
"chartHeight",
"=",
"chartHeight",
"=",
"mathMax",
"(",
"0",
",",
"mathRound",
"(",
"height",
")",
")",
";",
"}",
"(",
"globalAnimation",
"?",
"animate",
":",
"css",
")",
"(",
"chart",
".",
"container",
",",
"{",
"width",
":",
"chartWidth",
"+",
"PX",
",",
"height",
":",
"chartHeight",
"+",
"PX",
"}",
",",
"globalAnimation",
")",
";",
"chart",
".",
"setChartSize",
"(",
"true",
")",
";",
"chart",
".",
"renderer",
".",
"setSize",
"(",
"chartWidth",
",",
"chartHeight",
",",
"animation",
")",
";",
"chart",
".",
"maxTicks",
"=",
"null",
";",
"each",
"(",
"chart",
".",
"axes",
",",
"function",
"(",
"axis",
")",
"{",
"axis",
".",
"isDirty",
"=",
"true",
";",
"axis",
".",
"setScale",
"(",
")",
";",
"}",
")",
";",
"each",
"(",
"chart",
".",
"series",
",",
"function",
"(",
"serie",
")",
"{",
"serie",
".",
"isDirty",
"=",
"true",
";",
"}",
")",
";",
"chart",
".",
"isDirtyLegend",
"=",
"true",
";",
"chart",
".",
"isDirtyBox",
"=",
"true",
";",
"chart",
".",
"layOutTitles",
"(",
")",
";",
"chart",
".",
"getMargins",
"(",
")",
";",
"chart",
".",
"redraw",
"(",
"animation",
")",
";",
"chart",
".",
"oldChartHeight",
"=",
"null",
";",
"fireEvent",
"(",
"chart",
",",
"'resize'",
")",
";",
"if",
"(",
"globalAnimation",
"===",
"false",
")",
"{",
"fireEndResize",
"(",
")",
";",
"}",
"else",
"{",
"setTimeout",
"(",
"fireEndResize",
",",
"(",
"globalAnimation",
"&&",
"globalAnimation",
".",
"duration",
")",
"||",
"500",
")",
";",
"}",
"}"
] | Resize the chart to a given width and height
@param {Number} width
@param {Number} height
@param {Object|Boolean} animation | [
"Resize",
"the",
"chart",
"to",
"a",
"given",
"width",
"and",
"height"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L63343-L63412 | train |
|
duniter/duniter-ui | public/libraries.js | function () {
each(this.series, function (serie) {
serie.translate();
if (serie.setTooltipPoints) {
serie.setTooltipPoints();
}
serie.render();
});
} | javascript | function () {
each(this.series, function (serie) {
serie.translate();
if (serie.setTooltipPoints) {
serie.setTooltipPoints();
}
serie.render();
});
} | [
"function",
"(",
")",
"{",
"each",
"(",
"this",
".",
"series",
",",
"function",
"(",
"serie",
")",
"{",
"serie",
".",
"translate",
"(",
")",
";",
"if",
"(",
"serie",
".",
"setTooltipPoints",
")",
"{",
"serie",
".",
"setTooltipPoints",
"(",
")",
";",
"}",
"serie",
".",
"render",
"(",
")",
";",
"}",
")",
";",
"}"
] | Render series for the chart | [
"Render",
"series",
"for",
"the",
"chart"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L63677-L63685 | train |
|
duniter/duniter-ui | public/libraries.js | function (credits) {
if (credits.enabled && !this.credits) {
this.credits = this.renderer.text(
credits.text,
0,
0
)
.on('click', function () {
if (credits.href) {
location.href = credits.href;
}
})
.attr({
align: credits.position.align,
zIndex: 8
})
.css(credits.style)
.add()
.align(credits.position);
}
} | javascript | function (credits) {
if (credits.enabled && !this.credits) {
this.credits = this.renderer.text(
credits.text,
0,
0
)
.on('click', function () {
if (credits.href) {
location.href = credits.href;
}
})
.attr({
align: credits.position.align,
zIndex: 8
})
.css(credits.style)
.add()
.align(credits.position);
}
} | [
"function",
"(",
"credits",
")",
"{",
"if",
"(",
"credits",
".",
"enabled",
"&&",
"!",
"this",
".",
"credits",
")",
"{",
"this",
".",
"credits",
"=",
"this",
".",
"renderer",
".",
"text",
"(",
"credits",
".",
"text",
",",
"0",
",",
"0",
")",
".",
"on",
"(",
"'click'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"credits",
".",
"href",
")",
"{",
"location",
".",
"href",
"=",
"credits",
".",
"href",
";",
"}",
"}",
")",
".",
"attr",
"(",
"{",
"align",
":",
"credits",
".",
"position",
".",
"align",
",",
"zIndex",
":",
"8",
"}",
")",
".",
"css",
"(",
"credits",
".",
"style",
")",
".",
"add",
"(",
")",
".",
"align",
"(",
"credits",
".",
"position",
")",
";",
"}",
"}"
] | Show chart credits based on config options | [
"Show",
"chart",
"credits",
"based",
"on",
"config",
"options"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L63784-L63804 | train |
|
duniter/duniter-ui | public/libraries.js | function (chart, options) {
var series = this,
eventType,
events,
chartSeries = chart.series,
sortByIndex = function (a, b) {
return pick(a.options.index, a._i) - pick(b.options.index, b._i);
};
series.chart = chart;
series.options = options = series.setOptions(options); // merge with plotOptions
series.linkedSeries = [];
// bind the axes
series.bindAxes();
// set some variables
extend(series, {
name: options.name,
state: NORMAL_STATE,
pointAttr: {},
visible: options.visible !== false, // true by default
selected: options.selected === true // false by default
});
// special
if (useCanVG) {
options.animation = false;
}
// register event listeners
events = options.events;
for (eventType in events) {
addEvent(series, eventType, events[eventType]);
}
if (
(events && events.click) ||
(options.point && options.point.events && options.point.events.click) ||
options.allowPointSelect
) {
chart.runTrackerClick = true;
}
series.getColor();
series.getSymbol();
// Set the data
each(series.parallelArrays, function (key) {
series[key + 'Data'] = [];
});
series.setData(options.data, false);
// Mark cartesian
if (series.isCartesian) {
chart.hasCartesianSeries = true;
}
// Register it in the chart
chartSeries.push(series);
series._i = chartSeries.length - 1;
// Sort series according to index option (#248, #1123, #2456)
stableSort(chartSeries, sortByIndex);
if (this.yAxis) {
stableSort(this.yAxis.series, sortByIndex);
}
each(chartSeries, function (series, i) {
series.index = i;
series.name = series.name || 'Series ' + (i + 1);
});
} | javascript | function (chart, options) {
var series = this,
eventType,
events,
chartSeries = chart.series,
sortByIndex = function (a, b) {
return pick(a.options.index, a._i) - pick(b.options.index, b._i);
};
series.chart = chart;
series.options = options = series.setOptions(options); // merge with plotOptions
series.linkedSeries = [];
// bind the axes
series.bindAxes();
// set some variables
extend(series, {
name: options.name,
state: NORMAL_STATE,
pointAttr: {},
visible: options.visible !== false, // true by default
selected: options.selected === true // false by default
});
// special
if (useCanVG) {
options.animation = false;
}
// register event listeners
events = options.events;
for (eventType in events) {
addEvent(series, eventType, events[eventType]);
}
if (
(events && events.click) ||
(options.point && options.point.events && options.point.events.click) ||
options.allowPointSelect
) {
chart.runTrackerClick = true;
}
series.getColor();
series.getSymbol();
// Set the data
each(series.parallelArrays, function (key) {
series[key + 'Data'] = [];
});
series.setData(options.data, false);
// Mark cartesian
if (series.isCartesian) {
chart.hasCartesianSeries = true;
}
// Register it in the chart
chartSeries.push(series);
series._i = chartSeries.length - 1;
// Sort series according to index option (#248, #1123, #2456)
stableSort(chartSeries, sortByIndex);
if (this.yAxis) {
stableSort(this.yAxis.series, sortByIndex);
}
each(chartSeries, function (series, i) {
series.index = i;
series.name = series.name || 'Series ' + (i + 1);
});
} | [
"function",
"(",
"chart",
",",
"options",
")",
"{",
"var",
"series",
"=",
"this",
",",
"eventType",
",",
"events",
",",
"chartSeries",
"=",
"chart",
".",
"series",
",",
"sortByIndex",
"=",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"pick",
"(",
"a",
".",
"options",
".",
"index",
",",
"a",
".",
"_i",
")",
"-",
"pick",
"(",
"b",
".",
"options",
".",
"index",
",",
"b",
".",
"_i",
")",
";",
"}",
";",
"series",
".",
"chart",
"=",
"chart",
";",
"series",
".",
"options",
"=",
"options",
"=",
"series",
".",
"setOptions",
"(",
"options",
")",
";",
"series",
".",
"linkedSeries",
"=",
"[",
"]",
";",
"series",
".",
"bindAxes",
"(",
")",
";",
"extend",
"(",
"series",
",",
"{",
"name",
":",
"options",
".",
"name",
",",
"state",
":",
"NORMAL_STATE",
",",
"pointAttr",
":",
"{",
"}",
",",
"visible",
":",
"options",
".",
"visible",
"!==",
"false",
",",
"selected",
":",
"options",
".",
"selected",
"===",
"true",
"}",
")",
";",
"if",
"(",
"useCanVG",
")",
"{",
"options",
".",
"animation",
"=",
"false",
";",
"}",
"events",
"=",
"options",
".",
"events",
";",
"for",
"(",
"eventType",
"in",
"events",
")",
"{",
"addEvent",
"(",
"series",
",",
"eventType",
",",
"events",
"[",
"eventType",
"]",
")",
";",
"}",
"if",
"(",
"(",
"events",
"&&",
"events",
".",
"click",
")",
"||",
"(",
"options",
".",
"point",
"&&",
"options",
".",
"point",
".",
"events",
"&&",
"options",
".",
"point",
".",
"events",
".",
"click",
")",
"||",
"options",
".",
"allowPointSelect",
")",
"{",
"chart",
".",
"runTrackerClick",
"=",
"true",
";",
"}",
"series",
".",
"getColor",
"(",
")",
";",
"series",
".",
"getSymbol",
"(",
")",
";",
"each",
"(",
"series",
".",
"parallelArrays",
",",
"function",
"(",
"key",
")",
"{",
"series",
"[",
"key",
"+",
"'Data'",
"]",
"=",
"[",
"]",
";",
"}",
")",
";",
"series",
".",
"setData",
"(",
"options",
".",
"data",
",",
"false",
")",
";",
"if",
"(",
"series",
".",
"isCartesian",
")",
"{",
"chart",
".",
"hasCartesianSeries",
"=",
"true",
";",
"}",
"chartSeries",
".",
"push",
"(",
"series",
")",
";",
"series",
".",
"_i",
"=",
"chartSeries",
".",
"length",
"-",
"1",
";",
"stableSort",
"(",
"chartSeries",
",",
"sortByIndex",
")",
";",
"if",
"(",
"this",
".",
"yAxis",
")",
"{",
"stableSort",
"(",
"this",
".",
"yAxis",
".",
"series",
",",
"sortByIndex",
")",
";",
"}",
"each",
"(",
"chartSeries",
",",
"function",
"(",
"series",
",",
"i",
")",
"{",
"series",
".",
"index",
"=",
"i",
";",
"series",
".",
"name",
"=",
"series",
".",
"name",
"||",
"'Series '",
"+",
"(",
"i",
"+",
"1",
")",
";",
"}",
")",
";",
"}"
] | each point's x and y values are stored in this.xData and this.yData | [
"each",
"point",
"s",
"x",
"and",
"y",
"values",
"are",
"stored",
"in",
"this",
".",
"xData",
"and",
"this",
".",
"yData"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L64287-L64359 | train |
|
duniter/duniter-ui | public/libraries.js | function () {
var series = this,
seriesOptions = series.options,
chart = series.chart,
axisOptions;
each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis
each(chart[AXIS], function (axis) { // loop through the chart's axis objects
axisOptions = axis.options;
// apply if the series xAxis or yAxis option mathches the number of the
// axis, or if undefined, use the first axis
if ((seriesOptions[AXIS] === axisOptions.index) ||
(seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) ||
(seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) {
// register this series in the axis.series lookup
axis.series.push(series);
// set this series.xAxis or series.yAxis reference
series[AXIS] = axis;
// mark dirty for redraw
axis.isDirty = true;
}
});
// The series needs an X and an Y axis
if (!series[AXIS] && series.optionalAxis !== AXIS) {
error(18, true);
}
});
} | javascript | function () {
var series = this,
seriesOptions = series.options,
chart = series.chart,
axisOptions;
each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis
each(chart[AXIS], function (axis) { // loop through the chart's axis objects
axisOptions = axis.options;
// apply if the series xAxis or yAxis option mathches the number of the
// axis, or if undefined, use the first axis
if ((seriesOptions[AXIS] === axisOptions.index) ||
(seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) ||
(seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) {
// register this series in the axis.series lookup
axis.series.push(series);
// set this series.xAxis or series.yAxis reference
series[AXIS] = axis;
// mark dirty for redraw
axis.isDirty = true;
}
});
// The series needs an X and an Y axis
if (!series[AXIS] && series.optionalAxis !== AXIS) {
error(18, true);
}
});
} | [
"function",
"(",
")",
"{",
"var",
"series",
"=",
"this",
",",
"seriesOptions",
"=",
"series",
".",
"options",
",",
"chart",
"=",
"series",
".",
"chart",
",",
"axisOptions",
";",
"each",
"(",
"series",
".",
"axisTypes",
"||",
"[",
"]",
",",
"function",
"(",
"AXIS",
")",
"{",
"each",
"(",
"chart",
"[",
"AXIS",
"]",
",",
"function",
"(",
"axis",
")",
"{",
"axisOptions",
"=",
"axis",
".",
"options",
";",
"if",
"(",
"(",
"seriesOptions",
"[",
"AXIS",
"]",
"===",
"axisOptions",
".",
"index",
")",
"||",
"(",
"seriesOptions",
"[",
"AXIS",
"]",
"!==",
"UNDEFINED",
"&&",
"seriesOptions",
"[",
"AXIS",
"]",
"===",
"axisOptions",
".",
"id",
")",
"||",
"(",
"seriesOptions",
"[",
"AXIS",
"]",
"===",
"UNDEFINED",
"&&",
"axisOptions",
".",
"index",
"===",
"0",
")",
")",
"{",
"axis",
".",
"series",
".",
"push",
"(",
"series",
")",
";",
"series",
"[",
"AXIS",
"]",
"=",
"axis",
";",
"axis",
".",
"isDirty",
"=",
"true",
";",
"}",
"}",
")",
";",
"if",
"(",
"!",
"series",
"[",
"AXIS",
"]",
"&&",
"series",
".",
"optionalAxis",
"!==",
"AXIS",
")",
"{",
"error",
"(",
"18",
",",
"true",
")",
";",
"}",
"}",
")",
";",
"}"
] | Set the xAxis and yAxis properties of cartesian series, and register the series
in the axis.series array | [
"Set",
"the",
"xAxis",
"and",
"yAxis",
"properties",
"of",
"cartesian",
"series",
"and",
"register",
"the",
"series",
"in",
"the",
"axis",
".",
"series",
"array"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L64365-L64399 | train |
|
duniter/duniter-ui | public/libraries.js | function (point, i) {
var series = point.series,
args = arguments,
fn = typeof i === 'number' ?
// Insert the value in the given position
function (key) {
var val = key === 'y' && series.toYData ? series.toYData(point) : point[key];
series[key + 'Data'][i] = val;
} :
// Apply the method specified in i with the following arguments as arguments
function (key) {
Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2));
};
each(series.parallelArrays, fn);
} | javascript | function (point, i) {
var series = point.series,
args = arguments,
fn = typeof i === 'number' ?
// Insert the value in the given position
function (key) {
var val = key === 'y' && series.toYData ? series.toYData(point) : point[key];
series[key + 'Data'][i] = val;
} :
// Apply the method specified in i with the following arguments as arguments
function (key) {
Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2));
};
each(series.parallelArrays, fn);
} | [
"function",
"(",
"point",
",",
"i",
")",
"{",
"var",
"series",
"=",
"point",
".",
"series",
",",
"args",
"=",
"arguments",
",",
"fn",
"=",
"typeof",
"i",
"===",
"'number'",
"?",
"function",
"(",
"key",
")",
"{",
"var",
"val",
"=",
"key",
"===",
"'y'",
"&&",
"series",
".",
"toYData",
"?",
"series",
".",
"toYData",
"(",
"point",
")",
":",
"point",
"[",
"key",
"]",
";",
"series",
"[",
"key",
"+",
"'Data'",
"]",
"[",
"i",
"]",
"=",
"val",
";",
"}",
":",
"function",
"(",
"key",
")",
"{",
"Array",
".",
"prototype",
"[",
"i",
"]",
".",
"apply",
"(",
"series",
"[",
"key",
"+",
"'Data'",
"]",
",",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"args",
",",
"2",
")",
")",
";",
"}",
";",
"each",
"(",
"series",
".",
"parallelArrays",
",",
"fn",
")",
";",
"}"
] | For simple series types like line and column, the data values are held in arrays like
xData and yData for quick lookup to find extremes and more. For multidimensional series
like bubble and map, this can be extended with arrays like zData and valueData by
adding to the series.parallelArrays array. | [
"For",
"simple",
"series",
"types",
"like",
"line",
"and",
"column",
"the",
"data",
"values",
"are",
"held",
"in",
"arrays",
"like",
"xData",
"and",
"yData",
"for",
"quick",
"lookup",
"to",
"find",
"extremes",
"and",
"more",
".",
"For",
"multidimensional",
"series",
"like",
"bubble",
"and",
"map",
"this",
"can",
"be",
"extended",
"with",
"arrays",
"like",
"zData",
"and",
"valueData",
"by",
"adding",
"to",
"the",
"series",
".",
"parallelArrays",
"array",
"."
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L64407-L64422 | train |
|
duniter/duniter-ui | public/libraries.js | function (key) {
var val = key === 'y' && series.toYData ? series.toYData(point) : point[key];
series[key + 'Data'][i] = val;
} | javascript | function (key) {
var val = key === 'y' && series.toYData ? series.toYData(point) : point[key];
series[key + 'Data'][i] = val;
} | [
"function",
"(",
"key",
")",
"{",
"var",
"val",
"=",
"key",
"===",
"'y'",
"&&",
"series",
".",
"toYData",
"?",
"series",
".",
"toYData",
"(",
"point",
")",
":",
"point",
"[",
"key",
"]",
";",
"series",
"[",
"key",
"+",
"'Data'",
"]",
"[",
"i",
"]",
"=",
"val",
";",
"}"
] | Insert the value in the given position | [
"Insert",
"the",
"value",
"in",
"the",
"given",
"position"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L64412-L64415 | train |
|
duniter/duniter-ui | public/libraries.js | function (key) {
Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2));
} | javascript | function (key) {
Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2));
} | [
"function",
"(",
"key",
")",
"{",
"Array",
".",
"prototype",
"[",
"i",
"]",
".",
"apply",
"(",
"series",
"[",
"key",
"+",
"'Data'",
"]",
",",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"args",
",",
"2",
")",
")",
";",
"}"
] | Apply the method specified in i with the following arguments as arguments | [
"Apply",
"the",
"method",
"specified",
"in",
"i",
"with",
"the",
"following",
"arguments",
"as",
"arguments"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L64417-L64419 | train |
|
duniter/duniter-ui | public/libraries.js | function (force) {
var series = this,
processedXData = series.xData, // copied during slice operation below
processedYData = series.yData,
dataLength = processedXData.length,
croppedData,
cropStart = 0,
cropped,
distance,
closestPointRange,
xAxis = series.xAxis,
i, // loop variable
options = series.options,
cropThreshold = options.cropThreshold,
activePointCount = 0,
isCartesian = series.isCartesian,
xExtremes,
min,
max;
// If the series data or axes haven't changed, don't go through this. Return false to pass
// the message on to override methods like in data grouping.
if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
return false;
}
if (xAxis) {
xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053)
min = xExtremes.min;
max = xExtremes.max;
}
// optionally filter out points outside the plot area
if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
// it's outside current extremes
if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
processedXData = [];
processedYData = [];
// only crop if it's actually spilling out
} else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
croppedData = this.cropData(series.xData, series.yData, min, max);
processedXData = croppedData.xData;
processedYData = croppedData.yData;
cropStart = croppedData.start;
cropped = true;
activePointCount = processedXData.length;
}
}
// Find the closest distance between processed points
for (i = processedXData.length - 1; i >= 0; i--) {
distance = processedXData[i] - processedXData[i - 1];
if (!cropped && processedXData[i] > min && processedXData[i] < max) {
activePointCount++;
}
if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) {
closestPointRange = distance;
// Unsorted data is not supported by the line tooltip, as well as data grouping and
// navigation in Stock charts (#725) and width calculation of columns (#1900)
} else if (distance < 0 && series.requireSorting) {
error(15);
}
}
// Record the properties
series.cropped = cropped; // undefined or true
series.cropStart = cropStart;
series.processedXData = processedXData;
series.processedYData = processedYData;
series.activePointCount = activePointCount;
if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC
series.pointRange = closestPointRange || 1;
}
series.closestPointRange = closestPointRange;
} | javascript | function (force) {
var series = this,
processedXData = series.xData, // copied during slice operation below
processedYData = series.yData,
dataLength = processedXData.length,
croppedData,
cropStart = 0,
cropped,
distance,
closestPointRange,
xAxis = series.xAxis,
i, // loop variable
options = series.options,
cropThreshold = options.cropThreshold,
activePointCount = 0,
isCartesian = series.isCartesian,
xExtremes,
min,
max;
// If the series data or axes haven't changed, don't go through this. Return false to pass
// the message on to override methods like in data grouping.
if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
return false;
}
if (xAxis) {
xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053)
min = xExtremes.min;
max = xExtremes.max;
}
// optionally filter out points outside the plot area
if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
// it's outside current extremes
if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
processedXData = [];
processedYData = [];
// only crop if it's actually spilling out
} else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
croppedData = this.cropData(series.xData, series.yData, min, max);
processedXData = croppedData.xData;
processedYData = croppedData.yData;
cropStart = croppedData.start;
cropped = true;
activePointCount = processedXData.length;
}
}
// Find the closest distance between processed points
for (i = processedXData.length - 1; i >= 0; i--) {
distance = processedXData[i] - processedXData[i - 1];
if (!cropped && processedXData[i] > min && processedXData[i] < max) {
activePointCount++;
}
if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) {
closestPointRange = distance;
// Unsorted data is not supported by the line tooltip, as well as data grouping and
// navigation in Stock charts (#725) and width calculation of columns (#1900)
} else if (distance < 0 && series.requireSorting) {
error(15);
}
}
// Record the properties
series.cropped = cropped; // undefined or true
series.cropStart = cropStart;
series.processedXData = processedXData;
series.processedYData = processedYData;
series.activePointCount = activePointCount;
if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC
series.pointRange = closestPointRange || 1;
}
series.closestPointRange = closestPointRange;
} | [
"function",
"(",
"force",
")",
"{",
"var",
"series",
"=",
"this",
",",
"processedXData",
"=",
"series",
".",
"xData",
",",
"processedYData",
"=",
"series",
".",
"yData",
",",
"dataLength",
"=",
"processedXData",
".",
"length",
",",
"croppedData",
",",
"cropStart",
"=",
"0",
",",
"cropped",
",",
"distance",
",",
"closestPointRange",
",",
"xAxis",
"=",
"series",
".",
"xAxis",
",",
"i",
",",
"options",
"=",
"series",
".",
"options",
",",
"cropThreshold",
"=",
"options",
".",
"cropThreshold",
",",
"activePointCount",
"=",
"0",
",",
"isCartesian",
"=",
"series",
".",
"isCartesian",
",",
"xExtremes",
",",
"min",
",",
"max",
";",
"if",
"(",
"isCartesian",
"&&",
"!",
"series",
".",
"isDirty",
"&&",
"!",
"xAxis",
".",
"isDirty",
"&&",
"!",
"series",
".",
"yAxis",
".",
"isDirty",
"&&",
"!",
"force",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"xAxis",
")",
"{",
"xExtremes",
"=",
"xAxis",
".",
"getExtremes",
"(",
")",
";",
"min",
"=",
"xExtremes",
".",
"min",
";",
"max",
"=",
"xExtremes",
".",
"max",
";",
"}",
"if",
"(",
"isCartesian",
"&&",
"series",
".",
"sorted",
"&&",
"(",
"!",
"cropThreshold",
"||",
"dataLength",
">",
"cropThreshold",
"||",
"series",
".",
"forceCrop",
")",
")",
"{",
"if",
"(",
"processedXData",
"[",
"dataLength",
"-",
"1",
"]",
"<",
"min",
"||",
"processedXData",
"[",
"0",
"]",
">",
"max",
")",
"{",
"processedXData",
"=",
"[",
"]",
";",
"processedYData",
"=",
"[",
"]",
";",
"}",
"else",
"if",
"(",
"processedXData",
"[",
"0",
"]",
"<",
"min",
"||",
"processedXData",
"[",
"dataLength",
"-",
"1",
"]",
">",
"max",
")",
"{",
"croppedData",
"=",
"this",
".",
"cropData",
"(",
"series",
".",
"xData",
",",
"series",
".",
"yData",
",",
"min",
",",
"max",
")",
";",
"processedXData",
"=",
"croppedData",
".",
"xData",
";",
"processedYData",
"=",
"croppedData",
".",
"yData",
";",
"cropStart",
"=",
"croppedData",
".",
"start",
";",
"cropped",
"=",
"true",
";",
"activePointCount",
"=",
"processedXData",
".",
"length",
";",
"}",
"}",
"for",
"(",
"i",
"=",
"processedXData",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"distance",
"=",
"processedXData",
"[",
"i",
"]",
"-",
"processedXData",
"[",
"i",
"-",
"1",
"]",
";",
"if",
"(",
"!",
"cropped",
"&&",
"processedXData",
"[",
"i",
"]",
">",
"min",
"&&",
"processedXData",
"[",
"i",
"]",
"<",
"max",
")",
"{",
"activePointCount",
"++",
";",
"}",
"if",
"(",
"distance",
">",
"0",
"&&",
"(",
"closestPointRange",
"===",
"UNDEFINED",
"||",
"distance",
"<",
"closestPointRange",
")",
")",
"{",
"closestPointRange",
"=",
"distance",
";",
"}",
"else",
"if",
"(",
"distance",
"<",
"0",
"&&",
"series",
".",
"requireSorting",
")",
"{",
"error",
"(",
"15",
")",
";",
"}",
"}",
"series",
".",
"cropped",
"=",
"cropped",
";",
"series",
".",
"cropStart",
"=",
"cropStart",
";",
"series",
".",
"processedXData",
"=",
"processedXData",
";",
"series",
".",
"processedYData",
"=",
"processedYData",
";",
"series",
".",
"activePointCount",
"=",
"activePointCount",
";",
"if",
"(",
"options",
".",
"pointRange",
"===",
"null",
")",
"{",
"series",
".",
"pointRange",
"=",
"closestPointRange",
"||",
"1",
";",
"}",
"series",
".",
"closestPointRange",
"=",
"closestPointRange",
";",
"}"
] | Process the data by cropping away unused data points if the series is longer
than the crop threshold. This saves computing time for lage series. | [
"Process",
"the",
"data",
"by",
"cropping",
"away",
"unused",
"data",
"points",
"if",
"the",
"series",
"is",
"longer",
"than",
"the",
"crop",
"threshold",
".",
"This",
"saves",
"computing",
"time",
"for",
"lage",
"series",
"."
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L64708-L64790 | train |
|
duniter/duniter-ui | public/libraries.js | function () {
var series = this,
options = series.options,
dataOptions = options.data,
data = series.data,
dataLength,
processedXData = series.processedXData,
processedYData = series.processedYData,
pointClass = series.pointClass,
processedDataLength = processedXData.length,
cropStart = series.cropStart || 0,
cursor,
hasGroupedData = series.hasGroupedData,
point,
points = [],
i;
if (!data && !hasGroupedData) {
var arr = [];
arr.length = dataOptions.length;
data = series.data = arr;
}
for (i = 0; i < processedDataLength; i++) {
cursor = cropStart + i;
if (!hasGroupedData) {
if (data[cursor]) {
point = data[cursor];
} else if (dataOptions[cursor] !== UNDEFINED) { // #970
data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]);
}
points[i] = point;
} else {
// splat the y data in case of ohlc data array
points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
}
points[i].index = cursor; // For faster access in Point.update
}
// Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
// swithching view from non-grouped data to grouped data (#637)
if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
for (i = 0; i < dataLength; i++) {
if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
i += processedDataLength;
}
if (data[i]) {
data[i].destroyElements();
data[i].plotX = UNDEFINED; // #1003
}
}
}
series.data = data;
series.points = points;
} | javascript | function () {
var series = this,
options = series.options,
dataOptions = options.data,
data = series.data,
dataLength,
processedXData = series.processedXData,
processedYData = series.processedYData,
pointClass = series.pointClass,
processedDataLength = processedXData.length,
cropStart = series.cropStart || 0,
cursor,
hasGroupedData = series.hasGroupedData,
point,
points = [],
i;
if (!data && !hasGroupedData) {
var arr = [];
arr.length = dataOptions.length;
data = series.data = arr;
}
for (i = 0; i < processedDataLength; i++) {
cursor = cropStart + i;
if (!hasGroupedData) {
if (data[cursor]) {
point = data[cursor];
} else if (dataOptions[cursor] !== UNDEFINED) { // #970
data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]);
}
points[i] = point;
} else {
// splat the y data in case of ohlc data array
points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
}
points[i].index = cursor; // For faster access in Point.update
}
// Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
// swithching view from non-grouped data to grouped data (#637)
if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
for (i = 0; i < dataLength; i++) {
if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
i += processedDataLength;
}
if (data[i]) {
data[i].destroyElements();
data[i].plotX = UNDEFINED; // #1003
}
}
}
series.data = data;
series.points = points;
} | [
"function",
"(",
")",
"{",
"var",
"series",
"=",
"this",
",",
"options",
"=",
"series",
".",
"options",
",",
"dataOptions",
"=",
"options",
".",
"data",
",",
"data",
"=",
"series",
".",
"data",
",",
"dataLength",
",",
"processedXData",
"=",
"series",
".",
"processedXData",
",",
"processedYData",
"=",
"series",
".",
"processedYData",
",",
"pointClass",
"=",
"series",
".",
"pointClass",
",",
"processedDataLength",
"=",
"processedXData",
".",
"length",
",",
"cropStart",
"=",
"series",
".",
"cropStart",
"||",
"0",
",",
"cursor",
",",
"hasGroupedData",
"=",
"series",
".",
"hasGroupedData",
",",
"point",
",",
"points",
"=",
"[",
"]",
",",
"i",
";",
"if",
"(",
"!",
"data",
"&&",
"!",
"hasGroupedData",
")",
"{",
"var",
"arr",
"=",
"[",
"]",
";",
"arr",
".",
"length",
"=",
"dataOptions",
".",
"length",
";",
"data",
"=",
"series",
".",
"data",
"=",
"arr",
";",
"}",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"processedDataLength",
";",
"i",
"++",
")",
"{",
"cursor",
"=",
"cropStart",
"+",
"i",
";",
"if",
"(",
"!",
"hasGroupedData",
")",
"{",
"if",
"(",
"data",
"[",
"cursor",
"]",
")",
"{",
"point",
"=",
"data",
"[",
"cursor",
"]",
";",
"}",
"else",
"if",
"(",
"dataOptions",
"[",
"cursor",
"]",
"!==",
"UNDEFINED",
")",
"{",
"data",
"[",
"cursor",
"]",
"=",
"point",
"=",
"(",
"new",
"pointClass",
"(",
")",
")",
".",
"init",
"(",
"series",
",",
"dataOptions",
"[",
"cursor",
"]",
",",
"processedXData",
"[",
"i",
"]",
")",
";",
"}",
"points",
"[",
"i",
"]",
"=",
"point",
";",
"}",
"else",
"{",
"points",
"[",
"i",
"]",
"=",
"(",
"new",
"pointClass",
"(",
")",
")",
".",
"init",
"(",
"series",
",",
"[",
"processedXData",
"[",
"i",
"]",
"]",
".",
"concat",
"(",
"splat",
"(",
"processedYData",
"[",
"i",
"]",
")",
")",
")",
";",
"}",
"points",
"[",
"i",
"]",
".",
"index",
"=",
"cursor",
";",
"}",
"if",
"(",
"data",
"&&",
"(",
"processedDataLength",
"!==",
"(",
"dataLength",
"=",
"data",
".",
"length",
")",
"||",
"hasGroupedData",
")",
")",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"dataLength",
";",
"i",
"++",
")",
"{",
"if",
"(",
"i",
"===",
"cropStart",
"&&",
"!",
"hasGroupedData",
")",
"{",
"i",
"+=",
"processedDataLength",
";",
"}",
"if",
"(",
"data",
"[",
"i",
"]",
")",
"{",
"data",
"[",
"i",
"]",
".",
"destroyElements",
"(",
")",
";",
"data",
"[",
"i",
"]",
".",
"plotX",
"=",
"UNDEFINED",
";",
"}",
"}",
"}",
"series",
".",
"data",
"=",
"data",
";",
"series",
".",
"points",
"=",
"points",
";",
"}"
] | Generate the data point after the data has been processed by cropping away
unused points and optionally grouped in Highcharts Stock. | [
"Generate",
"the",
"data",
"point",
"after",
"the",
"data",
"has",
"been",
"processed",
"by",
"cropping",
"away",
"unused",
"points",
"and",
"optionally",
"grouped",
"in",
"Highcharts",
"Stock",
"."
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L64832-L64887 | train |
|
duniter/duniter-ui | public/libraries.js | StackItem | function StackItem(axis, options, isNegative, x, stackOption) {
var inverted = axis.chart.inverted;
this.axis = axis;
// Tells if the stack is negative
this.isNegative = isNegative;
// Save the options to be able to style the label
this.options = options;
// Save the x value to be able to position the label later
this.x = x;
// Initialize total value
this.total = null;
// This will keep each points' extremes stored by series.index and point index
this.points = {};
// Save the stack option on the series configuration object, and whether to treat it as percent
this.stack = stackOption;
// The align options and text align varies on whether the stack is negative and
// if the chart is inverted or not.
// First test the user supplied value, then use the dynamic.
this.alignOptions = {
align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'),
verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')),
y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)),
x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0)
};
this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center');
} | javascript | function StackItem(axis, options, isNegative, x, stackOption) {
var inverted = axis.chart.inverted;
this.axis = axis;
// Tells if the stack is negative
this.isNegative = isNegative;
// Save the options to be able to style the label
this.options = options;
// Save the x value to be able to position the label later
this.x = x;
// Initialize total value
this.total = null;
// This will keep each points' extremes stored by series.index and point index
this.points = {};
// Save the stack option on the series configuration object, and whether to treat it as percent
this.stack = stackOption;
// The align options and text align varies on whether the stack is negative and
// if the chart is inverted or not.
// First test the user supplied value, then use the dynamic.
this.alignOptions = {
align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'),
verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')),
y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)),
x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0)
};
this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center');
} | [
"function",
"StackItem",
"(",
"axis",
",",
"options",
",",
"isNegative",
",",
"x",
",",
"stackOption",
")",
"{",
"var",
"inverted",
"=",
"axis",
".",
"chart",
".",
"inverted",
";",
"this",
".",
"axis",
"=",
"axis",
";",
"this",
".",
"isNegative",
"=",
"isNegative",
";",
"this",
".",
"options",
"=",
"options",
";",
"this",
".",
"x",
"=",
"x",
";",
"this",
".",
"total",
"=",
"null",
";",
"this",
".",
"points",
"=",
"{",
"}",
";",
"this",
".",
"stack",
"=",
"stackOption",
";",
"this",
".",
"alignOptions",
"=",
"{",
"align",
":",
"options",
".",
"align",
"||",
"(",
"inverted",
"?",
"(",
"isNegative",
"?",
"'left'",
":",
"'right'",
")",
":",
"'center'",
")",
",",
"verticalAlign",
":",
"options",
".",
"verticalAlign",
"||",
"(",
"inverted",
"?",
"'middle'",
":",
"(",
"isNegative",
"?",
"'bottom'",
":",
"'top'",
")",
")",
",",
"y",
":",
"pick",
"(",
"options",
".",
"y",
",",
"inverted",
"?",
"4",
":",
"(",
"isNegative",
"?",
"14",
":",
"-",
"6",
")",
")",
",",
"x",
":",
"pick",
"(",
"options",
".",
"x",
",",
"inverted",
"?",
"(",
"isNegative",
"?",
"-",
"6",
":",
"6",
")",
":",
"0",
")",
"}",
";",
"this",
".",
"textAlign",
"=",
"options",
".",
"textAlign",
"||",
"(",
"inverted",
"?",
"(",
"isNegative",
"?",
"'right'",
":",
"'left'",
")",
":",
"'center'",
")",
";",
"}"
] | end Series prototype
The class for stack items | [
"end",
"Series",
"prototype",
"The",
"class",
"for",
"stack",
"items"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L65906-L65941 | train |
duniter/duniter-ui | public/libraries.js | function (newOptions, redraw) {
var series = this,
chart = this.chart,
// must use user options when changing type because this.options is merged
// in with type specific plotOptions
oldOptions = this.userOptions,
oldType = this.type,
proto = seriesTypes[oldType].prototype,
preserve = ['group', 'markerGroup', 'dataLabelsGroup'],
n;
// Make sure groups are not destroyed (#3094)
each(preserve, function (prop) {
preserve[prop] = series[prop];
delete series[prop];
});
// Do the merge, with some forced options
newOptions = merge(oldOptions, {
animation: false,
index: this.index,
pointStart: this.xData[0] // when updating after addPoint
}, { data: this.options.data }, newOptions);
// Destroy the series and reinsert methods from the type prototype
this.remove(false);
for (n in proto) { // Overwrite series-type specific methods (#2270)
if (proto.hasOwnProperty(n)) {
this[n] = UNDEFINED;
}
}
extend(this, seriesTypes[newOptions.type || oldType].prototype);
// Re-register groups (#3094)
each(preserve, function (prop) {
series[prop] = preserve[prop];
});
this.init(chart, newOptions);
chart.linkSeries(); // Links are lost in this.remove (#3028)
if (pick(redraw, true)) {
chart.redraw(false);
}
} | javascript | function (newOptions, redraw) {
var series = this,
chart = this.chart,
// must use user options when changing type because this.options is merged
// in with type specific plotOptions
oldOptions = this.userOptions,
oldType = this.type,
proto = seriesTypes[oldType].prototype,
preserve = ['group', 'markerGroup', 'dataLabelsGroup'],
n;
// Make sure groups are not destroyed (#3094)
each(preserve, function (prop) {
preserve[prop] = series[prop];
delete series[prop];
});
// Do the merge, with some forced options
newOptions = merge(oldOptions, {
animation: false,
index: this.index,
pointStart: this.xData[0] // when updating after addPoint
}, { data: this.options.data }, newOptions);
// Destroy the series and reinsert methods from the type prototype
this.remove(false);
for (n in proto) { // Overwrite series-type specific methods (#2270)
if (proto.hasOwnProperty(n)) {
this[n] = UNDEFINED;
}
}
extend(this, seriesTypes[newOptions.type || oldType].prototype);
// Re-register groups (#3094)
each(preserve, function (prop) {
series[prop] = preserve[prop];
});
this.init(chart, newOptions);
chart.linkSeries(); // Links are lost in this.remove (#3028)
if (pick(redraw, true)) {
chart.redraw(false);
}
} | [
"function",
"(",
"newOptions",
",",
"redraw",
")",
"{",
"var",
"series",
"=",
"this",
",",
"chart",
"=",
"this",
".",
"chart",
",",
"oldOptions",
"=",
"this",
".",
"userOptions",
",",
"oldType",
"=",
"this",
".",
"type",
",",
"proto",
"=",
"seriesTypes",
"[",
"oldType",
"]",
".",
"prototype",
",",
"preserve",
"=",
"[",
"'group'",
",",
"'markerGroup'",
",",
"'dataLabelsGroup'",
"]",
",",
"n",
";",
"each",
"(",
"preserve",
",",
"function",
"(",
"prop",
")",
"{",
"preserve",
"[",
"prop",
"]",
"=",
"series",
"[",
"prop",
"]",
";",
"delete",
"series",
"[",
"prop",
"]",
";",
"}",
")",
";",
"newOptions",
"=",
"merge",
"(",
"oldOptions",
",",
"{",
"animation",
":",
"false",
",",
"index",
":",
"this",
".",
"index",
",",
"pointStart",
":",
"this",
".",
"xData",
"[",
"0",
"]",
"}",
",",
"{",
"data",
":",
"this",
".",
"options",
".",
"data",
"}",
",",
"newOptions",
")",
";",
"this",
".",
"remove",
"(",
"false",
")",
";",
"for",
"(",
"n",
"in",
"proto",
")",
"{",
"if",
"(",
"proto",
".",
"hasOwnProperty",
"(",
"n",
")",
")",
"{",
"this",
"[",
"n",
"]",
"=",
"UNDEFINED",
";",
"}",
"}",
"extend",
"(",
"this",
",",
"seriesTypes",
"[",
"newOptions",
".",
"type",
"||",
"oldType",
"]",
".",
"prototype",
")",
";",
"each",
"(",
"preserve",
",",
"function",
"(",
"prop",
")",
"{",
"series",
"[",
"prop",
"]",
"=",
"preserve",
"[",
"prop",
"]",
";",
"}",
")",
";",
"this",
".",
"init",
"(",
"chart",
",",
"newOptions",
")",
";",
"chart",
".",
"linkSeries",
"(",
")",
";",
"if",
"(",
"pick",
"(",
"redraw",
",",
"true",
")",
")",
"{",
"chart",
".",
"redraw",
"(",
"false",
")",
";",
"}",
"}"
] | Update the series with a new set of options | [
"Update",
"the",
"series",
"with",
"a",
"new",
"set",
"of",
"options"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L66585-L66629 | train |
|
duniter/duniter-ui | public/libraries.js | function () {
var series = this,
segments = [],
segment = [],
keys = [],
xAxis = this.xAxis,
yAxis = this.yAxis,
stack = yAxis.stacks[this.stackKey],
pointMap = {},
plotX,
plotY,
points = this.points,
connectNulls = this.options.connectNulls,
i,
x;
if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue
// Create a map where we can quickly look up the points by their X value.
for (i = 0; i < points.length; i++) {
pointMap[points[i].x] = points[i];
}
// Sort the keys (#1651)
for (x in stack) {
if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336)
keys.push(+x);
}
}
keys.sort(function (a, b) {
return a - b;
});
each(keys, function (x) {
var y = 0,
stackPoint;
if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836
return;
// The point exists, push it to the segment
} else if (pointMap[x]) {
segment.push(pointMap[x]);
// There is no point for this X value in this series, so we
// insert a dummy point in order for the areas to be drawn
// correctly.
} else {
// Loop down the stack to find the series below this one that has
// a value (#1991)
for (i = series.index; i <= yAxis.series.length; i++) {
stackPoint = stack[x].points[i + ',' + x];
if (stackPoint) {
y = stackPoint[1];
break;
}
}
plotX = xAxis.translate(x);
plotY = yAxis.toPixels(y, true);
segment.push({
y: null,
plotX: plotX,
clientX: plotX,
plotY: plotY,
yBottom: plotY,
onMouseOver: noop
});
}
});
if (segment.length) {
segments.push(segment);
}
} else {
Series.prototype.getSegments.call(this);
segments = this.segments;
}
this.segments = segments;
} | javascript | function () {
var series = this,
segments = [],
segment = [],
keys = [],
xAxis = this.xAxis,
yAxis = this.yAxis,
stack = yAxis.stacks[this.stackKey],
pointMap = {},
plotX,
plotY,
points = this.points,
connectNulls = this.options.connectNulls,
i,
x;
if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue
// Create a map where we can quickly look up the points by their X value.
for (i = 0; i < points.length; i++) {
pointMap[points[i].x] = points[i];
}
// Sort the keys (#1651)
for (x in stack) {
if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336)
keys.push(+x);
}
}
keys.sort(function (a, b) {
return a - b;
});
each(keys, function (x) {
var y = 0,
stackPoint;
if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836
return;
// The point exists, push it to the segment
} else if (pointMap[x]) {
segment.push(pointMap[x]);
// There is no point for this X value in this series, so we
// insert a dummy point in order for the areas to be drawn
// correctly.
} else {
// Loop down the stack to find the series below this one that has
// a value (#1991)
for (i = series.index; i <= yAxis.series.length; i++) {
stackPoint = stack[x].points[i + ',' + x];
if (stackPoint) {
y = stackPoint[1];
break;
}
}
plotX = xAxis.translate(x);
plotY = yAxis.toPixels(y, true);
segment.push({
y: null,
plotX: plotX,
clientX: plotX,
plotY: plotY,
yBottom: plotY,
onMouseOver: noop
});
}
});
if (segment.length) {
segments.push(segment);
}
} else {
Series.prototype.getSegments.call(this);
segments = this.segments;
}
this.segments = segments;
} | [
"function",
"(",
")",
"{",
"var",
"series",
"=",
"this",
",",
"segments",
"=",
"[",
"]",
",",
"segment",
"=",
"[",
"]",
",",
"keys",
"=",
"[",
"]",
",",
"xAxis",
"=",
"this",
".",
"xAxis",
",",
"yAxis",
"=",
"this",
".",
"yAxis",
",",
"stack",
"=",
"yAxis",
".",
"stacks",
"[",
"this",
".",
"stackKey",
"]",
",",
"pointMap",
"=",
"{",
"}",
",",
"plotX",
",",
"plotY",
",",
"points",
"=",
"this",
".",
"points",
",",
"connectNulls",
"=",
"this",
".",
"options",
".",
"connectNulls",
",",
"i",
",",
"x",
";",
"if",
"(",
"this",
".",
"options",
".",
"stacking",
"&&",
"!",
"this",
".",
"cropped",
")",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"points",
".",
"length",
";",
"i",
"++",
")",
"{",
"pointMap",
"[",
"points",
"[",
"i",
"]",
".",
"x",
"]",
"=",
"points",
"[",
"i",
"]",
";",
"}",
"for",
"(",
"x",
"in",
"stack",
")",
"{",
"if",
"(",
"stack",
"[",
"x",
"]",
".",
"total",
"!==",
"null",
")",
"{",
"keys",
".",
"push",
"(",
"+",
"x",
")",
";",
"}",
"}",
"keys",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"a",
"-",
"b",
";",
"}",
")",
";",
"each",
"(",
"keys",
",",
"function",
"(",
"x",
")",
"{",
"var",
"y",
"=",
"0",
",",
"stackPoint",
";",
"if",
"(",
"connectNulls",
"&&",
"(",
"!",
"pointMap",
"[",
"x",
"]",
"||",
"pointMap",
"[",
"x",
"]",
".",
"y",
"===",
"null",
")",
")",
"{",
"return",
";",
"}",
"else",
"if",
"(",
"pointMap",
"[",
"x",
"]",
")",
"{",
"segment",
".",
"push",
"(",
"pointMap",
"[",
"x",
"]",
")",
";",
"}",
"else",
"{",
"for",
"(",
"i",
"=",
"series",
".",
"index",
";",
"i",
"<=",
"yAxis",
".",
"series",
".",
"length",
";",
"i",
"++",
")",
"{",
"stackPoint",
"=",
"stack",
"[",
"x",
"]",
".",
"points",
"[",
"i",
"+",
"','",
"+",
"x",
"]",
";",
"if",
"(",
"stackPoint",
")",
"{",
"y",
"=",
"stackPoint",
"[",
"1",
"]",
";",
"break",
";",
"}",
"}",
"plotX",
"=",
"xAxis",
".",
"translate",
"(",
"x",
")",
";",
"plotY",
"=",
"yAxis",
".",
"toPixels",
"(",
"y",
",",
"true",
")",
";",
"segment",
".",
"push",
"(",
"{",
"y",
":",
"null",
",",
"plotX",
":",
"plotX",
",",
"clientX",
":",
"plotX",
",",
"plotY",
":",
"plotY",
",",
"yBottom",
":",
"plotY",
",",
"onMouseOver",
":",
"noop",
"}",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"segment",
".",
"length",
")",
"{",
"segments",
".",
"push",
"(",
"segment",
")",
";",
"}",
"}",
"else",
"{",
"Series",
".",
"prototype",
".",
"getSegments",
".",
"call",
"(",
"this",
")",
";",
"segments",
"=",
"this",
".",
"segments",
";",
"}",
"this",
".",
"segments",
"=",
"segments",
";",
"}"
] | For stacks, don't split segments on null values. Instead, draw null values with
no marker. Also insert dummy points for any X position that exists in other series
in the stack. | [
"For",
"stacks",
"don",
"t",
"split",
"segments",
"on",
"null",
"values",
".",
"Instead",
"draw",
"null",
"values",
"with",
"no",
"marker",
".",
"Also",
"insert",
"dummy",
"points",
"for",
"any",
"X",
"position",
"that",
"exists",
"in",
"other",
"series",
"in",
"the",
"stack",
"."
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L66731-L66812 | train |
|
duniter/duniter-ui | public/libraries.js | function (segment) {
var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method
areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path
i,
options = this.options,
segLength = segmentPath.length,
translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181
yBottom;
if (segLength === 3) { // for animation from 1 to two points
areaSegmentPath.push(L, segmentPath[1], segmentPath[2]);
}
if (options.stacking && !this.closedStacks) {
// Follow stack back. Todo: implement areaspline. A general solution could be to
// reverse the entire graphPath of the previous series, though may be hard with
// splines and with series with different extremes
for (i = segment.length - 1; i >= 0; i--) {
yBottom = pick(segment[i].yBottom, translatedThreshold);
// step line?
if (i < segment.length - 1 && options.step) {
areaSegmentPath.push(segment[i + 1].plotX, yBottom);
}
areaSegmentPath.push(segment[i].plotX, yBottom);
}
} else { // follow zero line back
this.closeSegment(areaSegmentPath, segment, translatedThreshold);
}
this.areaPath = this.areaPath.concat(areaSegmentPath);
return segmentPath;
} | javascript | function (segment) {
var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method
areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path
i,
options = this.options,
segLength = segmentPath.length,
translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181
yBottom;
if (segLength === 3) { // for animation from 1 to two points
areaSegmentPath.push(L, segmentPath[1], segmentPath[2]);
}
if (options.stacking && !this.closedStacks) {
// Follow stack back. Todo: implement areaspline. A general solution could be to
// reverse the entire graphPath of the previous series, though may be hard with
// splines and with series with different extremes
for (i = segment.length - 1; i >= 0; i--) {
yBottom = pick(segment[i].yBottom, translatedThreshold);
// step line?
if (i < segment.length - 1 && options.step) {
areaSegmentPath.push(segment[i + 1].plotX, yBottom);
}
areaSegmentPath.push(segment[i].plotX, yBottom);
}
} else { // follow zero line back
this.closeSegment(areaSegmentPath, segment, translatedThreshold);
}
this.areaPath = this.areaPath.concat(areaSegmentPath);
return segmentPath;
} | [
"function",
"(",
"segment",
")",
"{",
"var",
"segmentPath",
"=",
"Series",
".",
"prototype",
".",
"getSegmentPath",
".",
"call",
"(",
"this",
",",
"segment",
")",
",",
"areaSegmentPath",
"=",
"[",
"]",
".",
"concat",
"(",
"segmentPath",
")",
",",
"i",
",",
"options",
"=",
"this",
".",
"options",
",",
"segLength",
"=",
"segmentPath",
".",
"length",
",",
"translatedThreshold",
"=",
"this",
".",
"yAxis",
".",
"getThreshold",
"(",
"options",
".",
"threshold",
")",
",",
"yBottom",
";",
"if",
"(",
"segLength",
"===",
"3",
")",
"{",
"areaSegmentPath",
".",
"push",
"(",
"L",
",",
"segmentPath",
"[",
"1",
"]",
",",
"segmentPath",
"[",
"2",
"]",
")",
";",
"}",
"if",
"(",
"options",
".",
"stacking",
"&&",
"!",
"this",
".",
"closedStacks",
")",
"{",
"for",
"(",
"i",
"=",
"segment",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"yBottom",
"=",
"pick",
"(",
"segment",
"[",
"i",
"]",
".",
"yBottom",
",",
"translatedThreshold",
")",
";",
"if",
"(",
"i",
"<",
"segment",
".",
"length",
"-",
"1",
"&&",
"options",
".",
"step",
")",
"{",
"areaSegmentPath",
".",
"push",
"(",
"segment",
"[",
"i",
"+",
"1",
"]",
".",
"plotX",
",",
"yBottom",
")",
";",
"}",
"areaSegmentPath",
".",
"push",
"(",
"segment",
"[",
"i",
"]",
".",
"plotX",
",",
"yBottom",
")",
";",
"}",
"}",
"else",
"{",
"this",
".",
"closeSegment",
"(",
"areaSegmentPath",
",",
"segment",
",",
"translatedThreshold",
")",
";",
"}",
"this",
".",
"areaPath",
"=",
"this",
".",
"areaPath",
".",
"concat",
"(",
"areaSegmentPath",
")",
";",
"return",
"segmentPath",
";",
"}"
] | Extend the base Series getSegmentPath method by adding the path for the area.
This path is pushed to the series.areaPath property. | [
"Extend",
"the",
"base",
"Series",
"getSegmentPath",
"method",
"by",
"adding",
"the",
"path",
"for",
"the",
"area",
".",
"This",
"path",
"is",
"pushed",
"to",
"the",
"series",
".",
"areaPath",
"property",
"."
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L66818-L66853 | train |
|
duniter/duniter-ui | public/libraries.js | function () {
var chart = this.series.chart,
hoverPoints = chart.hoverPoints;
this.firePointEvent('mouseOut');
if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240
this.setState();
chart.hoverPoint = null;
}
} | javascript | function () {
var chart = this.series.chart,
hoverPoints = chart.hoverPoints;
this.firePointEvent('mouseOut');
if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240
this.setState();
chart.hoverPoint = null;
}
} | [
"function",
"(",
")",
"{",
"var",
"chart",
"=",
"this",
".",
"series",
".",
"chart",
",",
"hoverPoints",
"=",
"chart",
".",
"hoverPoints",
";",
"this",
".",
"firePointEvent",
"(",
"'mouseOut'",
")",
";",
"if",
"(",
"!",
"hoverPoints",
"||",
"inArray",
"(",
"this",
",",
"hoverPoints",
")",
"===",
"-",
"1",
")",
"{",
"this",
".",
"setState",
"(",
")",
";",
"chart",
".",
"hoverPoint",
"=",
"null",
";",
"}",
"}"
] | Runs on mouse out from the point | [
"Runs",
"on",
"mouse",
"out",
"from",
"the",
"point"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L69093-L69103 | train |
|
duniter/duniter-ui | public/libraries.js | onScroll | function onScroll() {
// unique tick id
++ticks;
// viewport rectangle
var top = jWindow.scrollTop(),
left = jWindow.scrollLeft(),
right = left + jWindow.width(),
bottom = top + jWindow.height();
// determine which elements are in view
// + 60 accounts for fixed nav
var intersections = findElements(top+offset.top + 200, right+offset.right, bottom+offset.bottom, left+offset.left);
$.each(intersections, function(i, element) {
var lastTick = element.data('scrollSpy:ticks');
if (typeof lastTick != 'number') {
// entered into view
element.triggerHandler('scrollSpy:enter');
}
// update tick id
element.data('scrollSpy:ticks', ticks);
});
// determine which elements are no longer in view
$.each(elementsInView, function(i, element) {
var lastTick = element.data('scrollSpy:ticks');
if (typeof lastTick == 'number' && lastTick !== ticks) {
// exited from view
element.triggerHandler('scrollSpy:exit');
element.data('scrollSpy:ticks', null);
}
});
// remember elements in view for next tick
elementsInView = intersections;
} | javascript | function onScroll() {
// unique tick id
++ticks;
// viewport rectangle
var top = jWindow.scrollTop(),
left = jWindow.scrollLeft(),
right = left + jWindow.width(),
bottom = top + jWindow.height();
// determine which elements are in view
// + 60 accounts for fixed nav
var intersections = findElements(top+offset.top + 200, right+offset.right, bottom+offset.bottom, left+offset.left);
$.each(intersections, function(i, element) {
var lastTick = element.data('scrollSpy:ticks');
if (typeof lastTick != 'number') {
// entered into view
element.triggerHandler('scrollSpy:enter');
}
// update tick id
element.data('scrollSpy:ticks', ticks);
});
// determine which elements are no longer in view
$.each(elementsInView, function(i, element) {
var lastTick = element.data('scrollSpy:ticks');
if (typeof lastTick == 'number' && lastTick !== ticks) {
// exited from view
element.triggerHandler('scrollSpy:exit');
element.data('scrollSpy:ticks', null);
}
});
// remember elements in view for next tick
elementsInView = intersections;
} | [
"function",
"onScroll",
"(",
")",
"{",
"++",
"ticks",
";",
"var",
"top",
"=",
"jWindow",
".",
"scrollTop",
"(",
")",
",",
"left",
"=",
"jWindow",
".",
"scrollLeft",
"(",
")",
",",
"right",
"=",
"left",
"+",
"jWindow",
".",
"width",
"(",
")",
",",
"bottom",
"=",
"top",
"+",
"jWindow",
".",
"height",
"(",
")",
";",
"var",
"intersections",
"=",
"findElements",
"(",
"top",
"+",
"offset",
".",
"top",
"+",
"200",
",",
"right",
"+",
"offset",
".",
"right",
",",
"bottom",
"+",
"offset",
".",
"bottom",
",",
"left",
"+",
"offset",
".",
"left",
")",
";",
"$",
".",
"each",
"(",
"intersections",
",",
"function",
"(",
"i",
",",
"element",
")",
"{",
"var",
"lastTick",
"=",
"element",
".",
"data",
"(",
"'scrollSpy:ticks'",
")",
";",
"if",
"(",
"typeof",
"lastTick",
"!=",
"'number'",
")",
"{",
"element",
".",
"triggerHandler",
"(",
"'scrollSpy:enter'",
")",
";",
"}",
"element",
".",
"data",
"(",
"'scrollSpy:ticks'",
",",
"ticks",
")",
";",
"}",
")",
";",
"$",
".",
"each",
"(",
"elementsInView",
",",
"function",
"(",
"i",
",",
"element",
")",
"{",
"var",
"lastTick",
"=",
"element",
".",
"data",
"(",
"'scrollSpy:ticks'",
")",
";",
"if",
"(",
"typeof",
"lastTick",
"==",
"'number'",
"&&",
"lastTick",
"!==",
"ticks",
")",
"{",
"element",
".",
"triggerHandler",
"(",
"'scrollSpy:exit'",
")",
";",
"element",
".",
"data",
"(",
"'scrollSpy:ticks'",
",",
"null",
")",
";",
"}",
"}",
")",
";",
"elementsInView",
"=",
"intersections",
";",
"}"
] | Called when the user scrolls the window | [
"Called",
"when",
"the",
"user",
"scrolls",
"the",
"window"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L71936-L71973 | train |
duniter/duniter-ui | public/libraries.js | function(e){
// TAB - switch to another input
if(e.which == 9){
$newSelect.trigger('close');
return;
}
// ARROW DOWN WHEN SELECT IS CLOSED - open select options
if(e.which == 40 && !options.is(':visible')){
$newSelect.trigger('open');
return;
}
// ENTER WHEN SELECT IS CLOSED - submit form
if(e.which == 13 && !options.is(':visible')){
return;
}
e.preventDefault();
// CASE WHEN USER TYPE LETTERS
var letter = String.fromCharCode(e.which).toLowerCase(),
nonLetters = [9,13,27,38,40];
if (letter && (nonLetters.indexOf(e.which) === -1)) {
filterQuery.push(letter);
var string = filterQuery.join(''),
newOption = options.find('li').filter(function() {
return $(this).text().toLowerCase().indexOf(string) === 0;
})[0];
if (newOption) {
activateOption(options, newOption);
}
}
// ENTER - select option and close when select options are opened
if (e.which == 13) {
var activeOption = options.find('li.selected:not(.disabled)')[0];
if(activeOption){
$(activeOption).trigger('click');
if (!multiple) {
$newSelect.trigger('close');
}
}
}
// ARROW DOWN - move to next not disabled option
if (e.which == 40) {
if (options.find('li.selected').length) {
newOption = options.find('li.selected').next('li:not(.disabled)')[0];
} else {
newOption = options.find('li:not(.disabled)')[0];
}
activateOption(options, newOption);
}
// ESC - close options
if (e.which == 27) {
$newSelect.trigger('close');
}
// ARROW UP - move to previous not disabled option
if (e.which == 38) {
newOption = options.find('li.selected').prev('li:not(.disabled)')[0];
if(newOption)
activateOption(options, newOption);
}
// Automaticaly clean filter query so user can search again by starting letters
setTimeout(function(){ filterQuery = []; }, 1000);
} | javascript | function(e){
// TAB - switch to another input
if(e.which == 9){
$newSelect.trigger('close');
return;
}
// ARROW DOWN WHEN SELECT IS CLOSED - open select options
if(e.which == 40 && !options.is(':visible')){
$newSelect.trigger('open');
return;
}
// ENTER WHEN SELECT IS CLOSED - submit form
if(e.which == 13 && !options.is(':visible')){
return;
}
e.preventDefault();
// CASE WHEN USER TYPE LETTERS
var letter = String.fromCharCode(e.which).toLowerCase(),
nonLetters = [9,13,27,38,40];
if (letter && (nonLetters.indexOf(e.which) === -1)) {
filterQuery.push(letter);
var string = filterQuery.join(''),
newOption = options.find('li').filter(function() {
return $(this).text().toLowerCase().indexOf(string) === 0;
})[0];
if (newOption) {
activateOption(options, newOption);
}
}
// ENTER - select option and close when select options are opened
if (e.which == 13) {
var activeOption = options.find('li.selected:not(.disabled)')[0];
if(activeOption){
$(activeOption).trigger('click');
if (!multiple) {
$newSelect.trigger('close');
}
}
}
// ARROW DOWN - move to next not disabled option
if (e.which == 40) {
if (options.find('li.selected').length) {
newOption = options.find('li.selected').next('li:not(.disabled)')[0];
} else {
newOption = options.find('li:not(.disabled)')[0];
}
activateOption(options, newOption);
}
// ESC - close options
if (e.which == 27) {
$newSelect.trigger('close');
}
// ARROW UP - move to previous not disabled option
if (e.which == 38) {
newOption = options.find('li.selected').prev('li:not(.disabled)')[0];
if(newOption)
activateOption(options, newOption);
}
// Automaticaly clean filter query so user can search again by starting letters
setTimeout(function(){ filterQuery = []; }, 1000);
} | [
"function",
"(",
"e",
")",
"{",
"if",
"(",
"e",
".",
"which",
"==",
"9",
")",
"{",
"$newSelect",
".",
"trigger",
"(",
"'close'",
")",
";",
"return",
";",
"}",
"if",
"(",
"e",
".",
"which",
"==",
"40",
"&&",
"!",
"options",
".",
"is",
"(",
"':visible'",
")",
")",
"{",
"$newSelect",
".",
"trigger",
"(",
"'open'",
")",
";",
"return",
";",
"}",
"if",
"(",
"e",
".",
"which",
"==",
"13",
"&&",
"!",
"options",
".",
"is",
"(",
"':visible'",
")",
")",
"{",
"return",
";",
"}",
"e",
".",
"preventDefault",
"(",
")",
";",
"var",
"letter",
"=",
"String",
".",
"fromCharCode",
"(",
"e",
".",
"which",
")",
".",
"toLowerCase",
"(",
")",
",",
"nonLetters",
"=",
"[",
"9",
",",
"13",
",",
"27",
",",
"38",
",",
"40",
"]",
";",
"if",
"(",
"letter",
"&&",
"(",
"nonLetters",
".",
"indexOf",
"(",
"e",
".",
"which",
")",
"===",
"-",
"1",
")",
")",
"{",
"filterQuery",
".",
"push",
"(",
"letter",
")",
";",
"var",
"string",
"=",
"filterQuery",
".",
"join",
"(",
"''",
")",
",",
"newOption",
"=",
"options",
".",
"find",
"(",
"'li'",
")",
".",
"filter",
"(",
"function",
"(",
")",
"{",
"return",
"$",
"(",
"this",
")",
".",
"text",
"(",
")",
".",
"toLowerCase",
"(",
")",
".",
"indexOf",
"(",
"string",
")",
"===",
"0",
";",
"}",
")",
"[",
"0",
"]",
";",
"if",
"(",
"newOption",
")",
"{",
"activateOption",
"(",
"options",
",",
"newOption",
")",
";",
"}",
"}",
"if",
"(",
"e",
".",
"which",
"==",
"13",
")",
"{",
"var",
"activeOption",
"=",
"options",
".",
"find",
"(",
"'li.selected:not(.disabled)'",
")",
"[",
"0",
"]",
";",
"if",
"(",
"activeOption",
")",
"{",
"$",
"(",
"activeOption",
")",
".",
"trigger",
"(",
"'click'",
")",
";",
"if",
"(",
"!",
"multiple",
")",
"{",
"$newSelect",
".",
"trigger",
"(",
"'close'",
")",
";",
"}",
"}",
"}",
"if",
"(",
"e",
".",
"which",
"==",
"40",
")",
"{",
"if",
"(",
"options",
".",
"find",
"(",
"'li.selected'",
")",
".",
"length",
")",
"{",
"newOption",
"=",
"options",
".",
"find",
"(",
"'li.selected'",
")",
".",
"next",
"(",
"'li:not(.disabled)'",
")",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"newOption",
"=",
"options",
".",
"find",
"(",
"'li:not(.disabled)'",
")",
"[",
"0",
"]",
";",
"}",
"activateOption",
"(",
"options",
",",
"newOption",
")",
";",
"}",
"if",
"(",
"e",
".",
"which",
"==",
"27",
")",
"{",
"$newSelect",
".",
"trigger",
"(",
"'close'",
")",
";",
"}",
"if",
"(",
"e",
".",
"which",
"==",
"38",
")",
"{",
"newOption",
"=",
"options",
".",
"find",
"(",
"'li.selected'",
")",
".",
"prev",
"(",
"'li:not(.disabled)'",
")",
"[",
"0",
"]",
";",
"if",
"(",
"newOption",
")",
"activateOption",
"(",
"options",
",",
"newOption",
")",
";",
"}",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"filterQuery",
"=",
"[",
"]",
";",
"}",
",",
"1000",
")",
";",
"}"
] | Allow user to search by typing this array is cleared after 1 second | [
"Allow",
"user",
"to",
"search",
"by",
"typing",
"this",
"array",
"is",
"cleared",
"after",
"1",
"second"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L72625-L72696 | train |
|
duniter/duniter-ui | public/libraries.js | captionTransition | function captionTransition(caption, duration) {
if (caption.hasClass("center-align")) {
caption.velocity({opacity: 0, translateY: -100}, {duration: duration, queue: false});
}
else if (caption.hasClass("right-align")) {
caption.velocity({opacity: 0, translateX: 100}, {duration: duration, queue: false});
}
else if (caption.hasClass("left-align")) {
caption.velocity({opacity: 0, translateX: -100}, {duration: duration, queue: false});
}
} | javascript | function captionTransition(caption, duration) {
if (caption.hasClass("center-align")) {
caption.velocity({opacity: 0, translateY: -100}, {duration: duration, queue: false});
}
else if (caption.hasClass("right-align")) {
caption.velocity({opacity: 0, translateX: 100}, {duration: duration, queue: false});
}
else if (caption.hasClass("left-align")) {
caption.velocity({opacity: 0, translateX: -100}, {duration: duration, queue: false});
}
} | [
"function",
"captionTransition",
"(",
"caption",
",",
"duration",
")",
"{",
"if",
"(",
"caption",
".",
"hasClass",
"(",
"\"center-align\"",
")",
")",
"{",
"caption",
".",
"velocity",
"(",
"{",
"opacity",
":",
"0",
",",
"translateY",
":",
"-",
"100",
"}",
",",
"{",
"duration",
":",
"duration",
",",
"queue",
":",
"false",
"}",
")",
";",
"}",
"else",
"if",
"(",
"caption",
".",
"hasClass",
"(",
"\"right-align\"",
")",
")",
"{",
"caption",
".",
"velocity",
"(",
"{",
"opacity",
":",
"0",
",",
"translateX",
":",
"100",
"}",
",",
"{",
"duration",
":",
"duration",
",",
"queue",
":",
"false",
"}",
")",
";",
"}",
"else",
"if",
"(",
"caption",
".",
"hasClass",
"(",
"\"left-align\"",
")",
")",
"{",
"caption",
".",
"velocity",
"(",
"{",
"opacity",
":",
"0",
",",
"translateX",
":",
"-",
"100",
"}",
",",
"{",
"duration",
":",
"duration",
",",
"queue",
":",
"false",
"}",
")",
";",
"}",
"}"
] | Transitions the caption depending on alignment | [
"Transitions",
"the",
"caption",
"depending",
"on",
"alignment"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L72763-L72773 | train |
duniter/duniter-ui | public/libraries.js | moveToSlide | function moveToSlide(index) {
// Wrap around indices.
if (index >= $slides.length) index = 0;
else if (index < 0) index = $slides.length -1;
$active_index = $slider.find('.active').index();
// Only do if index changes
if ($active_index != index) {
$active = $slides.eq($active_index);
$caption = $active.find('.caption');
$active.removeClass('active');
$active.velocity({opacity: 0}, {duration: options.transition, queue: false, easing: 'easeOutQuad',
complete: function() {
$slides.not('.active').velocity({opacity: 0, translateX: 0, translateY: 0}, {duration: 0, queue: false});
} });
captionTransition($caption, options.transition);
// Update indicators
if (options.indicators) {
$indicators.eq($active_index).removeClass('active');
}
$slides.eq(index).velocity({opacity: 1}, {duration: options.transition, queue: false, easing: 'easeOutQuad'});
$slides.eq(index).find('.caption').velocity({opacity: 1, translateX: 0, translateY: 0}, {duration: options.transition, delay: options.transition, queue: false, easing: 'easeOutQuad'});
$slides.eq(index).addClass('active');
// Update indicators
if (options.indicators) {
$indicators.eq(index).addClass('active');
}
}
} | javascript | function moveToSlide(index) {
// Wrap around indices.
if (index >= $slides.length) index = 0;
else if (index < 0) index = $slides.length -1;
$active_index = $slider.find('.active').index();
// Only do if index changes
if ($active_index != index) {
$active = $slides.eq($active_index);
$caption = $active.find('.caption');
$active.removeClass('active');
$active.velocity({opacity: 0}, {duration: options.transition, queue: false, easing: 'easeOutQuad',
complete: function() {
$slides.not('.active').velocity({opacity: 0, translateX: 0, translateY: 0}, {duration: 0, queue: false});
} });
captionTransition($caption, options.transition);
// Update indicators
if (options.indicators) {
$indicators.eq($active_index).removeClass('active');
}
$slides.eq(index).velocity({opacity: 1}, {duration: options.transition, queue: false, easing: 'easeOutQuad'});
$slides.eq(index).find('.caption').velocity({opacity: 1, translateX: 0, translateY: 0}, {duration: options.transition, delay: options.transition, queue: false, easing: 'easeOutQuad'});
$slides.eq(index).addClass('active');
// Update indicators
if (options.indicators) {
$indicators.eq(index).addClass('active');
}
}
} | [
"function",
"moveToSlide",
"(",
"index",
")",
"{",
"if",
"(",
"index",
">=",
"$slides",
".",
"length",
")",
"index",
"=",
"0",
";",
"else",
"if",
"(",
"index",
"<",
"0",
")",
"index",
"=",
"$slides",
".",
"length",
"-",
"1",
";",
"$active_index",
"=",
"$slider",
".",
"find",
"(",
"'.active'",
")",
".",
"index",
"(",
")",
";",
"if",
"(",
"$active_index",
"!=",
"index",
")",
"{",
"$active",
"=",
"$slides",
".",
"eq",
"(",
"$active_index",
")",
";",
"$caption",
"=",
"$active",
".",
"find",
"(",
"'.caption'",
")",
";",
"$active",
".",
"removeClass",
"(",
"'active'",
")",
";",
"$active",
".",
"velocity",
"(",
"{",
"opacity",
":",
"0",
"}",
",",
"{",
"duration",
":",
"options",
".",
"transition",
",",
"queue",
":",
"false",
",",
"easing",
":",
"'easeOutQuad'",
",",
"complete",
":",
"function",
"(",
")",
"{",
"$slides",
".",
"not",
"(",
"'.active'",
")",
".",
"velocity",
"(",
"{",
"opacity",
":",
"0",
",",
"translateX",
":",
"0",
",",
"translateY",
":",
"0",
"}",
",",
"{",
"duration",
":",
"0",
",",
"queue",
":",
"false",
"}",
")",
";",
"}",
"}",
")",
";",
"captionTransition",
"(",
"$caption",
",",
"options",
".",
"transition",
")",
";",
"if",
"(",
"options",
".",
"indicators",
")",
"{",
"$indicators",
".",
"eq",
"(",
"$active_index",
")",
".",
"removeClass",
"(",
"'active'",
")",
";",
"}",
"$slides",
".",
"eq",
"(",
"index",
")",
".",
"velocity",
"(",
"{",
"opacity",
":",
"1",
"}",
",",
"{",
"duration",
":",
"options",
".",
"transition",
",",
"queue",
":",
"false",
",",
"easing",
":",
"'easeOutQuad'",
"}",
")",
";",
"$slides",
".",
"eq",
"(",
"index",
")",
".",
"find",
"(",
"'.caption'",
")",
".",
"velocity",
"(",
"{",
"opacity",
":",
"1",
",",
"translateX",
":",
"0",
",",
"translateY",
":",
"0",
"}",
",",
"{",
"duration",
":",
"options",
".",
"transition",
",",
"delay",
":",
"options",
".",
"transition",
",",
"queue",
":",
"false",
",",
"easing",
":",
"'easeOutQuad'",
"}",
")",
";",
"$slides",
".",
"eq",
"(",
"index",
")",
".",
"addClass",
"(",
"'active'",
")",
";",
"if",
"(",
"options",
".",
"indicators",
")",
"{",
"$indicators",
".",
"eq",
"(",
"index",
")",
".",
"addClass",
"(",
"'active'",
")",
";",
"}",
"}",
"}"
] | This function will transition the slide to any index of the next slide | [
"This",
"function",
"will",
"transition",
"the",
"slide",
"to",
"any",
"index",
"of",
"the",
"next",
"slide"
] | de5c73aa4fe9add95711f3efba2f883645f315d1 | https://github.com/duniter/duniter-ui/blob/de5c73aa4fe9add95711f3efba2f883645f315d1/public/libraries.js#L72776-L72811 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.