id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
|---|---|---|---|---|---|---|---|---|---|---|---|
15,700
|
ninsuo/symfony-collection
|
jquery.collection.js
|
function (element) {
$(element).find(':input').each(function (index, inputObj) {
putFieldValue(inputObj, getFieldValue(inputObj), true);
});
}
|
javascript
|
function (element) {
$(element).find(':input').each(function (index, inputObj) {
putFieldValue(inputObj, getFieldValue(inputObj), true);
});
}
|
[
"function",
"(",
"element",
")",
"{",
"$",
"(",
"element",
")",
".",
"find",
"(",
"':input'",
")",
".",
"each",
"(",
"function",
"(",
"index",
",",
"inputObj",
")",
"{",
"putFieldValue",
"(",
"inputObj",
",",
"getFieldValue",
"(",
"inputObj",
")",
",",
"true",
")",
";",
"}",
")",
";",
"}"
] |
sometimes, setting a value will only be made in memory and not physically in the dom; and we need the full dom when we want to duplicate a field.
|
[
"sometimes",
"setting",
"a",
"value",
"will",
"only",
"be",
"made",
"in",
"memory",
"and",
"not",
"physically",
"in",
"the",
"dom",
";",
"and",
"we",
"need",
"the",
"full",
"dom",
"when",
"we",
"want",
"to",
"duplicate",
"a",
"field",
"."
] |
d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0
|
https://github.com/ninsuo/symfony-collection/blob/d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0/jquery.collection.js#L262-L266
|
|
15,701
|
ninsuo/symfony-collection
|
jquery.collection.js
|
function (collection, elements, settings, index) {
for (var i = index + 1; i < elements.length; i++) {
elements = swapElements(collection, elements, i - 1, i);
}
return collection.find(settings.elements_selector);
}
|
javascript
|
function (collection, elements, settings, index) {
for (var i = index + 1; i < elements.length; i++) {
elements = swapElements(collection, elements, i - 1, i);
}
return collection.find(settings.elements_selector);
}
|
[
"function",
"(",
"collection",
",",
"elements",
",",
"settings",
",",
"index",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"index",
"+",
"1",
";",
"i",
"<",
"elements",
".",
"length",
";",
"i",
"++",
")",
"{",
"elements",
"=",
"swapElements",
"(",
"collection",
",",
"elements",
",",
"i",
"-",
"1",
",",
"i",
")",
";",
"}",
"return",
"collection",
".",
"find",
"(",
"settings",
".",
"elements_selector",
")",
";",
"}"
] |
if we create an element at position 2, all element indexes from 2 to N should be increased. for example, in 0-A 1-B 2-C 3-D, adding X at position 1 will create 0-A 1-X 2-B 3-C 4-D
|
[
"if",
"we",
"create",
"an",
"element",
"at",
"position",
"2",
"all",
"element",
"indexes",
"from",
"2",
"to",
"N",
"should",
"be",
"increased",
".",
"for",
"example",
"in",
"0",
"-",
"A",
"1",
"-",
"B",
"2",
"-",
"C",
"3",
"-",
"D",
"adding",
"X",
"at",
"position",
"1",
"will",
"create",
"0",
"-",
"A",
"1",
"-",
"X",
"2",
"-",
"B",
"3",
"-",
"C",
"4",
"-",
"D"
] |
d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0
|
https://github.com/ninsuo/symfony-collection/blob/d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0/jquery.collection.js#L316-L321
|
|
15,702
|
ninsuo/symfony-collection
|
jquery.collection.js
|
function (collection, settings, elements, element, index) {
if (elements.length > settings.min && trueOrUndefined(settings.before_remove(collection, element))) {
var deletion = function () {
var toDelete = element;
if (!settings.preserve_names) {
elements = shiftElementsUp(collection, elements, settings, index);
toDelete = elements.last();
}
var backup = toDelete.clone({withDataAndEvents: true}).show();
toDelete.remove();
if (!trueOrUndefined(settings.after_remove(collection, backup))) {
var elementsParent = $(settings.elements_parent_selector);
elementsParent.find('> .' + settings.prefix + '-tmp').before(backup);
elements = collection.find(settings.elements_selector);
elements = shiftElementsDown(collection, elements, settings, index - 1);
}
if (settings.position_field_selector) {
doRewritePositions(settings, elements);
}
};
if (settings.fade_out) {
element.fadeOut('fast', function () {
deletion();
});
} else {
deletion();
}
}
return elements;
}
|
javascript
|
function (collection, settings, elements, element, index) {
if (elements.length > settings.min && trueOrUndefined(settings.before_remove(collection, element))) {
var deletion = function () {
var toDelete = element;
if (!settings.preserve_names) {
elements = shiftElementsUp(collection, elements, settings, index);
toDelete = elements.last();
}
var backup = toDelete.clone({withDataAndEvents: true}).show();
toDelete.remove();
if (!trueOrUndefined(settings.after_remove(collection, backup))) {
var elementsParent = $(settings.elements_parent_selector);
elementsParent.find('> .' + settings.prefix + '-tmp').before(backup);
elements = collection.find(settings.elements_selector);
elements = shiftElementsDown(collection, elements, settings, index - 1);
}
if (settings.position_field_selector) {
doRewritePositions(settings, elements);
}
};
if (settings.fade_out) {
element.fadeOut('fast', function () {
deletion();
});
} else {
deletion();
}
}
return elements;
}
|
[
"function",
"(",
"collection",
",",
"settings",
",",
"elements",
",",
"element",
",",
"index",
")",
"{",
"if",
"(",
"elements",
".",
"length",
">",
"settings",
".",
"min",
"&&",
"trueOrUndefined",
"(",
"settings",
".",
"before_remove",
"(",
"collection",
",",
"element",
")",
")",
")",
"{",
"var",
"deletion",
"=",
"function",
"(",
")",
"{",
"var",
"toDelete",
"=",
"element",
";",
"if",
"(",
"!",
"settings",
".",
"preserve_names",
")",
"{",
"elements",
"=",
"shiftElementsUp",
"(",
"collection",
",",
"elements",
",",
"settings",
",",
"index",
")",
";",
"toDelete",
"=",
"elements",
".",
"last",
"(",
")",
";",
"}",
"var",
"backup",
"=",
"toDelete",
".",
"clone",
"(",
"{",
"withDataAndEvents",
":",
"true",
"}",
")",
".",
"show",
"(",
")",
";",
"toDelete",
".",
"remove",
"(",
")",
";",
"if",
"(",
"!",
"trueOrUndefined",
"(",
"settings",
".",
"after_remove",
"(",
"collection",
",",
"backup",
")",
")",
")",
"{",
"var",
"elementsParent",
"=",
"$",
"(",
"settings",
".",
"elements_parent_selector",
")",
";",
"elementsParent",
".",
"find",
"(",
"'> .'",
"+",
"settings",
".",
"prefix",
"+",
"'-tmp'",
")",
".",
"before",
"(",
"backup",
")",
";",
"elements",
"=",
"collection",
".",
"find",
"(",
"settings",
".",
"elements_selector",
")",
";",
"elements",
"=",
"shiftElementsDown",
"(",
"collection",
",",
"elements",
",",
"settings",
",",
"index",
"-",
"1",
")",
";",
"}",
"if",
"(",
"settings",
".",
"position_field_selector",
")",
"{",
"doRewritePositions",
"(",
"settings",
",",
"elements",
")",
";",
"}",
"}",
";",
"if",
"(",
"settings",
".",
"fade_out",
")",
"{",
"element",
".",
"fadeOut",
"(",
"'fast'",
",",
"function",
"(",
")",
"{",
"deletion",
"(",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"deletion",
"(",
")",
";",
"}",
"}",
"return",
"elements",
";",
"}"
] |
removes the current element when clicking on a "delete" button and decrease all following indexes from 1 position.
|
[
"removes",
"the",
"current",
"element",
"when",
"clicking",
"on",
"a",
"delete",
"button",
"and",
"decrease",
"all",
"following",
"indexes",
"from",
"1",
"position",
"."
] |
d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0
|
https://github.com/ninsuo/symfony-collection/blob/d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0/jquery.collection.js#L598-L628
|
|
15,703
|
ninsuo/symfony-collection
|
jquery.collection.js
|
function (collection, settings, elements, element, oldIndex, newIndex) {
if (1 === Math.abs(newIndex - oldIndex)) {
elements = swapElements(collection, elements, oldIndex, newIndex);
if (!(newIndex - oldIndex > 0 ? trueOrUndefined(settings.after_up(collection, element)) : trueOrUndefined(settings.after_down(collection, element)))) {
elements = swapElements(collection, elements, newIndex, oldIndex);
}
} else {
if (oldIndex < newIndex) {
elements = swapElementsUp(collection, elements, settings, oldIndex, newIndex);
if (!(newIndex - oldIndex > 0 ? trueOrUndefined(settings.after_up(collection, element)) : trueOrUndefined(settings.after_down(collection, element)))) {
elements = swapElementsDown(collection, elements, settings, newIndex, oldIndex);
}
} else {
elements = swapElementsDown(collection, elements, settings, oldIndex, newIndex);
if (!(newIndex - oldIndex > 0 ? trueOrUndefined(settings.after_up(collection, element)) : trueOrUndefined(settings.after_down(collection, element)))) {
elements = swapElementsUp(collection, elements, settings, newIndex, oldIndex);
}
}
}
dumpCollectionActions(collection, settings, false);
if (settings.position_field_selector) {
return doRewritePositions(settings, elements);
}
return elements;
}
|
javascript
|
function (collection, settings, elements, element, oldIndex, newIndex) {
if (1 === Math.abs(newIndex - oldIndex)) {
elements = swapElements(collection, elements, oldIndex, newIndex);
if (!(newIndex - oldIndex > 0 ? trueOrUndefined(settings.after_up(collection, element)) : trueOrUndefined(settings.after_down(collection, element)))) {
elements = swapElements(collection, elements, newIndex, oldIndex);
}
} else {
if (oldIndex < newIndex) {
elements = swapElementsUp(collection, elements, settings, oldIndex, newIndex);
if (!(newIndex - oldIndex > 0 ? trueOrUndefined(settings.after_up(collection, element)) : trueOrUndefined(settings.after_down(collection, element)))) {
elements = swapElementsDown(collection, elements, settings, newIndex, oldIndex);
}
} else {
elements = swapElementsDown(collection, elements, settings, oldIndex, newIndex);
if (!(newIndex - oldIndex > 0 ? trueOrUndefined(settings.after_up(collection, element)) : trueOrUndefined(settings.after_down(collection, element)))) {
elements = swapElementsUp(collection, elements, settings, newIndex, oldIndex);
}
}
}
dumpCollectionActions(collection, settings, false);
if (settings.position_field_selector) {
return doRewritePositions(settings, elements);
}
return elements;
}
|
[
"function",
"(",
"collection",
",",
"settings",
",",
"elements",
",",
"element",
",",
"oldIndex",
",",
"newIndex",
")",
"{",
"if",
"(",
"1",
"===",
"Math",
".",
"abs",
"(",
"newIndex",
"-",
"oldIndex",
")",
")",
"{",
"elements",
"=",
"swapElements",
"(",
"collection",
",",
"elements",
",",
"oldIndex",
",",
"newIndex",
")",
";",
"if",
"(",
"!",
"(",
"newIndex",
"-",
"oldIndex",
">",
"0",
"?",
"trueOrUndefined",
"(",
"settings",
".",
"after_up",
"(",
"collection",
",",
"element",
")",
")",
":",
"trueOrUndefined",
"(",
"settings",
".",
"after_down",
"(",
"collection",
",",
"element",
")",
")",
")",
")",
"{",
"elements",
"=",
"swapElements",
"(",
"collection",
",",
"elements",
",",
"newIndex",
",",
"oldIndex",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"oldIndex",
"<",
"newIndex",
")",
"{",
"elements",
"=",
"swapElementsUp",
"(",
"collection",
",",
"elements",
",",
"settings",
",",
"oldIndex",
",",
"newIndex",
")",
";",
"if",
"(",
"!",
"(",
"newIndex",
"-",
"oldIndex",
">",
"0",
"?",
"trueOrUndefined",
"(",
"settings",
".",
"after_up",
"(",
"collection",
",",
"element",
")",
")",
":",
"trueOrUndefined",
"(",
"settings",
".",
"after_down",
"(",
"collection",
",",
"element",
")",
")",
")",
")",
"{",
"elements",
"=",
"swapElementsDown",
"(",
"collection",
",",
"elements",
",",
"settings",
",",
"newIndex",
",",
"oldIndex",
")",
";",
"}",
"}",
"else",
"{",
"elements",
"=",
"swapElementsDown",
"(",
"collection",
",",
"elements",
",",
"settings",
",",
"oldIndex",
",",
"newIndex",
")",
";",
"if",
"(",
"!",
"(",
"newIndex",
"-",
"oldIndex",
">",
"0",
"?",
"trueOrUndefined",
"(",
"settings",
".",
"after_up",
"(",
"collection",
",",
"element",
")",
")",
":",
"trueOrUndefined",
"(",
"settings",
".",
"after_down",
"(",
"collection",
",",
"element",
")",
")",
")",
")",
"{",
"elements",
"=",
"swapElementsUp",
"(",
"collection",
",",
"elements",
",",
"settings",
",",
"newIndex",
",",
"oldIndex",
")",
";",
"}",
"}",
"}",
"dumpCollectionActions",
"(",
"collection",
",",
"settings",
",",
"false",
")",
";",
"if",
"(",
"settings",
".",
"position_field_selector",
")",
"{",
"return",
"doRewritePositions",
"(",
"settings",
",",
"elements",
")",
";",
"}",
"return",
"elements",
";",
"}"
] |
move an element from a position to an arbitrary new position
|
[
"move",
"an",
"element",
"from",
"a",
"position",
"to",
"an",
"arbitrary",
"new",
"position"
] |
d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0
|
https://github.com/ninsuo/symfony-collection/blob/d5e6cbc7c7dc1f0509631c9bb6094fead0f6c8f0/jquery.collection.js#L665-L691
|
|
15,704
|
electron-userland/electron-installer-debian
|
src/dependencies.js
|
dependenciesForElectron
|
function dependenciesForElectron (electronVersion) {
return {
depends: common.getDepends(electronVersion, dependencyMap)
.concat(trashRequiresAsBoolean(electronVersion, dependencyMap)),
recommends: [
'pulseaudio | libasound2'
],
suggests: [
'gir1.2-gnomekeyring-1.0',
'libgnome-keyring0',
'lsb-release'
],
enhances: [
],
preDepends: [
]
}
}
|
javascript
|
function dependenciesForElectron (electronVersion) {
return {
depends: common.getDepends(electronVersion, dependencyMap)
.concat(trashRequiresAsBoolean(electronVersion, dependencyMap)),
recommends: [
'pulseaudio | libasound2'
],
suggests: [
'gir1.2-gnomekeyring-1.0',
'libgnome-keyring0',
'lsb-release'
],
enhances: [
],
preDepends: [
]
}
}
|
[
"function",
"dependenciesForElectron",
"(",
"electronVersion",
")",
"{",
"return",
"{",
"depends",
":",
"common",
".",
"getDepends",
"(",
"electronVersion",
",",
"dependencyMap",
")",
".",
"concat",
"(",
"trashRequiresAsBoolean",
"(",
"electronVersion",
",",
"dependencyMap",
")",
")",
",",
"recommends",
":",
"[",
"'pulseaudio | libasound2'",
"]",
",",
"suggests",
":",
"[",
"'gir1.2-gnomekeyring-1.0'",
",",
"'libgnome-keyring0'",
",",
"'lsb-release'",
"]",
",",
"enhances",
":",
"[",
"]",
",",
"preDepends",
":",
"[",
"]",
"}",
"}"
] |
The dependencies for Electron itself, given an Electron version.
|
[
"The",
"dependencies",
"for",
"Electron",
"itself",
"given",
"an",
"Electron",
"version",
"."
] |
4ad7774f4e172bf11992efe81d9d12704df693d4
|
https://github.com/electron-userland/electron-installer-debian/blob/4ad7774f4e172bf11992efe81d9d12704df693d4/src/dependencies.js#L33-L50
|
15,705
|
nearform/udaru
|
packages/udaru-hapi-server/index.js
|
logMessage
|
function logMessage (message) {
if (!process.send) {
console.log(message)
} else {
process.send(message)
}
}
|
javascript
|
function logMessage (message) {
if (!process.send) {
console.log(message)
} else {
process.send(message)
}
}
|
[
"function",
"logMessage",
"(",
"message",
")",
"{",
"if",
"(",
"!",
"process",
".",
"send",
")",
"{",
"console",
".",
"log",
"(",
"message",
")",
"}",
"else",
"{",
"process",
".",
"send",
"(",
"message",
")",
"}",
"}"
] |
if forked as child, send output message via ipc to parent otherwise output to console
|
[
"if",
"forked",
"as",
"child",
"send",
"output",
"message",
"via",
"ipc",
"to",
"parent",
"otherwise",
"output",
"to",
"console"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-hapi-server/index.js#L12-L18
|
15,706
|
nearform/udaru
|
packages/udaru-core/lib/ops/teamOps.js
|
createTeam
|
function createTeam (params, opts, cb) {
if (!cb) {
cb = opts
}
if (!opts || typeof opts === 'function') {
opts = {}
}
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { createOnly } = opts
const tasks = [
(job, next) => {
const { id, name, description, metadata, parentId, organizationId, user } = params
// We should not use boom but return specific errors that will be then handled out side the udaru.js module
Joi.validate({ id, name, description, metadata, parentId, organizationId, user }, validationRules.createTeam, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.params = params
next()
},
insertTeam
]
if (!createOnly) {
tasks.push(
createDefaultPolicies,
createDefaultUser,
makeDefaultUserAdmin,
assignDefaultUserToTeam
)
}
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
teamOps.readTeam({ id: res.team.id, organizationId: params.organizationId }, cb)
})
return promise
}
|
javascript
|
function createTeam (params, opts, cb) {
if (!cb) {
cb = opts
}
if (!opts || typeof opts === 'function') {
opts = {}
}
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { createOnly } = opts
const tasks = [
(job, next) => {
const { id, name, description, metadata, parentId, organizationId, user } = params
// We should not use boom but return specific errors that will be then handled out side the udaru.js module
Joi.validate({ id, name, description, metadata, parentId, organizationId, user }, validationRules.createTeam, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.params = params
next()
},
insertTeam
]
if (!createOnly) {
tasks.push(
createDefaultPolicies,
createDefaultUser,
makeDefaultUserAdmin,
assignDefaultUserToTeam
)
}
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
teamOps.readTeam({ id: res.team.id, organizationId: params.organizationId }, cb)
})
return promise
}
|
[
"function",
"createTeam",
"(",
"params",
",",
"opts",
",",
"cb",
")",
"{",
"if",
"(",
"!",
"cb",
")",
"{",
"cb",
"=",
"opts",
"}",
"if",
"(",
"!",
"opts",
"||",
"typeof",
"opts",
"===",
"'function'",
")",
"{",
"opts",
"=",
"{",
"}",
"}",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"createOnly",
"}",
"=",
"opts",
"const",
"tasks",
"=",
"[",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"const",
"{",
"id",
",",
"name",
",",
"description",
",",
"metadata",
",",
"parentId",
",",
"organizationId",
",",
"user",
"}",
"=",
"params",
"// We should not use boom but return specific errors that will be then handled out side the udaru.js module",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"name",
",",
"description",
",",
"metadata",
",",
"parentId",
",",
"organizationId",
",",
"user",
"}",
",",
"validationRules",
".",
"createTeam",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"next",
"(",
")",
"}",
")",
"}",
",",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"job",
".",
"params",
"=",
"params",
"next",
"(",
")",
"}",
",",
"insertTeam",
"]",
"if",
"(",
"!",
"createOnly",
")",
"{",
"tasks",
".",
"push",
"(",
"createDefaultPolicies",
",",
"createDefaultUser",
",",
"makeDefaultUserAdmin",
",",
"assignDefaultUserToTeam",
")",
"}",
"db",
".",
"withTransaction",
"(",
"tasks",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"teamOps",
".",
"readTeam",
"(",
"{",
"id",
":",
"res",
".",
"team",
".",
"id",
",",
"organizationId",
":",
"params",
".",
"organizationId",
"}",
",",
"cb",
")",
"}",
")",
"return",
"promise",
"}"
] |
Creates a new team
@param {Object} params { id, name, description, metadata, parentId, organizationId, user } "metadata" optoinal
@param {Object} opts { createOnly }
@param {Function} cb
|
[
"Creates",
"a",
"new",
"team"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/teamOps.js#L436-L479
|
15,707
|
nearform/udaru
|
packages/udaru-core/lib/ops/teamOps.js
|
listTeamPolicies
|
function listTeamPolicies ({ id, page = 1, limit, organizationId }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
Joi.validate({ id, page, limit, organizationId }, validationRules.listTeamPolicies, function (err) {
if (err) return cb(Boom.badRequest(err))
const pageLimit = limit || _.get(config, 'authorization.defaultPageSize')
const offset = (page - 1) * pageLimit
const job = {
id: id,
organizationId: organizationId,
offset: offset,
limit: pageLimit,
team: {},
client: db
}
loadTeamPolicies(job, (err) => {
if (err) return cb(err)
const pageSize = pageLimit || job.totalPoliciesCount
const result = {
page: page,
limit: pageSize,
total: job.totalPoliciesCount,
data: job.team.policies
}
return cb(null, result)
})
})
return promise
}
|
javascript
|
function listTeamPolicies ({ id, page = 1, limit, organizationId }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
Joi.validate({ id, page, limit, organizationId }, validationRules.listTeamPolicies, function (err) {
if (err) return cb(Boom.badRequest(err))
const pageLimit = limit || _.get(config, 'authorization.defaultPageSize')
const offset = (page - 1) * pageLimit
const job = {
id: id,
organizationId: organizationId,
offset: offset,
limit: pageLimit,
team: {},
client: db
}
loadTeamPolicies(job, (err) => {
if (err) return cb(err)
const pageSize = pageLimit || job.totalPoliciesCount
const result = {
page: page,
limit: pageSize,
total: job.totalPoliciesCount,
data: job.team.policies
}
return cb(null, result)
})
})
return promise
}
|
[
"function",
"listTeamPolicies",
"(",
"{",
"id",
",",
"page",
"=",
"1",
",",
"limit",
",",
"organizationId",
"}",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"page",
",",
"limit",
",",
"organizationId",
"}",
",",
"validationRules",
".",
"listTeamPolicies",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"const",
"pageLimit",
"=",
"limit",
"||",
"_",
".",
"get",
"(",
"config",
",",
"'authorization.defaultPageSize'",
")",
"const",
"offset",
"=",
"(",
"page",
"-",
"1",
")",
"*",
"pageLimit",
"const",
"job",
"=",
"{",
"id",
":",
"id",
",",
"organizationId",
":",
"organizationId",
",",
"offset",
":",
"offset",
",",
"limit",
":",
"pageLimit",
",",
"team",
":",
"{",
"}",
",",
"client",
":",
"db",
"}",
"loadTeamPolicies",
"(",
"job",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"const",
"pageSize",
"=",
"pageLimit",
"||",
"job",
".",
"totalPoliciesCount",
"const",
"result",
"=",
"{",
"page",
":",
"page",
",",
"limit",
":",
"pageSize",
",",
"total",
":",
"job",
".",
"totalPoliciesCount",
",",
"data",
":",
"job",
".",
"team",
".",
"policies",
"}",
"return",
"cb",
"(",
"null",
",",
"result",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
Fetch a team's policies
@param {params} params { id, page, limit }
@param {Function} cb
|
[
"Fetch",
"a",
"team",
"s",
"policies"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/teamOps.js#L487-L520
|
15,708
|
nearform/udaru
|
packages/udaru-core/lib/ops/teamOps.js
|
readTeam
|
function readTeam ({ id, organizationId }, cb) {
const job = {
team: {}
}
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
async.applyEachSeries([
(job, next) => {
Joi.validate({ id, organizationId }, validationRules.readTeam, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.client = db
job.id = id
job.organizationId = organizationId
next()
},
loadTeams,
loadTeamUsers,
loadTeamPolicies
], job, (err) => {
if (err) return cb(err)
return cb(null, job.team)
})
return promise
}
|
javascript
|
function readTeam ({ id, organizationId }, cb) {
const job = {
team: {}
}
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
async.applyEachSeries([
(job, next) => {
Joi.validate({ id, organizationId }, validationRules.readTeam, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.client = db
job.id = id
job.organizationId = organizationId
next()
},
loadTeams,
loadTeamUsers,
loadTeamPolicies
], job, (err) => {
if (err) return cb(err)
return cb(null, job.team)
})
return promise
}
|
[
"function",
"readTeam",
"(",
"{",
"id",
",",
"organizationId",
"}",
",",
"cb",
")",
"{",
"const",
"job",
"=",
"{",
"team",
":",
"{",
"}",
"}",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"async",
".",
"applyEachSeries",
"(",
"[",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"organizationId",
"}",
",",
"validationRules",
".",
"readTeam",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"next",
"(",
")",
"}",
")",
"}",
",",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"job",
".",
"client",
"=",
"db",
"job",
".",
"id",
"=",
"id",
"job",
".",
"organizationId",
"=",
"organizationId",
"next",
"(",
")",
"}",
",",
"loadTeams",
",",
"loadTeamUsers",
",",
"loadTeamPolicies",
"]",
",",
"job",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"return",
"cb",
"(",
"null",
",",
"job",
".",
"team",
")",
"}",
")",
"return",
"promise",
"}"
] |
Fetch specific team data
@param {params} params { id, organizationId }
@param {Function} cb
|
[
"Fetch",
"specific",
"team",
"data"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/teamOps.js#L528-L558
|
15,709
|
nearform/udaru
|
packages/udaru-core/lib/ops/teamOps.js
|
updateTeam
|
function updateTeam (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, name, description, metadata, organizationId } = params
Joi.validate({ id, name, description, organizationId, metadata }, Joi.object().keys(validationRules.updateTeam).or('name', 'description'), function (err) {
if (err) return cb(Boom.badRequest(err))
const updates = []
const sql = SQL` UPDATE teams SET `
if (name) { updates.push(SQL`name = ${name}`) }
if (description) { updates.push(SQL`description = ${description}`) }
if (metadata) { updates.push(SQL`metadata = ${metadata}`) }
sql.append(sql.glue(updates, ' , '))
sql.append(SQL`
WHERE id = ${id}
AND org_id = ${organizationId}
`)
db.query(sql, (err, res) => {
if (utils.isUniqueViolationError(err)) return cb(Boom.conflict(err.detail))
if (err) return cb(Boom.badImplementation(err))
if (res.rowCount === 0) return cb(Boom.notFound(`Team with id ${id} could not be found`))
teamOps.readTeam({ id, organizationId }, cb)
})
})
return promise
}
|
javascript
|
function updateTeam (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, name, description, metadata, organizationId } = params
Joi.validate({ id, name, description, organizationId, metadata }, Joi.object().keys(validationRules.updateTeam).or('name', 'description'), function (err) {
if (err) return cb(Boom.badRequest(err))
const updates = []
const sql = SQL` UPDATE teams SET `
if (name) { updates.push(SQL`name = ${name}`) }
if (description) { updates.push(SQL`description = ${description}`) }
if (metadata) { updates.push(SQL`metadata = ${metadata}`) }
sql.append(sql.glue(updates, ' , '))
sql.append(SQL`
WHERE id = ${id}
AND org_id = ${organizationId}
`)
db.query(sql, (err, res) => {
if (utils.isUniqueViolationError(err)) return cb(Boom.conflict(err.detail))
if (err) return cb(Boom.badImplementation(err))
if (res.rowCount === 0) return cb(Boom.notFound(`Team with id ${id} could not be found`))
teamOps.readTeam({ id, organizationId }, cb)
})
})
return promise
}
|
[
"function",
"updateTeam",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"id",
",",
"name",
",",
"description",
",",
"metadata",
",",
"organizationId",
"}",
"=",
"params",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"name",
",",
"description",
",",
"organizationId",
",",
"metadata",
"}",
",",
"Joi",
".",
"object",
"(",
")",
".",
"keys",
"(",
"validationRules",
".",
"updateTeam",
")",
".",
"or",
"(",
"'name'",
",",
"'description'",
")",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"const",
"updates",
"=",
"[",
"]",
"const",
"sql",
"=",
"SQL",
"`",
"`",
"if",
"(",
"name",
")",
"{",
"updates",
".",
"push",
"(",
"SQL",
"`",
"${",
"name",
"}",
"`",
")",
"}",
"if",
"(",
"description",
")",
"{",
"updates",
".",
"push",
"(",
"SQL",
"`",
"${",
"description",
"}",
"`",
")",
"}",
"if",
"(",
"metadata",
")",
"{",
"updates",
".",
"push",
"(",
"SQL",
"`",
"${",
"metadata",
"}",
"`",
")",
"}",
"sql",
".",
"append",
"(",
"sql",
".",
"glue",
"(",
"updates",
",",
"' , '",
")",
")",
"sql",
".",
"append",
"(",
"SQL",
"`",
"${",
"id",
"}",
"${",
"organizationId",
"}",
"`",
")",
"db",
".",
"query",
"(",
"sql",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"utils",
".",
"isUniqueViolationError",
"(",
"err",
")",
")",
"return",
"cb",
"(",
"Boom",
".",
"conflict",
"(",
"err",
".",
"detail",
")",
")",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"if",
"(",
"res",
".",
"rowCount",
"===",
"0",
")",
"return",
"cb",
"(",
"Boom",
".",
"notFound",
"(",
"`",
"${",
"id",
"}",
"`",
")",
")",
"teamOps",
".",
"readTeam",
"(",
"{",
"id",
",",
"organizationId",
"}",
",",
"cb",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
Uodate team data
@param {Object} params {id, name, description, metadata, organizationId } "metadata" optional
@param {Function} cb
|
[
"Uodate",
"team",
"data"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/teamOps.js#L565-L595
|
15,710
|
nearform/udaru
|
packages/udaru-core/lib/ops/teamOps.js
|
deleteTeam
|
function deleteTeam (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
db.withTransaction([
(job, next) => {
const { id, organizationId } = params
Joi.validate({ id, organizationId }, validationRules.deleteTeam, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.teamId = params.id
job.organizationId = params.organizationId
next()
},
loadTeamDescendants,
deleteTeamsMembers,
deleteTeamsPolicies,
readDefaultPoliciesIds,
deleteDefaultPolicies,
removeTeams
], (err) => {
if (err) return cb(err)
cb()
})
return promise
}
|
javascript
|
function deleteTeam (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
db.withTransaction([
(job, next) => {
const { id, organizationId } = params
Joi.validate({ id, organizationId }, validationRules.deleteTeam, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.teamId = params.id
job.organizationId = params.organizationId
next()
},
loadTeamDescendants,
deleteTeamsMembers,
deleteTeamsPolicies,
readDefaultPoliciesIds,
deleteDefaultPolicies,
removeTeams
], (err) => {
if (err) return cb(err)
cb()
})
return promise
}
|
[
"function",
"deleteTeam",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"db",
".",
"withTransaction",
"(",
"[",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"const",
"{",
"id",
",",
"organizationId",
"}",
"=",
"params",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"organizationId",
"}",
",",
"validationRules",
".",
"deleteTeam",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"next",
"(",
")",
"}",
")",
"}",
",",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"job",
".",
"teamId",
"=",
"params",
".",
"id",
"job",
".",
"organizationId",
"=",
"params",
".",
"organizationId",
"next",
"(",
")",
"}",
",",
"loadTeamDescendants",
",",
"deleteTeamsMembers",
",",
"deleteTeamsPolicies",
",",
"readDefaultPoliciesIds",
",",
"deleteDefaultPolicies",
",",
"removeTeams",
"]",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"cb",
"(",
")",
"}",
")",
"return",
"promise",
"}"
] |
Delete specific team
@param {Object} params { id, organizationId }
@param {Function} cb [description]
|
[
"Delete",
"specific",
"team"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/teamOps.js#L603-L633
|
15,711
|
nearform/udaru
|
packages/udaru-core/lib/ops/teamOps.js
|
addTeamPolicies
|
function addTeamPolicies (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId } = params
Joi.validate({ id, organizationId, policies: params.policies }, validationRules.addTeamPolicies, function (err) {
if (err) return cb(Boom.badRequest(err))
const policies = utils.preparePolicies(params.policies)
utils.checkPoliciesOrg(db, policies, organizationId, (err) => {
if (err) return cb(err)
insertTeamPolicies({ client: db, teamId: id, policies }, (err, res) => {
if (err) return cb(err)
teamOps.readTeam({ id, organizationId }, cb)
})
})
})
return promise
}
|
javascript
|
function addTeamPolicies (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId } = params
Joi.validate({ id, organizationId, policies: params.policies }, validationRules.addTeamPolicies, function (err) {
if (err) return cb(Boom.badRequest(err))
const policies = utils.preparePolicies(params.policies)
utils.checkPoliciesOrg(db, policies, organizationId, (err) => {
if (err) return cb(err)
insertTeamPolicies({ client: db, teamId: id, policies }, (err, res) => {
if (err) return cb(err)
teamOps.readTeam({ id, organizationId }, cb)
})
})
})
return promise
}
|
[
"function",
"addTeamPolicies",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"id",
",",
"organizationId",
"}",
"=",
"params",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"organizationId",
",",
"policies",
":",
"params",
".",
"policies",
"}",
",",
"validationRules",
".",
"addTeamPolicies",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"const",
"policies",
"=",
"utils",
".",
"preparePolicies",
"(",
"params",
".",
"policies",
")",
"utils",
".",
"checkPoliciesOrg",
"(",
"db",
",",
"policies",
",",
"organizationId",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"insertTeamPolicies",
"(",
"{",
"client",
":",
"db",
",",
"teamId",
":",
"id",
",",
"policies",
"}",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"teamOps",
".",
"readTeam",
"(",
"{",
"id",
",",
"organizationId",
"}",
",",
"cb",
")",
"}",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
Add one or more policies to a team
@param {Object} params { id, organizationId, policies }
@param {Function} cb
|
[
"Add",
"one",
"or",
"more",
"policies",
"to",
"a",
"team"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/teamOps.js#L731-L753
|
15,712
|
nearform/udaru
|
packages/udaru-core/lib/ops/teamOps.js
|
replaceTeamPolicies
|
function replaceTeamPolicies (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId, policies } = params
const tasks = [
(job, next) => {
Joi.validate({ id, organizationId, policies }, validationRules.replaceTeamPolicies, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.teamId = id
job.organizationId = organizationId
job.policies = utils.preparePolicies(policies)
next()
},
(job, next) => {
utils.checkPoliciesOrg(job.client, job.policies, job.organizationId, next)
},
clearTeamPolicies,
insertTeamPolicies
]
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
teamOps.readTeam({ id, organizationId }, cb)
})
return promise
}
|
javascript
|
function replaceTeamPolicies (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId, policies } = params
const tasks = [
(job, next) => {
Joi.validate({ id, organizationId, policies }, validationRules.replaceTeamPolicies, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.teamId = id
job.organizationId = organizationId
job.policies = utils.preparePolicies(policies)
next()
},
(job, next) => {
utils.checkPoliciesOrg(job.client, job.policies, job.organizationId, next)
},
clearTeamPolicies,
insertTeamPolicies
]
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
teamOps.readTeam({ id, organizationId }, cb)
})
return promise
}
|
[
"function",
"replaceTeamPolicies",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"id",
",",
"organizationId",
",",
"policies",
"}",
"=",
"params",
"const",
"tasks",
"=",
"[",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"organizationId",
",",
"policies",
"}",
",",
"validationRules",
".",
"replaceTeamPolicies",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"next",
"(",
")",
"}",
")",
"}",
",",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"job",
".",
"teamId",
"=",
"id",
"job",
".",
"organizationId",
"=",
"organizationId",
"job",
".",
"policies",
"=",
"utils",
".",
"preparePolicies",
"(",
"policies",
")",
"next",
"(",
")",
"}",
",",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"utils",
".",
"checkPoliciesOrg",
"(",
"job",
".",
"client",
",",
"job",
".",
"policies",
",",
"job",
".",
"organizationId",
",",
"next",
")",
"}",
",",
"clearTeamPolicies",
",",
"insertTeamPolicies",
"]",
"db",
".",
"withTransaction",
"(",
"tasks",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"teamOps",
".",
"readTeam",
"(",
"{",
"id",
",",
"organizationId",
"}",
",",
"cb",
")",
"}",
")",
"return",
"promise",
"}"
] |
Replace team poilicies
@param {Object} params { id, organizationId, policies }
@param {Function} cb
|
[
"Replace",
"team",
"poilicies"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/teamOps.js#L794-L825
|
15,713
|
nearform/udaru
|
packages/udaru-core/lib/ops/teamOps.js
|
deleteTeamPolicies
|
function deleteTeamPolicies (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId } = params
Joi.validate({ id, organizationId }, validationRules.deleteTeamPolicies, function (err) {
if (err) return cb(Boom.badRequest(err))
clearTeamPolicies({ teamId: id, client: db }, (err, res) => {
if (err) return cb(err)
teamOps.readTeam({ id, organizationId }, cb)
})
})
return promise
}
|
javascript
|
function deleteTeamPolicies (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId } = params
Joi.validate({ id, organizationId }, validationRules.deleteTeamPolicies, function (err) {
if (err) return cb(Boom.badRequest(err))
clearTeamPolicies({ teamId: id, client: db }, (err, res) => {
if (err) return cb(err)
teamOps.readTeam({ id, organizationId }, cb)
})
})
return promise
}
|
[
"function",
"deleteTeamPolicies",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"id",
",",
"organizationId",
"}",
"=",
"params",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"organizationId",
"}",
",",
"validationRules",
".",
"deleteTeamPolicies",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"clearTeamPolicies",
"(",
"{",
"teamId",
":",
"id",
",",
"client",
":",
"db",
"}",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"teamOps",
".",
"readTeam",
"(",
"{",
"id",
",",
"organizationId",
"}",
",",
"cb",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
Remove all team's policies
@param {Object} params { id, organizationId }
@param {Function} cb
|
[
"Remove",
"all",
"team",
"s",
"policies"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/teamOps.js#L833-L849
|
15,714
|
nearform/udaru
|
packages/udaru-core/lib/ops/teamOps.js
|
deleteTeamPolicy
|
function deleteTeamPolicy (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { teamId, organizationId, policyId, instance } = params
Joi.validate({ teamId, organizationId, policyId, instance }, validationRules.deleteTeamPolicy, function (err) {
if (err) return cb(Boom.badRequest(err))
removeTeamPolicy({ client: db, teamId, policyId, instance }, (err, res) => {
if (err) return cb(err)
teamOps.readTeam({ id: teamId, organizationId }, cb)
})
})
return promise
}
|
javascript
|
function deleteTeamPolicy (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { teamId, organizationId, policyId, instance } = params
Joi.validate({ teamId, organizationId, policyId, instance }, validationRules.deleteTeamPolicy, function (err) {
if (err) return cb(Boom.badRequest(err))
removeTeamPolicy({ client: db, teamId, policyId, instance }, (err, res) => {
if (err) return cb(err)
teamOps.readTeam({ id: teamId, organizationId }, cb)
})
})
return promise
}
|
[
"function",
"deleteTeamPolicy",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"teamId",
",",
"organizationId",
",",
"policyId",
",",
"instance",
"}",
"=",
"params",
"Joi",
".",
"validate",
"(",
"{",
"teamId",
",",
"organizationId",
",",
"policyId",
",",
"instance",
"}",
",",
"validationRules",
".",
"deleteTeamPolicy",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"removeTeamPolicy",
"(",
"{",
"client",
":",
"db",
",",
"teamId",
",",
"policyId",
",",
"instance",
"}",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"teamOps",
".",
"readTeam",
"(",
"{",
"id",
":",
"teamId",
",",
"organizationId",
"}",
",",
"cb",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
Remove a specific team policy
@param {Object} params { userId, organizationId, policyId, instance } "instance" optional
@param {Function} cb
|
[
"Remove",
"a",
"specific",
"team",
"policy"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/teamOps.js#L857-L873
|
15,715
|
nearform/udaru
|
packages/udaru-core/lib/ops/teamOps.js
|
readTeamUsers
|
function readTeamUsers ({ id, page = 1, limit, organizationId }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
Joi.validate({ id, page, limit, organizationId }, validationRules.readTeamUsers, function (err) {
if (err) return cb(Boom.badRequest(err))
const pageLimit = limit || _.get(config, 'authorization.defaultPageSize')
const offset = (page - 1) * pageLimit
const job = {
id: id,
organizationId: organizationId,
offset: offset,
limit: pageLimit,
team: {},
client: db
}
loadTeamUsers(job, (err) => {
if (err) return cb(err)
const pageSize = pageLimit || job.totalUsersCount
const result = {
page: page,
limit: pageSize,
total: job.totalUsersCount,
data: job.team.users
}
return cb(null, result)
})
})
return promise
}
|
javascript
|
function readTeamUsers ({ id, page = 1, limit, organizationId }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
Joi.validate({ id, page, limit, organizationId }, validationRules.readTeamUsers, function (err) {
if (err) return cb(Boom.badRequest(err))
const pageLimit = limit || _.get(config, 'authorization.defaultPageSize')
const offset = (page - 1) * pageLimit
const job = {
id: id,
organizationId: organizationId,
offset: offset,
limit: pageLimit,
team: {},
client: db
}
loadTeamUsers(job, (err) => {
if (err) return cb(err)
const pageSize = pageLimit || job.totalUsersCount
const result = {
page: page,
limit: pageSize,
total: job.totalUsersCount,
data: job.team.users
}
return cb(null, result)
})
})
return promise
}
|
[
"function",
"readTeamUsers",
"(",
"{",
"id",
",",
"page",
"=",
"1",
",",
"limit",
",",
"organizationId",
"}",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"page",
",",
"limit",
",",
"organizationId",
"}",
",",
"validationRules",
".",
"readTeamUsers",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"const",
"pageLimit",
"=",
"limit",
"||",
"_",
".",
"get",
"(",
"config",
",",
"'authorization.defaultPageSize'",
")",
"const",
"offset",
"=",
"(",
"page",
"-",
"1",
")",
"*",
"pageLimit",
"const",
"job",
"=",
"{",
"id",
":",
"id",
",",
"organizationId",
":",
"organizationId",
",",
"offset",
":",
"offset",
",",
"limit",
":",
"pageLimit",
",",
"team",
":",
"{",
"}",
",",
"client",
":",
"db",
"}",
"loadTeamUsers",
"(",
"job",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"const",
"pageSize",
"=",
"pageLimit",
"||",
"job",
".",
"totalUsersCount",
"const",
"result",
"=",
"{",
"page",
":",
"page",
",",
"limit",
":",
"pageSize",
",",
"total",
":",
"job",
".",
"totalUsersCount",
",",
"data",
":",
"job",
".",
"team",
".",
"users",
"}",
"return",
"cb",
"(",
"null",
",",
"result",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
Fetch the users data from a team
@param {params} params { id, page, limit }
@param {Function} cb
|
[
"Fetch",
"the",
"users",
"data",
"from",
"a",
"team"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/teamOps.js#L881-L914
|
15,716
|
nearform/udaru
|
packages/udaru-core/lib/ops/teamOps.js
|
addUsersToTeam
|
function addUsersToTeam (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, users, organizationId } = params
const tasks = [
(job, next) => {
Joi.validate({ id, users, organizationId }, validationRules.addUsersToTeam, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.teamId = id
job.organizationId = organizationId
job.params = params
next()
},
(job, next) => {
utils.checkUsersOrg(job.client, job.params.users, job.organizationId, next)
},
checkTeamExists,
insertTeamMembers
]
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
teamOps.readTeam({ id, organizationId }, cb)
})
return promise
}
|
javascript
|
function addUsersToTeam (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, users, organizationId } = params
const tasks = [
(job, next) => {
Joi.validate({ id, users, organizationId }, validationRules.addUsersToTeam, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.teamId = id
job.organizationId = organizationId
job.params = params
next()
},
(job, next) => {
utils.checkUsersOrg(job.client, job.params.users, job.organizationId, next)
},
checkTeamExists,
insertTeamMembers
]
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
teamOps.readTeam({ id, organizationId }, cb)
})
return promise
}
|
[
"function",
"addUsersToTeam",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"id",
",",
"users",
",",
"organizationId",
"}",
"=",
"params",
"const",
"tasks",
"=",
"[",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"users",
",",
"organizationId",
"}",
",",
"validationRules",
".",
"addUsersToTeam",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"next",
"(",
")",
"}",
")",
"}",
",",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"job",
".",
"teamId",
"=",
"id",
"job",
".",
"organizationId",
"=",
"organizationId",
"job",
".",
"params",
"=",
"params",
"next",
"(",
")",
"}",
",",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"utils",
".",
"checkUsersOrg",
"(",
"job",
".",
"client",
",",
"job",
".",
"params",
".",
"users",
",",
"job",
".",
"organizationId",
",",
"next",
")",
"}",
",",
"checkTeamExists",
",",
"insertTeamMembers",
"]",
"db",
".",
"withTransaction",
"(",
"tasks",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"teamOps",
".",
"readTeam",
"(",
"{",
"id",
",",
"organizationId",
"}",
",",
"cb",
")",
"}",
")",
"return",
"promise",
"}"
] |
Add one or more users to a team
@param {Object} params { id, users, organizationId }
@param {Function} cb
|
[
"Add",
"one",
"or",
"more",
"users",
"to",
"a",
"team"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/teamOps.js#L922-L954
|
15,717
|
nearform/udaru
|
packages/udaru-core/lib/ops/teamOps.js
|
deleteTeamMembers
|
function deleteTeamMembers (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId } = params
const tasks = [
(job, next) => {
Joi.validate({ id, organizationId }, validationRules.deleteTeamMembers, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.teamId = id
job.organizationId = organizationId
next()
},
checkTeamExists,
deleteTeamUsers
]
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
cb()
})
return promise
}
|
javascript
|
function deleteTeamMembers (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId } = params
const tasks = [
(job, next) => {
Joi.validate({ id, organizationId }, validationRules.deleteTeamMembers, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.teamId = id
job.organizationId = organizationId
next()
},
checkTeamExists,
deleteTeamUsers
]
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
cb()
})
return promise
}
|
[
"function",
"deleteTeamMembers",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"id",
",",
"organizationId",
"}",
"=",
"params",
"const",
"tasks",
"=",
"[",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"organizationId",
"}",
",",
"validationRules",
".",
"deleteTeamMembers",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"next",
"(",
")",
"}",
")",
"}",
",",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"job",
".",
"teamId",
"=",
"id",
"job",
".",
"organizationId",
"=",
"organizationId",
"next",
"(",
")",
"}",
",",
"checkTeamExists",
",",
"deleteTeamUsers",
"]",
"db",
".",
"withTransaction",
"(",
"tasks",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"cb",
"(",
")",
"}",
")",
"return",
"promise",
"}"
] |
Delete team members
@param {Object} params { id, organizationId }
@param {Function} cb
|
[
"Delete",
"team",
"members"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/teamOps.js#L1003-L1033
|
15,718
|
nearform/udaru
|
packages/udaru-core/lib/ops/teamOps.js
|
search
|
function search (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify('data', 'total')
const { organizationId, query, type } = params
Joi.validate({ organizationId, query }, validationRules.searchTeam, function (err) {
if (err) {
return cb(Boom.badRequest(err))
}
const sqlQuery = SQL`
SELECT *
FROM teams
WHERE org_id=${organizationId}
AND (
`
if (!type || type === 'default') {
sqlQuery.append(SQL`
to_tsvector(name) || to_tsvector(description) @@ to_tsquery(${utils.toTsQuery(query)})
OR name LIKE(${'%' + query + '%'})
`)
} else if (type === 'exact') {
sqlQuery.append(SQL`
name = ${query}
`)
}
sqlQuery.append(SQL`)
ORDER BY id;
`)
db.query(sqlQuery, (err, result) => {
if (err) return cb(Boom.badImplementation(err))
return cb(null, result.rows.map(mapping.team), result.rows.length)
})
})
return promise
}
|
javascript
|
function search (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify('data', 'total')
const { organizationId, query, type } = params
Joi.validate({ organizationId, query }, validationRules.searchTeam, function (err) {
if (err) {
return cb(Boom.badRequest(err))
}
const sqlQuery = SQL`
SELECT *
FROM teams
WHERE org_id=${organizationId}
AND (
`
if (!type || type === 'default') {
sqlQuery.append(SQL`
to_tsvector(name) || to_tsvector(description) @@ to_tsquery(${utils.toTsQuery(query)})
OR name LIKE(${'%' + query + '%'})
`)
} else if (type === 'exact') {
sqlQuery.append(SQL`
name = ${query}
`)
}
sqlQuery.append(SQL`)
ORDER BY id;
`)
db.query(sqlQuery, (err, result) => {
if (err) return cb(Boom.badImplementation(err))
return cb(null, result.rows.map(mapping.team), result.rows.length)
})
})
return promise
}
|
[
"function",
"search",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
"'data'",
",",
"'total'",
")",
"const",
"{",
"organizationId",
",",
"query",
",",
"type",
"}",
"=",
"params",
"Joi",
".",
"validate",
"(",
"{",
"organizationId",
",",
"query",
"}",
",",
"validationRules",
".",
"searchTeam",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"}",
"const",
"sqlQuery",
"=",
"SQL",
"`",
"${",
"organizationId",
"}",
"`",
"if",
"(",
"!",
"type",
"||",
"type",
"===",
"'default'",
")",
"{",
"sqlQuery",
".",
"append",
"(",
"SQL",
"`",
"${",
"utils",
".",
"toTsQuery",
"(",
"query",
")",
"}",
"${",
"'%'",
"+",
"query",
"+",
"'%'",
"}",
"`",
")",
"}",
"else",
"if",
"(",
"type",
"===",
"'exact'",
")",
"{",
"sqlQuery",
".",
"append",
"(",
"SQL",
"`",
"${",
"query",
"}",
"`",
")",
"}",
"sqlQuery",
".",
"append",
"(",
"SQL",
"`",
"`",
")",
"db",
".",
"query",
"(",
"sqlQuery",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"return",
"cb",
"(",
"null",
",",
"result",
".",
"rows",
".",
"map",
"(",
"mapping",
".",
"team",
")",
",",
"result",
".",
"rows",
".",
"length",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
Search for team
@param {Object} params { organizationId, query }
@param {Function} cb
|
[
"Search",
"for",
"team"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/teamOps.js#L1078-L1116
|
15,719
|
nearform/udaru
|
packages/udaru-core/lib/ops/userOps.js
|
readUser
|
function readUser (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId } = params
let user
const tasks = []
tasks.push((next) => {
Joi.validate({ id, organizationId }, validationRules.readUser, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
})
tasks.push((next) => {
const sqlQuery = SQL`
SELECT id, name, org_id, metadata
FROM users
WHERE id = ${id}
AND org_id = ${organizationId}
`
db.query(sqlQuery, (err, result) => {
if (err) return next(Boom.badImplementation(err))
if (result.rowCount === 0) return next(Boom.notFound(`User ${id} not found`))
user = mapping.user(result.rows[0])
next()
})
})
tasks.push((next) => {
const sqlQuery = SQL`
SELECT teams.id, teams.name
FROM team_members mem, teams
WHERE mem.user_id = ${id} AND mem.team_id = teams.id
ORDER BY UPPER(teams.name)
`
db.query(sqlQuery, (err, result) => {
if (err) return next(Boom.badImplementation(err))
user.teams = result.rows.map(mapping.team.simple)
next()
})
})
tasks.push((next) => {
const sqlQuery = SQL`
SELECT pol.id, pol.name, pol.version, user_pol.variables, user_pol.policy_instance
FROM user_policies user_pol, policies pol
WHERE user_pol.user_id = ${id} AND user_pol.policy_id = pol.id
ORDER BY UPPER(pol.name)
`
db.query(sqlQuery, (err, result) => {
if (err) return next(Boom.badImplementation(err))
user.policies = result.rows.map(mapping.policy.simple)
next()
})
})
async.series(tasks, (err) => {
if (err) return cb(err)
return cb(null, user)
})
return promise
}
|
javascript
|
function readUser (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId } = params
let user
const tasks = []
tasks.push((next) => {
Joi.validate({ id, organizationId }, validationRules.readUser, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
})
tasks.push((next) => {
const sqlQuery = SQL`
SELECT id, name, org_id, metadata
FROM users
WHERE id = ${id}
AND org_id = ${organizationId}
`
db.query(sqlQuery, (err, result) => {
if (err) return next(Boom.badImplementation(err))
if (result.rowCount === 0) return next(Boom.notFound(`User ${id} not found`))
user = mapping.user(result.rows[0])
next()
})
})
tasks.push((next) => {
const sqlQuery = SQL`
SELECT teams.id, teams.name
FROM team_members mem, teams
WHERE mem.user_id = ${id} AND mem.team_id = teams.id
ORDER BY UPPER(teams.name)
`
db.query(sqlQuery, (err, result) => {
if (err) return next(Boom.badImplementation(err))
user.teams = result.rows.map(mapping.team.simple)
next()
})
})
tasks.push((next) => {
const sqlQuery = SQL`
SELECT pol.id, pol.name, pol.version, user_pol.variables, user_pol.policy_instance
FROM user_policies user_pol, policies pol
WHERE user_pol.user_id = ${id} AND user_pol.policy_id = pol.id
ORDER BY UPPER(pol.name)
`
db.query(sqlQuery, (err, result) => {
if (err) return next(Boom.badImplementation(err))
user.policies = result.rows.map(mapping.policy.simple)
next()
})
})
async.series(tasks, (err) => {
if (err) return cb(err)
return cb(null, user)
})
return promise
}
|
[
"function",
"readUser",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"id",
",",
"organizationId",
"}",
"=",
"params",
"let",
"user",
"const",
"tasks",
"=",
"[",
"]",
"tasks",
".",
"push",
"(",
"(",
"next",
")",
"=>",
"{",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"organizationId",
"}",
",",
"validationRules",
".",
"readUser",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"next",
"(",
")",
"}",
")",
"}",
")",
"tasks",
".",
"push",
"(",
"(",
"next",
")",
"=>",
"{",
"const",
"sqlQuery",
"=",
"SQL",
"`",
"${",
"id",
"}",
"${",
"organizationId",
"}",
"`",
"db",
".",
"query",
"(",
"sqlQuery",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"if",
"(",
"result",
".",
"rowCount",
"===",
"0",
")",
"return",
"next",
"(",
"Boom",
".",
"notFound",
"(",
"`",
"${",
"id",
"}",
"`",
")",
")",
"user",
"=",
"mapping",
".",
"user",
"(",
"result",
".",
"rows",
"[",
"0",
"]",
")",
"next",
"(",
")",
"}",
")",
"}",
")",
"tasks",
".",
"push",
"(",
"(",
"next",
")",
"=>",
"{",
"const",
"sqlQuery",
"=",
"SQL",
"`",
"${",
"id",
"}",
"`",
"db",
".",
"query",
"(",
"sqlQuery",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"user",
".",
"teams",
"=",
"result",
".",
"rows",
".",
"map",
"(",
"mapping",
".",
"team",
".",
"simple",
")",
"next",
"(",
")",
"}",
")",
"}",
")",
"tasks",
".",
"push",
"(",
"(",
"next",
")",
"=>",
"{",
"const",
"sqlQuery",
"=",
"SQL",
"`",
"${",
"id",
"}",
"`",
"db",
".",
"query",
"(",
"sqlQuery",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"user",
".",
"policies",
"=",
"result",
".",
"rows",
".",
"map",
"(",
"mapping",
".",
"policy",
".",
"simple",
")",
"next",
"(",
")",
"}",
")",
"}",
")",
"async",
".",
"series",
"(",
"tasks",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"return",
"cb",
"(",
"null",
",",
"user",
")",
"}",
")",
"return",
"promise",
"}"
] |
Get user details
@param {Object} params { id, organizationId }
@param {Function} cb
|
[
"Get",
"user",
"details"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/userOps.js#L190-L259
|
15,720
|
nearform/udaru
|
packages/udaru-core/lib/ops/userOps.js
|
updateUser
|
function updateUser (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId, name, metadata } = params
Joi.validate({ id, organizationId, name, metadata }, validationRules.updateUser, function (err) {
if (err) return cb(Boom.badRequest(err))
const sqlQuery = SQL`
UPDATE users
SET name = ${name},
metadata = ${metadata}
WHERE id = ${id}
AND org_id = ${organizationId}
`
db.query(sqlQuery, (err, result) => {
if (utils.isUniqueViolationError(err)) return cb(Boom.conflict(err.detail))
if (err) return cb(Boom.badImplementation(err))
if (result.rowCount === 0) return cb(Boom.notFound(`User ${id} not found`))
userOps.readUser({ id, organizationId }, cb)
})
})
return promise
}
|
javascript
|
function updateUser (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId, name, metadata } = params
Joi.validate({ id, organizationId, name, metadata }, validationRules.updateUser, function (err) {
if (err) return cb(Boom.badRequest(err))
const sqlQuery = SQL`
UPDATE users
SET name = ${name},
metadata = ${metadata}
WHERE id = ${id}
AND org_id = ${organizationId}
`
db.query(sqlQuery, (err, result) => {
if (utils.isUniqueViolationError(err)) return cb(Boom.conflict(err.detail))
if (err) return cb(Boom.badImplementation(err))
if (result.rowCount === 0) return cb(Boom.notFound(`User ${id} not found`))
userOps.readUser({ id, organizationId }, cb)
})
})
return promise
}
|
[
"function",
"updateUser",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"id",
",",
"organizationId",
",",
"name",
",",
"metadata",
"}",
"=",
"params",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"organizationId",
",",
"name",
",",
"metadata",
"}",
",",
"validationRules",
".",
"updateUser",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"const",
"sqlQuery",
"=",
"SQL",
"`",
"${",
"name",
"}",
"${",
"metadata",
"}",
"${",
"id",
"}",
"${",
"organizationId",
"}",
"`",
"db",
".",
"query",
"(",
"sqlQuery",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"utils",
".",
"isUniqueViolationError",
"(",
"err",
")",
")",
"return",
"cb",
"(",
"Boom",
".",
"conflict",
"(",
"err",
".",
"detail",
")",
")",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"if",
"(",
"result",
".",
"rowCount",
"===",
"0",
")",
"return",
"cb",
"(",
"Boom",
".",
"notFound",
"(",
"`",
"${",
"id",
"}",
"`",
")",
")",
"userOps",
".",
"readUser",
"(",
"{",
"id",
",",
"organizationId",
"}",
",",
"cb",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
Update user details
@param {Object} params { id, organizationId, name, metadata } "metadata" can be null
@param {Function} cb
|
[
"Update",
"user",
"details"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/userOps.js#L350-L376
|
15,721
|
nearform/udaru
|
packages/udaru-core/lib/ops/userOps.js
|
replaceUserPolicies
|
function replaceUserPolicies (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId, policies } = params
const tasks = [
(job, next) => {
Joi.validate({ id, organizationId, policies }, validationRules.replaceUserPolicies, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.id = id
job.organizationId = organizationId
job.policies = utils.preparePolicies(policies)
next()
},
checkUserOrg,
clearUserPolicies
]
if (policies.length > 0) {
tasks.push((job, next) => {
utils.checkPoliciesOrg(job.client, job.policies, job.organizationId, next)
})
tasks.push(insertUserPolicies)
}
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
userOps.readUser({ id, organizationId }, cb)
})
return promise
}
|
javascript
|
function replaceUserPolicies (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId, policies } = params
const tasks = [
(job, next) => {
Joi.validate({ id, organizationId, policies }, validationRules.replaceUserPolicies, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.id = id
job.organizationId = organizationId
job.policies = utils.preparePolicies(policies)
next()
},
checkUserOrg,
clearUserPolicies
]
if (policies.length > 0) {
tasks.push((job, next) => {
utils.checkPoliciesOrg(job.client, job.policies, job.organizationId, next)
})
tasks.push(insertUserPolicies)
}
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
userOps.readUser({ id, organizationId }, cb)
})
return promise
}
|
[
"function",
"replaceUserPolicies",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"id",
",",
"organizationId",
",",
"policies",
"}",
"=",
"params",
"const",
"tasks",
"=",
"[",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"organizationId",
",",
"policies",
"}",
",",
"validationRules",
".",
"replaceUserPolicies",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"next",
"(",
")",
"}",
")",
"}",
",",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"job",
".",
"id",
"=",
"id",
"job",
".",
"organizationId",
"=",
"organizationId",
"job",
".",
"policies",
"=",
"utils",
".",
"preparePolicies",
"(",
"policies",
")",
"next",
"(",
")",
"}",
",",
"checkUserOrg",
",",
"clearUserPolicies",
"]",
"if",
"(",
"policies",
".",
"length",
">",
"0",
")",
"{",
"tasks",
".",
"push",
"(",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"utils",
".",
"checkPoliciesOrg",
"(",
"job",
".",
"client",
",",
"job",
".",
"policies",
",",
"job",
".",
"organizationId",
",",
"next",
")",
"}",
")",
"tasks",
".",
"push",
"(",
"insertUserPolicies",
")",
"}",
"db",
".",
"withTransaction",
"(",
"tasks",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"userOps",
".",
"readUser",
"(",
"{",
"id",
",",
"organizationId",
"}",
",",
"cb",
")",
"}",
")",
"return",
"promise",
"}"
] |
Replace user policies
@param {Object} params { id, organizationId, policies }
@param {Function} cb
|
[
"Replace",
"user",
"policies"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/userOps.js#L384-L421
|
15,722
|
nearform/udaru
|
packages/udaru-core/lib/ops/userOps.js
|
deleteUserPolicy
|
function deleteUserPolicy (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { userId, organizationId, policyId, instance } = params
const tasks = [
(job, next) => {
Joi.validate({ userId, organizationId, policyId, instance }, validationRules.deleteUserPolicy, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.id = userId
job.policyId = policyId
job.organizationId = organizationId
job.instance = instance
next()
},
checkUserOrg,
removeUserPolicy
]
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
userOps.readUser({ id: userId, organizationId }, cb)
})
return promise
}
|
javascript
|
function deleteUserPolicy (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { userId, organizationId, policyId, instance } = params
const tasks = [
(job, next) => {
Joi.validate({ userId, organizationId, policyId, instance }, validationRules.deleteUserPolicy, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.id = userId
job.policyId = policyId
job.organizationId = organizationId
job.instance = instance
next()
},
checkUserOrg,
removeUserPolicy
]
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
userOps.readUser({ id: userId, organizationId }, cb)
})
return promise
}
|
[
"function",
"deleteUserPolicy",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"userId",
",",
"organizationId",
",",
"policyId",
",",
"instance",
"}",
"=",
"params",
"const",
"tasks",
"=",
"[",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"Joi",
".",
"validate",
"(",
"{",
"userId",
",",
"organizationId",
",",
"policyId",
",",
"instance",
"}",
",",
"validationRules",
".",
"deleteUserPolicy",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"next",
"(",
")",
"}",
")",
"}",
",",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"job",
".",
"id",
"=",
"userId",
"job",
".",
"policyId",
"=",
"policyId",
"job",
".",
"organizationId",
"=",
"organizationId",
"job",
".",
"instance",
"=",
"instance",
"next",
"(",
")",
"}",
",",
"checkUserOrg",
",",
"removeUserPolicy",
"]",
"db",
".",
"withTransaction",
"(",
"tasks",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"userOps",
".",
"readUser",
"(",
"{",
"id",
":",
"userId",
",",
"organizationId",
"}",
",",
"cb",
")",
"}",
")",
"return",
"promise",
"}"
] |
Remove one user policy
@param {Object} params { userId, organizationId, policyId }
@param {Function} cb
|
[
"Remove",
"one",
"user",
"policy"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/userOps.js#L557-L588
|
15,723
|
nearform/udaru
|
packages/udaru-core/lib/ops/userOps.js
|
insertUser
|
function insertUser (client, { id, name, organizationId, metadata }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
id = id || uuidV4()
const sqlQuery = SQL`
INSERT INTO users (
id, name, org_id, metadata
) VALUES (
${id}, ${name}, ${organizationId}, ${metadata}
)
RETURNING id
`
client.query(sqlQuery, (err, result) => {
if (utils.isUniqueViolationError(err)) return cb(Boom.conflict(err.detail))
if (err) return cb(Boom.badImplementation(err))
cb(null, result)
})
return promise
}
|
javascript
|
function insertUser (client, { id, name, organizationId, metadata }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
id = id || uuidV4()
const sqlQuery = SQL`
INSERT INTO users (
id, name, org_id, metadata
) VALUES (
${id}, ${name}, ${organizationId}, ${metadata}
)
RETURNING id
`
client.query(sqlQuery, (err, result) => {
if (utils.isUniqueViolationError(err)) return cb(Boom.conflict(err.detail))
if (err) return cb(Boom.badImplementation(err))
cb(null, result)
})
return promise
}
|
[
"function",
"insertUser",
"(",
"client",
",",
"{",
"id",
",",
"name",
",",
"organizationId",
",",
"metadata",
"}",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"id",
"=",
"id",
"||",
"uuidV4",
"(",
")",
"const",
"sqlQuery",
"=",
"SQL",
"`",
"${",
"id",
"}",
"${",
"name",
"}",
"${",
"organizationId",
"}",
"${",
"metadata",
"}",
"`",
"client",
".",
"query",
"(",
"sqlQuery",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"utils",
".",
"isUniqueViolationError",
"(",
"err",
")",
")",
"return",
"cb",
"(",
"Boom",
".",
"conflict",
"(",
"err",
".",
"detail",
")",
")",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"cb",
"(",
"null",
",",
"result",
")",
"}",
")",
"return",
"promise",
"}"
] |
Insert a new user into the database
@param {Object} client
@param {String|null} options.id
@param {String} options.name
@param {String} options.organizationId
@param {String} options.metadata (optional)
@param {Function} cb
|
[
"Insert",
"a",
"new",
"user",
"into",
"the",
"database"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/userOps.js#L600-L623
|
15,724
|
nearform/udaru
|
packages/udaru-core/lib/ops/userOps.js
|
listUserTeams
|
function listUserTeams ({ id, organizationId, page = 1, limit }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify('data', 'total')
Joi.validate({ id, organizationId, page, limit }, validationRules.listUserTeams, function (err) {
if (err) return cb(Boom.badRequest(err))
const offset = (page - 1) * limit
const job = {
id,
organizationId,
offset,
limit,
user: {},
client: db
}
readUserTeams(job, (err) => {
if (err) return cb(err)
return cb(null, job.user.teams, job.totalTeamsCount)
})
})
return promise
}
|
javascript
|
function listUserTeams ({ id, organizationId, page = 1, limit }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify('data', 'total')
Joi.validate({ id, organizationId, page, limit }, validationRules.listUserTeams, function (err) {
if (err) return cb(Boom.badRequest(err))
const offset = (page - 1) * limit
const job = {
id,
organizationId,
offset,
limit,
user: {},
client: db
}
readUserTeams(job, (err) => {
if (err) return cb(err)
return cb(null, job.user.teams, job.totalTeamsCount)
})
})
return promise
}
|
[
"function",
"listUserTeams",
"(",
"{",
"id",
",",
"organizationId",
",",
"page",
"=",
"1",
",",
"limit",
"}",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
"'data'",
",",
"'total'",
")",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"organizationId",
",",
"page",
",",
"limit",
"}",
",",
"validationRules",
".",
"listUserTeams",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"const",
"offset",
"=",
"(",
"page",
"-",
"1",
")",
"*",
"limit",
"const",
"job",
"=",
"{",
"id",
",",
"organizationId",
",",
"offset",
",",
"limit",
",",
"user",
":",
"{",
"}",
",",
"client",
":",
"db",
"}",
"readUserTeams",
"(",
"job",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"return",
"cb",
"(",
"null",
",",
"job",
".",
"user",
".",
"teams",
",",
"job",
".",
"totalTeamsCount",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
List the teams to which the user belongs to
Does not go recursively to parent teams
@param {Object} params { id, organizationId, limit, page }
@param {Function} cb
|
[
"List",
"the",
"teams",
"to",
"which",
"the",
"user",
"belongs",
"to",
"Does",
"not",
"go",
"recursively",
"to",
"parent",
"teams"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/userOps.js#L756-L781
|
15,725
|
nearform/udaru
|
packages/udaru-core/lib/ops/authorizeOps.js
|
batchAuthorization
|
function batchAuthorization ({ resourceBatch, userId, organizationId, sourceIpAddress, sourcePort }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
async.waterfall([
function validate (next) {
Joi.validate({ resourceBatch, userId, organizationId }, validationRules.batchAuthorization, badRequestWrap(next))
},
function listPolicies (result, next) {
policyOps.listAllUserPolicies({ userId, organizationId }, badImplementationWrap(next))
},
function check (policies, next) {
let context = buildContext({userId, organizationId, sourceIpAddress, sourcePort})
resourceBatch.forEach((rb) => {
rb.access = iam(policies).isAuthorized({resource: rb.resource, action: rb.action, context})
})
next(null, resourceBatch)
}
], function (err, access) {
cb(err, resourceBatch)
})
return promise
}
|
javascript
|
function batchAuthorization ({ resourceBatch, userId, organizationId, sourceIpAddress, sourcePort }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
async.waterfall([
function validate (next) {
Joi.validate({ resourceBatch, userId, organizationId }, validationRules.batchAuthorization, badRequestWrap(next))
},
function listPolicies (result, next) {
policyOps.listAllUserPolicies({ userId, organizationId }, badImplementationWrap(next))
},
function check (policies, next) {
let context = buildContext({userId, organizationId, sourceIpAddress, sourcePort})
resourceBatch.forEach((rb) => {
rb.access = iam(policies).isAuthorized({resource: rb.resource, action: rb.action, context})
})
next(null, resourceBatch)
}
], function (err, access) {
cb(err, resourceBatch)
})
return promise
}
|
[
"function",
"batchAuthorization",
"(",
"{",
"resourceBatch",
",",
"userId",
",",
"organizationId",
",",
"sourceIpAddress",
",",
"sourcePort",
"}",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"async",
".",
"waterfall",
"(",
"[",
"function",
"validate",
"(",
"next",
")",
"{",
"Joi",
".",
"validate",
"(",
"{",
"resourceBatch",
",",
"userId",
",",
"organizationId",
"}",
",",
"validationRules",
".",
"batchAuthorization",
",",
"badRequestWrap",
"(",
"next",
")",
")",
"}",
",",
"function",
"listPolicies",
"(",
"result",
",",
"next",
")",
"{",
"policyOps",
".",
"listAllUserPolicies",
"(",
"{",
"userId",
",",
"organizationId",
"}",
",",
"badImplementationWrap",
"(",
"next",
")",
")",
"}",
",",
"function",
"check",
"(",
"policies",
",",
"next",
")",
"{",
"let",
"context",
"=",
"buildContext",
"(",
"{",
"userId",
",",
"organizationId",
",",
"sourceIpAddress",
",",
"sourcePort",
"}",
")",
"resourceBatch",
".",
"forEach",
"(",
"(",
"rb",
")",
"=>",
"{",
"rb",
".",
"access",
"=",
"iam",
"(",
"policies",
")",
".",
"isAuthorized",
"(",
"{",
"resource",
":",
"rb",
".",
"resource",
",",
"action",
":",
"rb",
".",
"action",
",",
"context",
"}",
")",
"}",
")",
"next",
"(",
"null",
",",
"resourceBatch",
")",
"}",
"]",
",",
"function",
"(",
"err",
",",
"access",
")",
"{",
"cb",
"(",
"err",
",",
"resourceBatch",
")",
"}",
")",
"return",
"promise",
"}"
] |
Return if a user can perform an action on a certain resource
@param {Object} options { resource, action, userId, }
@param {Function} cb
|
[
"Return",
"if",
"a",
"user",
"can",
"perform",
"an",
"action",
"on",
"a",
"certain",
"resource"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/authorizeOps.js#L82-L106
|
15,726
|
nearform/udaru
|
packages/udaru-core/lib/ops/authorizeOps.js
|
listAuthorizationsOnResources
|
function listAuthorizationsOnResources ({ userId, resources, organizationId, sourceIpAddress, sourcePort }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
async.waterfall([
function validate (next) {
Joi.validate({ userId, resources, organizationId }, validationRules.listAuthorizationsOnResources, badRequestWrap(next))
},
function listPolicies (result, next) {
policyOps.listAllUserPolicies({ userId, organizationId }, badImplementationWrap(next))
},
function listAuthorizationsOnResources (policies, next) {
let context = buildContext({userId, organizationId, sourceIpAddress, sourcePort})
iam(policies).actionsOnResources({ resources, context }, badImplementationWrap(next))
}
], cb)
return promise
}
|
javascript
|
function listAuthorizationsOnResources ({ userId, resources, organizationId, sourceIpAddress, sourcePort }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
async.waterfall([
function validate (next) {
Joi.validate({ userId, resources, organizationId }, validationRules.listAuthorizationsOnResources, badRequestWrap(next))
},
function listPolicies (result, next) {
policyOps.listAllUserPolicies({ userId, organizationId }, badImplementationWrap(next))
},
function listAuthorizationsOnResources (policies, next) {
let context = buildContext({userId, organizationId, sourceIpAddress, sourcePort})
iam(policies).actionsOnResources({ resources, context }, badImplementationWrap(next))
}
], cb)
return promise
}
|
[
"function",
"listAuthorizationsOnResources",
"(",
"{",
"userId",
",",
"resources",
",",
"organizationId",
",",
"sourceIpAddress",
",",
"sourcePort",
"}",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"async",
".",
"waterfall",
"(",
"[",
"function",
"validate",
"(",
"next",
")",
"{",
"Joi",
".",
"validate",
"(",
"{",
"userId",
",",
"resources",
",",
"organizationId",
"}",
",",
"validationRules",
".",
"listAuthorizationsOnResources",
",",
"badRequestWrap",
"(",
"next",
")",
")",
"}",
",",
"function",
"listPolicies",
"(",
"result",
",",
"next",
")",
"{",
"policyOps",
".",
"listAllUserPolicies",
"(",
"{",
"userId",
",",
"organizationId",
"}",
",",
"badImplementationWrap",
"(",
"next",
")",
")",
"}",
",",
"function",
"listAuthorizationsOnResources",
"(",
"policies",
",",
"next",
")",
"{",
"let",
"context",
"=",
"buildContext",
"(",
"{",
"userId",
",",
"organizationId",
",",
"sourceIpAddress",
",",
"sourcePort",
"}",
")",
"iam",
"(",
"policies",
")",
".",
"actionsOnResources",
"(",
"{",
"resources",
",",
"context",
"}",
",",
"badImplementationWrap",
"(",
"next",
")",
")",
"}",
"]",
",",
"cb",
")",
"return",
"promise",
"}"
] |
List all user's actions on a given list of resources
@param {Object} options { userId, resources }
@param {Function} cb
|
[
"List",
"all",
"user",
"s",
"actions",
"on",
"a",
"given",
"list",
"of",
"resources"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/authorizeOps.js#L142-L160
|
15,727
|
nearform/udaru
|
packages/udaru-hapi-server/bench/util/loadVolumeData.js
|
loadUsers
|
function loadUsers (startId, orgId, teamId, callback) {
// insert users
console.log('inserting users ' + startId + ' to ' + (startId + NUM_USERS_PER_TEAM - 1) + ' into team: ' + teamId)
var userSql = 'INSERT INTO users (id, name, org_id, metadata)\nVALUES\n'
var userTeamSql = 'INSERT INTO team_members (user_id, team_id)\nVALUES\n'
for (var id = startId; id < (startId + NUM_USERS_PER_TEAM); id++) {
userSql += "('" + id + "', 'USER_" + id + "', '" + orgId + "'," + getMetaData(id, orgId) + ')'
userTeamSql += "('" + id + "', '" + teamId + "')"
if (id === startId + NUM_USERS_PER_TEAM - 1) {
userSql += ';'
userTeamSql += ';'
} else {
userSql += ',\n'
userTeamSql += ',\n'
}
}
var fixturesSQL = 'BEGIN;\n'
fixturesSQL += userSql + '\n'
fixturesSQL += userTeamSql + '\n'
fixturesSQL += 'COMMIT;\n'
client.query(fixturesSQL, function (err, result) {
if (err) {
callback(err)
} else {
console.log(chalk.green('success inserting users ' + startId +
' to ' + (startId + NUM_USERS_PER_TEAM - 1)))
if (teamId < NUM_TEAMS + TEAM_START_ID - 1) {
loadUsers(id, orgId, teamId + 1, callback)
} else {
loadVolumeDataEnd(callback)
}
}
})
}
|
javascript
|
function loadUsers (startId, orgId, teamId, callback) {
// insert users
console.log('inserting users ' + startId + ' to ' + (startId + NUM_USERS_PER_TEAM - 1) + ' into team: ' + teamId)
var userSql = 'INSERT INTO users (id, name, org_id, metadata)\nVALUES\n'
var userTeamSql = 'INSERT INTO team_members (user_id, team_id)\nVALUES\n'
for (var id = startId; id < (startId + NUM_USERS_PER_TEAM); id++) {
userSql += "('" + id + "', 'USER_" + id + "', '" + orgId + "'," + getMetaData(id, orgId) + ')'
userTeamSql += "('" + id + "', '" + teamId + "')"
if (id === startId + NUM_USERS_PER_TEAM - 1) {
userSql += ';'
userTeamSql += ';'
} else {
userSql += ',\n'
userTeamSql += ',\n'
}
}
var fixturesSQL = 'BEGIN;\n'
fixturesSQL += userSql + '\n'
fixturesSQL += userTeamSql + '\n'
fixturesSQL += 'COMMIT;\n'
client.query(fixturesSQL, function (err, result) {
if (err) {
callback(err)
} else {
console.log(chalk.green('success inserting users ' + startId +
' to ' + (startId + NUM_USERS_PER_TEAM - 1)))
if (teamId < NUM_TEAMS + TEAM_START_ID - 1) {
loadUsers(id, orgId, teamId + 1, callback)
} else {
loadVolumeDataEnd(callback)
}
}
})
}
|
[
"function",
"loadUsers",
"(",
"startId",
",",
"orgId",
",",
"teamId",
",",
"callback",
")",
"{",
"// insert users",
"console",
".",
"log",
"(",
"'inserting users '",
"+",
"startId",
"+",
"' to '",
"+",
"(",
"startId",
"+",
"NUM_USERS_PER_TEAM",
"-",
"1",
")",
"+",
"' into team: '",
"+",
"teamId",
")",
"var",
"userSql",
"=",
"'INSERT INTO users (id, name, org_id, metadata)\\nVALUES\\n'",
"var",
"userTeamSql",
"=",
"'INSERT INTO team_members (user_id, team_id)\\nVALUES\\n'",
"for",
"(",
"var",
"id",
"=",
"startId",
";",
"id",
"<",
"(",
"startId",
"+",
"NUM_USERS_PER_TEAM",
")",
";",
"id",
"++",
")",
"{",
"userSql",
"+=",
"\"('\"",
"+",
"id",
"+",
"\"', 'USER_\"",
"+",
"id",
"+",
"\"', '\"",
"+",
"orgId",
"+",
"\"',\"",
"+",
"getMetaData",
"(",
"id",
",",
"orgId",
")",
"+",
"')'",
"userTeamSql",
"+=",
"\"('\"",
"+",
"id",
"+",
"\"', '\"",
"+",
"teamId",
"+",
"\"')\"",
"if",
"(",
"id",
"===",
"startId",
"+",
"NUM_USERS_PER_TEAM",
"-",
"1",
")",
"{",
"userSql",
"+=",
"';'",
"userTeamSql",
"+=",
"';'",
"}",
"else",
"{",
"userSql",
"+=",
"',\\n'",
"userTeamSql",
"+=",
"',\\n'",
"}",
"}",
"var",
"fixturesSQL",
"=",
"'BEGIN;\\n'",
"fixturesSQL",
"+=",
"userSql",
"+",
"'\\n'",
"fixturesSQL",
"+=",
"userTeamSql",
"+",
"'\\n'",
"fixturesSQL",
"+=",
"'COMMIT;\\n'",
"client",
".",
"query",
"(",
"fixturesSQL",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"chalk",
".",
"green",
"(",
"'success inserting users '",
"+",
"startId",
"+",
"' to '",
"+",
"(",
"startId",
"+",
"NUM_USERS_PER_TEAM",
"-",
"1",
")",
")",
")",
"if",
"(",
"teamId",
"<",
"NUM_TEAMS",
"+",
"TEAM_START_ID",
"-",
"1",
")",
"{",
"loadUsers",
"(",
"id",
",",
"orgId",
",",
"teamId",
"+",
"1",
",",
"callback",
")",
"}",
"else",
"{",
"loadVolumeDataEnd",
"(",
"callback",
")",
"}",
"}",
"}",
")",
"}"
] |
insert users and add them to teams in batches
|
[
"insert",
"users",
"and",
"add",
"them",
"to",
"teams",
"in",
"batches"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-hapi-server/bench/util/loadVolumeData.js#L157-L194
|
15,728
|
nearform/udaru
|
packages/udaru-core/lib/ops/policyOps.js
|
readPolicyVariables
|
function readPolicyVariables ({ id, organizationId, type }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
Joi.validate({ id, organizationId, type }, validationRules.readPolicyVariables, function (err) {
if (err) return cb(Boom.badRequest(err))
const sqlQuery = SQL`
SELECT *
FROM policies
WHERE id = ${id}
`
if (type === 'shared') {
sqlQuery.append(SQL` AND org_id is NULL`)
} else {
sqlQuery.append(SQL` AND org_id=${organizationId}`)
}
db.query(sqlQuery, function (err, result) {
if (err) return cb(Boom.badImplementation(err))
if (result.rowCount === 0) return cb(Boom.notFound())
let variables = []
_.each(result.rows[0].statements.Statement, function (statement) {
if (statement.Resource) {
_.map(statement.Resource, function (resource) {
// ignore context vars but list all others, should match validation.js
let variableMatches = resource.match(/\${((?!(udaru)|(request)).*)(.+?)}/g)
_.each(variableMatches, function (variable) {
variables.push(variable)
})
})
}
})
return cb(null, variables)
})
})
return promise
}
|
javascript
|
function readPolicyVariables ({ id, organizationId, type }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
Joi.validate({ id, organizationId, type }, validationRules.readPolicyVariables, function (err) {
if (err) return cb(Boom.badRequest(err))
const sqlQuery = SQL`
SELECT *
FROM policies
WHERE id = ${id}
`
if (type === 'shared') {
sqlQuery.append(SQL` AND org_id is NULL`)
} else {
sqlQuery.append(SQL` AND org_id=${organizationId}`)
}
db.query(sqlQuery, function (err, result) {
if (err) return cb(Boom.badImplementation(err))
if (result.rowCount === 0) return cb(Boom.notFound())
let variables = []
_.each(result.rows[0].statements.Statement, function (statement) {
if (statement.Resource) {
_.map(statement.Resource, function (resource) {
// ignore context vars but list all others, should match validation.js
let variableMatches = resource.match(/\${((?!(udaru)|(request)).*)(.+?)}/g)
_.each(variableMatches, function (variable) {
variables.push(variable)
})
})
}
})
return cb(null, variables)
})
})
return promise
}
|
[
"function",
"readPolicyVariables",
"(",
"{",
"id",
",",
"organizationId",
",",
"type",
"}",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"organizationId",
",",
"type",
"}",
",",
"validationRules",
".",
"readPolicyVariables",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"const",
"sqlQuery",
"=",
"SQL",
"`",
"${",
"id",
"}",
"`",
"if",
"(",
"type",
"===",
"'shared'",
")",
"{",
"sqlQuery",
".",
"append",
"(",
"SQL",
"`",
"`",
")",
"}",
"else",
"{",
"sqlQuery",
".",
"append",
"(",
"SQL",
"`",
"${",
"organizationId",
"}",
"`",
")",
"}",
"db",
".",
"query",
"(",
"sqlQuery",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"if",
"(",
"result",
".",
"rowCount",
"===",
"0",
")",
"return",
"cb",
"(",
"Boom",
".",
"notFound",
"(",
")",
")",
"let",
"variables",
"=",
"[",
"]",
"_",
".",
"each",
"(",
"result",
".",
"rows",
"[",
"0",
"]",
".",
"statements",
".",
"Statement",
",",
"function",
"(",
"statement",
")",
"{",
"if",
"(",
"statement",
".",
"Resource",
")",
"{",
"_",
".",
"map",
"(",
"statement",
".",
"Resource",
",",
"function",
"(",
"resource",
")",
"{",
"// ignore context vars but list all others, should match validation.js",
"let",
"variableMatches",
"=",
"resource",
".",
"match",
"(",
"/",
"\\${((?!(udaru)|(request)).*)(.+?)}",
"/",
"g",
")",
"_",
".",
"each",
"(",
"variableMatches",
",",
"function",
"(",
"variable",
")",
"{",
"variables",
".",
"push",
"(",
"variable",
")",
"}",
")",
"}",
")",
"}",
"}",
")",
"return",
"cb",
"(",
"null",
",",
"variables",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
fetch specific policy variables
@param {Object} params { id, organizationId, type } "type" is optional, defaults to organization policies
@param {Function} cb
|
[
"fetch",
"specific",
"policy",
"variables"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/policyOps.js#L227-L269
|
15,729
|
nearform/udaru
|
packages/udaru-core/lib/ops/policyOps.js
|
listPolicyInstances
|
function listPolicyInstances ({ id, organizationId, type }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
Joi.validate({ id, organizationId, type }, validationRules.listPolicyInstances, function (err) {
if (err) return cb(Boom.badRequest(err))
const sqlQuery = SQL`
SELECT entity_type, entity_id, policy_instance, variables, policy_id FROM
(SELECT 'user' as entity_type, user_id as entity_id, variables, policy_instance, policy_id
FROM user_policies
WHERE policy_id = ${id}
UNION
SELECT 'team' as entity_type, team_id as entity_id, variables, policy_instance, policy_id
FROM team_policies
WHERE policy_id = ${id}
UNION
SELECT 'organization' as entity_type, org_id as entity_id, variables, policy_instance, policy_id
FROM organization_policies
WHERE policy_id = ${id}) as policy_instances
INNER JOIN policies
ON policies.id = policy_instances.policy_id
`
if (type === 'shared') {
sqlQuery.append(SQL` WHERE org_id is NULL`)
} else {
sqlQuery.append(SQL` WHERE org_id=${organizationId}`)
}
sqlQuery.append(SQL` ORDER BY entity_type, policy_instance`)
db.query(sqlQuery, function (err, result) {
if (err) return cb(Boom.badImplementation(err))
if (result.rowCount === 0) return cb(null, [])
return cb(null, result.rows.map(mapping.policy.instances))
})
})
return promise
}
|
javascript
|
function listPolicyInstances ({ id, organizationId, type }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
Joi.validate({ id, organizationId, type }, validationRules.listPolicyInstances, function (err) {
if (err) return cb(Boom.badRequest(err))
const sqlQuery = SQL`
SELECT entity_type, entity_id, policy_instance, variables, policy_id FROM
(SELECT 'user' as entity_type, user_id as entity_id, variables, policy_instance, policy_id
FROM user_policies
WHERE policy_id = ${id}
UNION
SELECT 'team' as entity_type, team_id as entity_id, variables, policy_instance, policy_id
FROM team_policies
WHERE policy_id = ${id}
UNION
SELECT 'organization' as entity_type, org_id as entity_id, variables, policy_instance, policy_id
FROM organization_policies
WHERE policy_id = ${id}) as policy_instances
INNER JOIN policies
ON policies.id = policy_instances.policy_id
`
if (type === 'shared') {
sqlQuery.append(SQL` WHERE org_id is NULL`)
} else {
sqlQuery.append(SQL` WHERE org_id=${organizationId}`)
}
sqlQuery.append(SQL` ORDER BY entity_type, policy_instance`)
db.query(sqlQuery, function (err, result) {
if (err) return cb(Boom.badImplementation(err))
if (result.rowCount === 0) return cb(null, [])
return cb(null, result.rows.map(mapping.policy.instances))
})
})
return promise
}
|
[
"function",
"listPolicyInstances",
"(",
"{",
"id",
",",
"organizationId",
",",
"type",
"}",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"organizationId",
",",
"type",
"}",
",",
"validationRules",
".",
"listPolicyInstances",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"const",
"sqlQuery",
"=",
"SQL",
"`",
"${",
"id",
"}",
"${",
"id",
"}",
"${",
"id",
"}",
"`",
"if",
"(",
"type",
"===",
"'shared'",
")",
"{",
"sqlQuery",
".",
"append",
"(",
"SQL",
"`",
"`",
")",
"}",
"else",
"{",
"sqlQuery",
".",
"append",
"(",
"SQL",
"`",
"${",
"organizationId",
"}",
"`",
")",
"}",
"sqlQuery",
".",
"append",
"(",
"SQL",
"`",
"`",
")",
"db",
".",
"query",
"(",
"sqlQuery",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"if",
"(",
"result",
".",
"rowCount",
"===",
"0",
")",
"return",
"cb",
"(",
"null",
",",
"[",
"]",
")",
"return",
"cb",
"(",
"null",
",",
"result",
".",
"rows",
".",
"map",
"(",
"mapping",
".",
"policy",
".",
"instances",
")",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
list policy instances in their respective entities
@param {Object} params { id, organizationId, type } "type" is optional, defaults to organization policies
@param {Function} cb
|
[
"list",
"policy",
"instances",
"in",
"their",
"respective",
"entities"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/policyOps.js#L277-L315
|
15,730
|
nearform/udaru
|
packages/udaru-core/lib/ops/policyOps.js
|
createPolicy
|
function createPolicy (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, version, name, organizationId, statements } = params
Joi.validate({ id, version, name, organizationId, statements }, validationRules.createPolicy, function (err) {
if (err) return cb(Boom.badRequest(err))
insertPolicies(db, [{
id: id,
version: version,
name: name,
org_id: organizationId,
statements: statements
}], (err, result) => {
if (utils.isUniqueViolationError(err)) return cb(Boom.conflict('policy already exists'))
if (err) return cb(Boom.badImplementation(err))
policyOps.readPolicy({ id: result.rows[0].id, organizationId }, cb)
})
})
return promise
}
|
javascript
|
function createPolicy (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, version, name, organizationId, statements } = params
Joi.validate({ id, version, name, organizationId, statements }, validationRules.createPolicy, function (err) {
if (err) return cb(Boom.badRequest(err))
insertPolicies(db, [{
id: id,
version: version,
name: name,
org_id: organizationId,
statements: statements
}], (err, result) => {
if (utils.isUniqueViolationError(err)) return cb(Boom.conflict('policy already exists'))
if (err) return cb(Boom.badImplementation(err))
policyOps.readPolicy({ id: result.rows[0].id, organizationId }, cb)
})
})
return promise
}
|
[
"function",
"createPolicy",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"id",
",",
"version",
",",
"name",
",",
"organizationId",
",",
"statements",
"}",
"=",
"params",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"version",
",",
"name",
",",
"organizationId",
",",
"statements",
"}",
",",
"validationRules",
".",
"createPolicy",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"insertPolicies",
"(",
"db",
",",
"[",
"{",
"id",
":",
"id",
",",
"version",
":",
"version",
",",
"name",
":",
"name",
",",
"org_id",
":",
"organizationId",
",",
"statements",
":",
"statements",
"}",
"]",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"utils",
".",
"isUniqueViolationError",
"(",
"err",
")",
")",
"return",
"cb",
"(",
"Boom",
".",
"conflict",
"(",
"'policy already exists'",
")",
")",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"policyOps",
".",
"readPolicy",
"(",
"{",
"id",
":",
"result",
".",
"rows",
"[",
"0",
"]",
".",
"id",
",",
"organizationId",
"}",
",",
"cb",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
Creates a new policy
@param {Object} params { id, version, name, organizationId, statements }
@param {Function} cb
|
[
"Creates",
"a",
"new",
"policy"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/policyOps.js#L323-L346
|
15,731
|
nearform/udaru
|
packages/udaru-core/lib/ops/policyOps.js
|
updatePolicy
|
function updatePolicy (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId, version, name, statements } = params
Joi.validate({ id, organizationId, version, name, statements }, validationRules.updatePolicy, function (err) {
if (err) return cb(Boom.badRequest(err))
const sqlQuery = SQL`
UPDATE policies
SET
version = ${version},
name = ${name},
statements = ${statements}
WHERE
id = ${id}
AND org_id = ${organizationId}
`
db.query(sqlQuery, function (err, result) {
if (utils.isUniqueViolationError(err)) return cb(Boom.conflict(err.detail))
if (err) return cb(Boom.badImplementation(err))
if (result.rowCount === 0) return cb(Boom.notFound())
policyOps.readPolicy({ id, organizationId }, cb)
})
})
return promise
}
|
javascript
|
function updatePolicy (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId, version, name, statements } = params
Joi.validate({ id, organizationId, version, name, statements }, validationRules.updatePolicy, function (err) {
if (err) return cb(Boom.badRequest(err))
const sqlQuery = SQL`
UPDATE policies
SET
version = ${version},
name = ${name},
statements = ${statements}
WHERE
id = ${id}
AND org_id = ${organizationId}
`
db.query(sqlQuery, function (err, result) {
if (utils.isUniqueViolationError(err)) return cb(Boom.conflict(err.detail))
if (err) return cb(Boom.badImplementation(err))
if (result.rowCount === 0) return cb(Boom.notFound())
policyOps.readPolicy({ id, organizationId }, cb)
})
})
return promise
}
|
[
"function",
"updatePolicy",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"id",
",",
"organizationId",
",",
"version",
",",
"name",
",",
"statements",
"}",
"=",
"params",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"organizationId",
",",
"version",
",",
"name",
",",
"statements",
"}",
",",
"validationRules",
".",
"updatePolicy",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"const",
"sqlQuery",
"=",
"SQL",
"`",
"${",
"version",
"}",
"${",
"name",
"}",
"${",
"statements",
"}",
"${",
"id",
"}",
"${",
"organizationId",
"}",
"`",
"db",
".",
"query",
"(",
"sqlQuery",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"utils",
".",
"isUniqueViolationError",
"(",
"err",
")",
")",
"return",
"cb",
"(",
"Boom",
".",
"conflict",
"(",
"err",
".",
"detail",
")",
")",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"if",
"(",
"result",
".",
"rowCount",
"===",
"0",
")",
"return",
"cb",
"(",
"Boom",
".",
"notFound",
"(",
")",
")",
"policyOps",
".",
"readPolicy",
"(",
"{",
"id",
",",
"organizationId",
"}",
",",
"cb",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
Update policy values
@param {Object} params { id, organizationId, version, name, statements }
@param {Function} cb
|
[
"Update",
"policy",
"values"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/policyOps.js#L354-L383
|
15,732
|
nearform/udaru
|
packages/udaru-core/lib/ops/policyOps.js
|
deletePolicy
|
function deletePolicy (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId } = params
const tasks = [
(job, next) => {
Joi.validate({ id, organizationId }, validationRules.deletePolicy, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.id = id
job.organizationId = organizationId
next()
},
removePolicyFromUsers,
removePolicyFromTeams,
removePolicyFromOrganizations,
removePolicy
]
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
cb()
})
return promise
}
|
javascript
|
function deletePolicy (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, organizationId } = params
const tasks = [
(job, next) => {
Joi.validate({ id, organizationId }, validationRules.deletePolicy, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.id = id
job.organizationId = organizationId
next()
},
removePolicyFromUsers,
removePolicyFromTeams,
removePolicyFromOrganizations,
removePolicy
]
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
cb()
})
return promise
}
|
[
"function",
"deletePolicy",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"id",
",",
"organizationId",
"}",
"=",
"params",
"const",
"tasks",
"=",
"[",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"organizationId",
"}",
",",
"validationRules",
".",
"deletePolicy",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"next",
"(",
")",
"}",
")",
"}",
",",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"job",
".",
"id",
"=",
"id",
"job",
".",
"organizationId",
"=",
"organizationId",
"next",
"(",
")",
"}",
",",
"removePolicyFromUsers",
",",
"removePolicyFromTeams",
",",
"removePolicyFromOrganizations",
",",
"removePolicy",
"]",
"db",
".",
"withTransaction",
"(",
"tasks",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"cb",
"(",
")",
"}",
")",
"return",
"promise",
"}"
] |
Delete a specific policy
@param {Object} params { id, organizationId }
@param {Function} cb
|
[
"Delete",
"a",
"specific",
"policy"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/policyOps.js#L391-L421
|
15,733
|
nearform/udaru
|
packages/udaru-core/lib/ops/policyOps.js
|
listAllUserPolicies
|
function listAllUserPolicies ({ userId, organizationId }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const rootOrgId = config.get('authorization.superUser.organization.id')
const sql = SQL`
WITH user_teams AS (
SELECT id FROM teams WHERE path @> (
SELECT array_agg(path) FROM teams
INNER JOIN team_members tm
ON tm.team_id = teams.id
WHERE tm.user_id = ${userId}
)
),
policies_from_teams AS (
SELECT
policy_id, variables
FROM
team_policies
WHERE
team_id IN (SELECT id FROM user_teams)
),
policies_from_user AS (
SELECT
policy_id, variables
FROM
user_policies
WHERE
user_id = ${userId}
),
policies_from_organization AS (
SELECT
op.policy_id, variables
FROM
organization_policies op
LEFT JOIN
users u ON u.org_id = op.org_id
WHERE
u.id = ${userId}
),
is_root_user AS (
SELECT FROM users WHERE id=${userId} AND org_id = ${rootOrgId}
)
SELECT
id,
version,
name,
statements,
policies_from_user.variables AS variables
FROM
policies
INNER JOIN
policies_from_user
ON
policies.id = policies_from_user.policy_id
WHERE (
org_id = ${organizationId}
OR (
EXISTS (SELECT FROM is_root_user)
AND
org_id = ${rootOrgId}
)
OR org_id IS NULL
)
UNION
SELECT
id,
version,
name,
statements,
policies_from_teams.variables AS variables
FROM
policies
INNER JOIN
policies_from_teams
ON
policies.id = policies_from_teams.policy_id
WHERE (
org_id = ${organizationId}
OR (
EXISTS (SELECT FROM is_root_user)
AND
org_id = ${rootOrgId}
)
OR org_id IS NULL
)
UNION
SELECT
id,
version,
name,
statements,
policies_from_organization.variables
FROM
policies
INNER JOIN
policies_from_organization
ON
policies.id = policies_from_organization.policy_id
WHERE (
org_id = ${organizationId}
OR (
EXISTS (SELECT FROM is_root_user)
AND
org_id = ${rootOrgId}
)
OR org_id IS NULL
)
`
db.query(sql, function (err, result) {
if (err) return cb(Boom.badImplementation(err))
cb(null, result.rows.map(mapping.policy.iam))
})
return promise
}
|
javascript
|
function listAllUserPolicies ({ userId, organizationId }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const rootOrgId = config.get('authorization.superUser.organization.id')
const sql = SQL`
WITH user_teams AS (
SELECT id FROM teams WHERE path @> (
SELECT array_agg(path) FROM teams
INNER JOIN team_members tm
ON tm.team_id = teams.id
WHERE tm.user_id = ${userId}
)
),
policies_from_teams AS (
SELECT
policy_id, variables
FROM
team_policies
WHERE
team_id IN (SELECT id FROM user_teams)
),
policies_from_user AS (
SELECT
policy_id, variables
FROM
user_policies
WHERE
user_id = ${userId}
),
policies_from_organization AS (
SELECT
op.policy_id, variables
FROM
organization_policies op
LEFT JOIN
users u ON u.org_id = op.org_id
WHERE
u.id = ${userId}
),
is_root_user AS (
SELECT FROM users WHERE id=${userId} AND org_id = ${rootOrgId}
)
SELECT
id,
version,
name,
statements,
policies_from_user.variables AS variables
FROM
policies
INNER JOIN
policies_from_user
ON
policies.id = policies_from_user.policy_id
WHERE (
org_id = ${organizationId}
OR (
EXISTS (SELECT FROM is_root_user)
AND
org_id = ${rootOrgId}
)
OR org_id IS NULL
)
UNION
SELECT
id,
version,
name,
statements,
policies_from_teams.variables AS variables
FROM
policies
INNER JOIN
policies_from_teams
ON
policies.id = policies_from_teams.policy_id
WHERE (
org_id = ${organizationId}
OR (
EXISTS (SELECT FROM is_root_user)
AND
org_id = ${rootOrgId}
)
OR org_id IS NULL
)
UNION
SELECT
id,
version,
name,
statements,
policies_from_organization.variables
FROM
policies
INNER JOIN
policies_from_organization
ON
policies.id = policies_from_organization.policy_id
WHERE (
org_id = ${organizationId}
OR (
EXISTS (SELECT FROM is_root_user)
AND
org_id = ${rootOrgId}
)
OR org_id IS NULL
)
`
db.query(sql, function (err, result) {
if (err) return cb(Boom.badImplementation(err))
cb(null, result.rows.map(mapping.policy.iam))
})
return promise
}
|
[
"function",
"listAllUserPolicies",
"(",
"{",
"userId",
",",
"organizationId",
"}",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"rootOrgId",
"=",
"config",
".",
"get",
"(",
"'authorization.superUser.organization.id'",
")",
"const",
"sql",
"=",
"SQL",
"`",
"${",
"userId",
"}",
"${",
"userId",
"}",
"${",
"userId",
"}",
"${",
"userId",
"}",
"${",
"rootOrgId",
"}",
"${",
"organizationId",
"}",
"${",
"rootOrgId",
"}",
"${",
"organizationId",
"}",
"${",
"rootOrgId",
"}",
"${",
"organizationId",
"}",
"${",
"rootOrgId",
"}",
"`",
"db",
".",
"query",
"(",
"sql",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"cb",
"(",
"null",
",",
"result",
".",
"rows",
".",
"map",
"(",
"mapping",
".",
"policy",
".",
"iam",
")",
")",
"}",
")",
"return",
"promise",
"}"
] |
List all user policies
@param {Object} params { userId, organizationId }
@param {Function} cb
|
[
"List",
"all",
"user",
"policies"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/policyOps.js#L429-L545
|
15,734
|
nearform/udaru
|
packages/udaru-core/lib/ops/policyOps.js
|
readSharedPolicy
|
function readSharedPolicy ({ id }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
Joi.validate({ id }, validationRules.readSharedPolicy, function (err) {
if (err) return cb(Boom.badRequest(err))
const sqlQuery = SQL`
SELECT *
FROM policies
WHERE id = ${id}
AND org_id IS NULL
`
db.query(sqlQuery, function (err, result) {
if (err) return cb(Boom.badImplementation(err))
if (result.rowCount === 0) return cb(Boom.notFound())
return cb(null, mapping.policy(result.rows[0]))
})
})
return promise
}
|
javascript
|
function readSharedPolicy ({ id }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
Joi.validate({ id }, validationRules.readSharedPolicy, function (err) {
if (err) return cb(Boom.badRequest(err))
const sqlQuery = SQL`
SELECT *
FROM policies
WHERE id = ${id}
AND org_id IS NULL
`
db.query(sqlQuery, function (err, result) {
if (err) return cb(Boom.badImplementation(err))
if (result.rowCount === 0) return cb(Boom.notFound())
return cb(null, mapping.policy(result.rows[0]))
})
})
return promise
}
|
[
"function",
"readSharedPolicy",
"(",
"{",
"id",
"}",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"Joi",
".",
"validate",
"(",
"{",
"id",
"}",
",",
"validationRules",
".",
"readSharedPolicy",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"const",
"sqlQuery",
"=",
"SQL",
"`",
"${",
"id",
"}",
"`",
"db",
".",
"query",
"(",
"sqlQuery",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"if",
"(",
"result",
".",
"rowCount",
"===",
"0",
")",
"return",
"cb",
"(",
"Boom",
".",
"notFound",
"(",
")",
")",
"return",
"cb",
"(",
"null",
",",
"mapping",
".",
"policy",
"(",
"result",
".",
"rows",
"[",
"0",
"]",
")",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
fetch specific shared policy
@param {Object} params { id }
@param {Function} cb
|
[
"fetch",
"specific",
"shared",
"policy"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/policyOps.js#L700-L722
|
15,735
|
nearform/udaru
|
packages/udaru-core/lib/ops/policyOps.js
|
createSharedPolicy
|
function createSharedPolicy (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
Joi.validate(params, validationRules.createSharedPolicy, function (err) {
if (err) return cb(Boom.badRequest(err))
const { id, version, name, statements } = params
insertSharedPolicies(db, [{
id: id,
version: version,
name: name,
statements: statements
}], (err, result) => {
if (utils.isUniqueViolationError(err)) return cb(Boom.conflict('policy already exists'))
if (err) return cb(err)
policyOps.readSharedPolicy({ id: result.rows[0].id }, cb)
})
})
return promise
}
|
javascript
|
function createSharedPolicy (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
Joi.validate(params, validationRules.createSharedPolicy, function (err) {
if (err) return cb(Boom.badRequest(err))
const { id, version, name, statements } = params
insertSharedPolicies(db, [{
id: id,
version: version,
name: name,
statements: statements
}], (err, result) => {
if (utils.isUniqueViolationError(err)) return cb(Boom.conflict('policy already exists'))
if (err) return cb(err)
policyOps.readSharedPolicy({ id: result.rows[0].id }, cb)
})
})
return promise
}
|
[
"function",
"createSharedPolicy",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"Joi",
".",
"validate",
"(",
"params",
",",
"validationRules",
".",
"createSharedPolicy",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"const",
"{",
"id",
",",
"version",
",",
"name",
",",
"statements",
"}",
"=",
"params",
"insertSharedPolicies",
"(",
"db",
",",
"[",
"{",
"id",
":",
"id",
",",
"version",
":",
"version",
",",
"name",
":",
"name",
",",
"statements",
":",
"statements",
"}",
"]",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"utils",
".",
"isUniqueViolationError",
"(",
"err",
")",
")",
"return",
"cb",
"(",
"Boom",
".",
"conflict",
"(",
"'policy already exists'",
")",
")",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"policyOps",
".",
"readSharedPolicy",
"(",
"{",
"id",
":",
"result",
".",
"rows",
"[",
"0",
"]",
".",
"id",
"}",
",",
"cb",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
Creates a new shared policy
@param {Object} params { id, version, name, statements }
@param {Function} cb
|
[
"Creates",
"a",
"new",
"shared",
"policy"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/policyOps.js#L730-L753
|
15,736
|
nearform/udaru
|
packages/udaru-core/lib/ops/organizationOps.js
|
insertOrgAdminUser
|
function insertOrgAdminUser (job, next) {
if (job.user) {
const { id, name } = job.user
const { id: organizationId } = job.organization
userOps.insertUser(job.client, { id, name, organizationId }, (err, res) => {
if (err) return next(err)
job.user.id = res.rows[0].id
userOps.insertPolicies(job.client, job.user.id, [{id: job.adminPolicyId, variables: {}}], utils.boomErrorWrapper(next))
})
return
}
next()
}
|
javascript
|
function insertOrgAdminUser (job, next) {
if (job.user) {
const { id, name } = job.user
const { id: organizationId } = job.organization
userOps.insertUser(job.client, { id, name, organizationId }, (err, res) => {
if (err) return next(err)
job.user.id = res.rows[0].id
userOps.insertPolicies(job.client, job.user.id, [{id: job.adminPolicyId, variables: {}}], utils.boomErrorWrapper(next))
})
return
}
next()
}
|
[
"function",
"insertOrgAdminUser",
"(",
"job",
",",
"next",
")",
"{",
"if",
"(",
"job",
".",
"user",
")",
"{",
"const",
"{",
"id",
",",
"name",
"}",
"=",
"job",
".",
"user",
"const",
"{",
"id",
":",
"organizationId",
"}",
"=",
"job",
".",
"organization",
"userOps",
".",
"insertUser",
"(",
"job",
".",
"client",
",",
"{",
"id",
",",
"name",
",",
"organizationId",
"}",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"err",
")",
"job",
".",
"user",
".",
"id",
"=",
"res",
".",
"rows",
"[",
"0",
"]",
".",
"id",
"userOps",
".",
"insertPolicies",
"(",
"job",
".",
"client",
",",
"job",
".",
"user",
".",
"id",
",",
"[",
"{",
"id",
":",
"job",
".",
"adminPolicyId",
",",
"variables",
":",
"{",
"}",
"}",
"]",
",",
"utils",
".",
"boomErrorWrapper",
"(",
"next",
")",
")",
"}",
")",
"return",
"}",
"next",
"(",
")",
"}"
] |
Insert a new user and attach to it the organization admin policy
@param {Object} job
@param {Function} next
|
[
"Insert",
"a",
"new",
"user",
"and",
"attach",
"to",
"it",
"the",
"organization",
"admin",
"policy"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/organizationOps.js#L175-L191
|
15,737
|
nearform/udaru
|
packages/udaru-core/lib/ops/organizationOps.js
|
list
|
function list ({ limit, page }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify('data', 'total')
Joi.validate({ limit, page }, validationRules.list, (err) => {
if (err) return cb(Boom.badRequest(err))
const sqlQuery = SQL`
WITH total AS (
SELECT COUNT(*) AS cnt FROM organizations
)
SELECT o.*, t.cnt::INTEGER AS total
FROM organizations AS o
INNER JOIN total AS t ON 1=1
ORDER BY UPPER(o.name)
`
if (limit) {
sqlQuery.append(SQL` LIMIT ${limit}`)
}
if (limit && page) {
let offset = (page - 1) * limit
sqlQuery.append(SQL` OFFSET ${offset}`)
}
db.query(sqlQuery, function (err, result) {
if (err) return cb(Boom.badImplementation(err))
let total = result.rows.length > 0 ? result.rows[0].total : 0
return cb(null, result.rows.map(mapping.organization), total)
})
})
return promise
}
|
javascript
|
function list ({ limit, page }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify('data', 'total')
Joi.validate({ limit, page }, validationRules.list, (err) => {
if (err) return cb(Boom.badRequest(err))
const sqlQuery = SQL`
WITH total AS (
SELECT COUNT(*) AS cnt FROM organizations
)
SELECT o.*, t.cnt::INTEGER AS total
FROM organizations AS o
INNER JOIN total AS t ON 1=1
ORDER BY UPPER(o.name)
`
if (limit) {
sqlQuery.append(SQL` LIMIT ${limit}`)
}
if (limit && page) {
let offset = (page - 1) * limit
sqlQuery.append(SQL` OFFSET ${offset}`)
}
db.query(sqlQuery, function (err, result) {
if (err) return cb(Boom.badImplementation(err))
let total = result.rows.length > 0 ? result.rows[0].total : 0
return cb(null, result.rows.map(mapping.organization), total)
})
})
return promise
}
|
[
"function",
"list",
"(",
"{",
"limit",
",",
"page",
"}",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
"'data'",
",",
"'total'",
")",
"Joi",
".",
"validate",
"(",
"{",
"limit",
",",
"page",
"}",
",",
"validationRules",
".",
"list",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"const",
"sqlQuery",
"=",
"SQL",
"`",
"`",
"if",
"(",
"limit",
")",
"{",
"sqlQuery",
".",
"append",
"(",
"SQL",
"`",
"${",
"limit",
"}",
"`",
")",
"}",
"if",
"(",
"limit",
"&&",
"page",
")",
"{",
"let",
"offset",
"=",
"(",
"page",
"-",
"1",
")",
"*",
"limit",
"sqlQuery",
".",
"append",
"(",
"SQL",
"`",
"${",
"offset",
"}",
"`",
")",
"}",
"db",
".",
"query",
"(",
"sqlQuery",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"let",
"total",
"=",
"result",
".",
"rows",
".",
"length",
">",
"0",
"?",
"result",
".",
"rows",
"[",
"0",
"]",
".",
"total",
":",
"0",
"return",
"cb",
"(",
"null",
",",
"result",
".",
"rows",
".",
"map",
"(",
"mapping",
".",
"organization",
")",
",",
"total",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
Fetch all organizations
@param {Object} params must contain both `limit` and `page` for pagination. Page is 1-indexed.
@param {Function} cb
|
[
"Fetch",
"all",
"organizations"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/organizationOps.js#L208-L240
|
15,738
|
nearform/udaru
|
packages/udaru-core/lib/ops/organizationOps.js
|
readById
|
function readById (id, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
let organization
const tasks = []
tasks.push((next) => {
Joi.validate(id, validationRules.readById, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
})
tasks.push((next) => {
const sqlQuery = SQL`
SELECT *
FROM organizations
WHERE id = ${id}
`
db.query(sqlQuery, (err, result) => {
if (err) return next(Boom.badImplementation(err))
if (result.rowCount === 0) return next(Boom.notFound(`Organization ${id} not found`))
organization = mapping.organization(result.rows[0])
next()
})
})
tasks.push((next) => {
const sqlQuery = SQL`
SELECT pol.id, pol.name, pol.version, org_pol.variables, org_pol.policy_instance
FROM organization_policies org_pol, policies pol
WHERE org_pol.org_id = ${id} AND org_pol.policy_id = pol.id
ORDER BY UPPER(pol.name)
`
db.query(sqlQuery, (err, result) => {
if (err) return next(Boom.badImplementation(err))
organization.policies = result.rows.map(mapping.policy.simple)
next()
})
})
async.series(tasks, (err) => {
if (err) return cb(err)
return cb(null, organization)
})
return promise
}
|
javascript
|
function readById (id, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
let organization
const tasks = []
tasks.push((next) => {
Joi.validate(id, validationRules.readById, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
})
tasks.push((next) => {
const sqlQuery = SQL`
SELECT *
FROM organizations
WHERE id = ${id}
`
db.query(sqlQuery, (err, result) => {
if (err) return next(Boom.badImplementation(err))
if (result.rowCount === 0) return next(Boom.notFound(`Organization ${id} not found`))
organization = mapping.organization(result.rows[0])
next()
})
})
tasks.push((next) => {
const sqlQuery = SQL`
SELECT pol.id, pol.name, pol.version, org_pol.variables, org_pol.policy_instance
FROM organization_policies org_pol, policies pol
WHERE org_pol.org_id = ${id} AND org_pol.policy_id = pol.id
ORDER BY UPPER(pol.name)
`
db.query(sqlQuery, (err, result) => {
if (err) return next(Boom.badImplementation(err))
organization.policies = result.rows.map(mapping.policy.simple)
next()
})
})
async.series(tasks, (err) => {
if (err) return cb(err)
return cb(null, organization)
})
return promise
}
|
[
"function",
"readById",
"(",
"id",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"let",
"organization",
"const",
"tasks",
"=",
"[",
"]",
"tasks",
".",
"push",
"(",
"(",
"next",
")",
"=>",
"{",
"Joi",
".",
"validate",
"(",
"id",
",",
"validationRules",
".",
"readById",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"next",
"(",
")",
"}",
")",
"}",
")",
"tasks",
".",
"push",
"(",
"(",
"next",
")",
"=>",
"{",
"const",
"sqlQuery",
"=",
"SQL",
"`",
"${",
"id",
"}",
"`",
"db",
".",
"query",
"(",
"sqlQuery",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"if",
"(",
"result",
".",
"rowCount",
"===",
"0",
")",
"return",
"next",
"(",
"Boom",
".",
"notFound",
"(",
"`",
"${",
"id",
"}",
"`",
")",
")",
"organization",
"=",
"mapping",
".",
"organization",
"(",
"result",
".",
"rows",
"[",
"0",
"]",
")",
"next",
"(",
")",
"}",
")",
"}",
")",
"tasks",
".",
"push",
"(",
"(",
"next",
")",
"=>",
"{",
"const",
"sqlQuery",
"=",
"SQL",
"`",
"${",
"id",
"}",
"`",
"db",
".",
"query",
"(",
"sqlQuery",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"organization",
".",
"policies",
"=",
"result",
".",
"rows",
".",
"map",
"(",
"mapping",
".",
"policy",
".",
"simple",
")",
"next",
"(",
")",
"}",
")",
"}",
")",
"async",
".",
"series",
"(",
"tasks",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"return",
"cb",
"(",
"null",
",",
"organization",
")",
"}",
")",
"return",
"promise",
"}"
] |
Fetch data for an organization
@param {String} id
@param {Function} cb
|
[
"Fetch",
"data",
"for",
"an",
"organization"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/organizationOps.js#L248-L299
|
15,739
|
nearform/udaru
|
packages/udaru-core/lib/ops/organizationOps.js
|
create
|
function create (params, opts, cb) {
if (!cb) {
cb = opts
}
if (!opts || typeof opts === 'function') {
opts = {}
}
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { createOnly } = opts
const tasks = [
(job, next) => {
const id = params.id || uuid()
params.id = id
const { name, description, metadata, user } = params
Joi.validate({ id, name, description, metadata, user }, validationRules.create, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.params = params
job.user = params.user
next()
},
insertOrganization
]
if (!createOnly) {
tasks.push(
createDefaultPolicies,
insertOrgAdminUser
)
}
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
organizationOps.readById(res.organization.id, (err, organization) => {
if (err) return cb(Boom.badImplementation(err))
cb(null, { organization, user: res.user })
})
})
return promise
}
|
javascript
|
function create (params, opts, cb) {
if (!cb) {
cb = opts
}
if (!opts || typeof opts === 'function') {
opts = {}
}
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { createOnly } = opts
const tasks = [
(job, next) => {
const id = params.id || uuid()
params.id = id
const { name, description, metadata, user } = params
Joi.validate({ id, name, description, metadata, user }, validationRules.create, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.params = params
job.user = params.user
next()
},
insertOrganization
]
if (!createOnly) {
tasks.push(
createDefaultPolicies,
insertOrgAdminUser
)
}
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
organizationOps.readById(res.organization.id, (err, organization) => {
if (err) return cb(Boom.badImplementation(err))
cb(null, { organization, user: res.user })
})
})
return promise
}
|
[
"function",
"create",
"(",
"params",
",",
"opts",
",",
"cb",
")",
"{",
"if",
"(",
"!",
"cb",
")",
"{",
"cb",
"=",
"opts",
"}",
"if",
"(",
"!",
"opts",
"||",
"typeof",
"opts",
"===",
"'function'",
")",
"{",
"opts",
"=",
"{",
"}",
"}",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"createOnly",
"}",
"=",
"opts",
"const",
"tasks",
"=",
"[",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"const",
"id",
"=",
"params",
".",
"id",
"||",
"uuid",
"(",
")",
"params",
".",
"id",
"=",
"id",
"const",
"{",
"name",
",",
"description",
",",
"metadata",
",",
"user",
"}",
"=",
"params",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"name",
",",
"description",
",",
"metadata",
",",
"user",
"}",
",",
"validationRules",
".",
"create",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"next",
"(",
")",
"}",
")",
"}",
",",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"job",
".",
"params",
"=",
"params",
"job",
".",
"user",
"=",
"params",
".",
"user",
"next",
"(",
")",
"}",
",",
"insertOrganization",
"]",
"if",
"(",
"!",
"createOnly",
")",
"{",
"tasks",
".",
"push",
"(",
"createDefaultPolicies",
",",
"insertOrgAdminUser",
")",
"}",
"db",
".",
"withTransaction",
"(",
"tasks",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"organizationOps",
".",
"readById",
"(",
"res",
".",
"organization",
".",
"id",
",",
"(",
"err",
",",
"organization",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badImplementation",
"(",
"err",
")",
")",
"cb",
"(",
"null",
",",
"{",
"organization",
",",
"user",
":",
"res",
".",
"user",
"}",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
Creates a new organization
@param {Object} params {id, name, description, metadata, user} "metadata" optional
@param {Object} opts { createOnly }
@param {Function} cb
|
[
"Creates",
"a",
"new",
"organization"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/organizationOps.js#L308-L358
|
15,740
|
nearform/udaru
|
packages/udaru-core/lib/ops/organizationOps.js
|
replaceOrganizationPolicies
|
function replaceOrganizationPolicies (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, policies } = params
const tasks = [
(job, next) => {
Joi.validate({ id, policies }, validationRules.replaceOrganizationPolicies, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.id = id
job.policies = utils.preparePolicies(policies)
next()
},
checkOrg,
clearOrganizationAttachedPolicies
]
if (policies.length > 0) {
tasks.push((job, next) => {
utils.checkPoliciesOrg(job.client, job.policies, job.id, next)
})
tasks.push(insertOrgPolicies)
}
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
organizationOps.readById(id, cb)
})
return promise
}
|
javascript
|
function replaceOrganizationPolicies (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, policies } = params
const tasks = [
(job, next) => {
Joi.validate({ id, policies }, validationRules.replaceOrganizationPolicies, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.id = id
job.policies = utils.preparePolicies(policies)
next()
},
checkOrg,
clearOrganizationAttachedPolicies
]
if (policies.length > 0) {
tasks.push((job, next) => {
utils.checkPoliciesOrg(job.client, job.policies, job.id, next)
})
tasks.push(insertOrgPolicies)
}
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
organizationOps.readById(id, cb)
})
return promise
}
|
[
"function",
"replaceOrganizationPolicies",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"id",
",",
"policies",
"}",
"=",
"params",
"const",
"tasks",
"=",
"[",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"policies",
"}",
",",
"validationRules",
".",
"replaceOrganizationPolicies",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"next",
"(",
")",
"}",
")",
"}",
",",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"job",
".",
"id",
"=",
"id",
"job",
".",
"policies",
"=",
"utils",
".",
"preparePolicies",
"(",
"policies",
")",
"next",
"(",
")",
"}",
",",
"checkOrg",
",",
"clearOrganizationAttachedPolicies",
"]",
"if",
"(",
"policies",
".",
"length",
">",
"0",
")",
"{",
"tasks",
".",
"push",
"(",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"utils",
".",
"checkPoliciesOrg",
"(",
"job",
".",
"client",
",",
"job",
".",
"policies",
",",
"job",
".",
"id",
",",
"next",
")",
"}",
")",
"tasks",
".",
"push",
"(",
"insertOrgPolicies",
")",
"}",
"db",
".",
"withTransaction",
"(",
"tasks",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"organizationOps",
".",
"readById",
"(",
"id",
",",
"cb",
")",
"}",
")",
"return",
"promise",
"}"
] |
Replace organization policies
@param {Object} params { id, policies }
@param {Function} cb
|
[
"Replace",
"organization",
"policies"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/organizationOps.js#L439-L475
|
15,741
|
nearform/udaru
|
packages/udaru-core/lib/ops/organizationOps.js
|
deleteOrganizationAttachedPolicies
|
function deleteOrganizationAttachedPolicies (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id } = params
const tasks = [
(job, next) => {
Joi.validate({ id }, validationRules.deleteOrganizationPolicies, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.id = id
next()
},
checkOrg,
clearOrganizationAttachedPolicies
]
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
organizationOps.readById(id, cb)
})
return promise
}
|
javascript
|
function deleteOrganizationAttachedPolicies (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id } = params
const tasks = [
(job, next) => {
Joi.validate({ id }, validationRules.deleteOrganizationPolicies, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.id = id
next()
},
checkOrg,
clearOrganizationAttachedPolicies
]
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
organizationOps.readById(id, cb)
})
return promise
}
|
[
"function",
"deleteOrganizationAttachedPolicies",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"id",
"}",
"=",
"params",
"const",
"tasks",
"=",
"[",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"Joi",
".",
"validate",
"(",
"{",
"id",
"}",
",",
"validationRules",
".",
"deleteOrganizationPolicies",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"next",
"(",
")",
"}",
")",
"}",
",",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"job",
".",
"id",
"=",
"id",
"next",
"(",
")",
"}",
",",
"checkOrg",
",",
"clearOrganizationAttachedPolicies",
"]",
"db",
".",
"withTransaction",
"(",
"tasks",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"organizationOps",
".",
"readById",
"(",
"id",
",",
"cb",
")",
"}",
")",
"return",
"promise",
"}"
] |
Rmove all organization's attached policies
@param {Object} params { id, organizationId }
@param {Function} cb
|
[
"Rmove",
"all",
"organization",
"s",
"attached",
"policies"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/organizationOps.js#L572-L600
|
15,742
|
nearform/udaru
|
packages/udaru-core/lib/ops/organizationOps.js
|
deleteOrganizationAttachedPolicy
|
function deleteOrganizationAttachedPolicy (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, policyId, instance } = params
const tasks = [
(job, next) => {
Joi.validate({ id, policyId, instance }, validationRules.deleteOrganizationPolicy, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.id = id
job.policyId = policyId
job.instance = instance
next()
},
checkOrg,
clearOrganizationAttachedPolicy
]
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
organizationOps.readById(id, cb)
})
return promise
}
|
javascript
|
function deleteOrganizationAttachedPolicy (params, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
const { id, policyId, instance } = params
const tasks = [
(job, next) => {
Joi.validate({ id, policyId, instance }, validationRules.deleteOrganizationPolicy, (err) => {
if (err) return next(Boom.badRequest(err))
next()
})
},
(job, next) => {
job.id = id
job.policyId = policyId
job.instance = instance
next()
},
checkOrg,
clearOrganizationAttachedPolicy
]
db.withTransaction(tasks, (err, res) => {
if (err) return cb(err)
organizationOps.readById(id, cb)
})
return promise
}
|
[
"function",
"deleteOrganizationAttachedPolicy",
"(",
"params",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"const",
"{",
"id",
",",
"policyId",
",",
"instance",
"}",
"=",
"params",
"const",
"tasks",
"=",
"[",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"policyId",
",",
"instance",
"}",
",",
"validationRules",
".",
"deleteOrganizationPolicy",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"next",
"(",
")",
"}",
")",
"}",
",",
"(",
"job",
",",
"next",
")",
"=>",
"{",
"job",
".",
"id",
"=",
"id",
"job",
".",
"policyId",
"=",
"policyId",
"job",
".",
"instance",
"=",
"instance",
"next",
"(",
")",
"}",
",",
"checkOrg",
",",
"clearOrganizationAttachedPolicy",
"]",
"db",
".",
"withTransaction",
"(",
"tasks",
",",
"(",
"err",
",",
"res",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"organizationOps",
".",
"readById",
"(",
"id",
",",
"cb",
")",
"}",
")",
"return",
"promise",
"}"
] |
Remove one organization policy
@param {Object} params { id, policyId, instance } "instance" optional
@param {Function} cb
|
[
"Remove",
"one",
"organization",
"policy"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/organizationOps.js#L608-L638
|
15,743
|
nearform/udaru
|
packages/udaru-core/lib/ops/organizationOps.js
|
listOrganizationPolicies
|
function listOrganizationPolicies ({ id, organizationId, page = 1, limit }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
Joi.validate({ id, organizationId, page, limit }, validationRules.listOrganizationPolicies, function (err) {
if (err) return cb(Boom.badRequest(err))
const offset = (page - 1) * limit
const job = {
id,
organizationId,
offset,
limit,
organization: {},
client: db
}
loadOrganizationPolicies(job, (err) => {
if (err) return cb(err)
const pageSize = limit || job.totalPoliciesCount
const result = {
page: page,
limit: pageSize,
total: job.totalPoliciesCount,
data: job.organization.policies
}
return cb(null, result)
})
})
return promise
}
|
javascript
|
function listOrganizationPolicies ({ id, organizationId, page = 1, limit }, cb) {
let promise = null
if (typeof cb !== 'function') [promise, cb] = asyncify()
Joi.validate({ id, organizationId, page, limit }, validationRules.listOrganizationPolicies, function (err) {
if (err) return cb(Boom.badRequest(err))
const offset = (page - 1) * limit
const job = {
id,
organizationId,
offset,
limit,
organization: {},
client: db
}
loadOrganizationPolicies(job, (err) => {
if (err) return cb(err)
const pageSize = limit || job.totalPoliciesCount
const result = {
page: page,
limit: pageSize,
total: job.totalPoliciesCount,
data: job.organization.policies
}
return cb(null, result)
})
})
return promise
}
|
[
"function",
"listOrganizationPolicies",
"(",
"{",
"id",
",",
"organizationId",
",",
"page",
"=",
"1",
",",
"limit",
"}",
",",
"cb",
")",
"{",
"let",
"promise",
"=",
"null",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"[",
"promise",
",",
"cb",
"]",
"=",
"asyncify",
"(",
")",
"Joi",
".",
"validate",
"(",
"{",
"id",
",",
"organizationId",
",",
"page",
",",
"limit",
"}",
",",
"validationRules",
".",
"listOrganizationPolicies",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"Boom",
".",
"badRequest",
"(",
"err",
")",
")",
"const",
"offset",
"=",
"(",
"page",
"-",
"1",
")",
"*",
"limit",
"const",
"job",
"=",
"{",
"id",
",",
"organizationId",
",",
"offset",
",",
"limit",
",",
"organization",
":",
"{",
"}",
",",
"client",
":",
"db",
"}",
"loadOrganizationPolicies",
"(",
"job",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"const",
"pageSize",
"=",
"limit",
"||",
"job",
".",
"totalPoliciesCount",
"const",
"result",
"=",
"{",
"page",
":",
"page",
",",
"limit",
":",
"pageSize",
",",
"total",
":",
"job",
".",
"totalPoliciesCount",
",",
"data",
":",
"job",
".",
"organization",
".",
"policies",
"}",
"return",
"cb",
"(",
"null",
",",
"result",
")",
"}",
")",
"}",
")",
"return",
"promise",
"}"
] |
List an organizations policies
@param {Object} params { id, organizationId, limit, page }
@param {Function} cb
|
[
"List",
"an",
"organizations",
"policies"
] |
1e69f8e2d7e5734d05b7954fa4b86801e96d17b2
|
https://github.com/nearform/udaru/blob/1e69f8e2d7e5734d05b7954fa4b86801e96d17b2/packages/udaru-core/lib/ops/organizationOps.js#L712-L743
|
15,744
|
skonves/express-http-context
|
index.js
|
set
|
function set(key, value) {
if (ns && ns.active) {
return ns.set(key, value);
}
}
|
javascript
|
function set(key, value) {
if (ns && ns.active) {
return ns.set(key, value);
}
}
|
[
"function",
"set",
"(",
"key",
",",
"value",
")",
"{",
"if",
"(",
"ns",
"&&",
"ns",
".",
"active",
")",
"{",
"return",
"ns",
".",
"set",
"(",
"key",
",",
"value",
")",
";",
"}",
"}"
] |
Adds a value to the context by key. If the key already exists, its value will be overwritten. No value will persist if the context has not yet been initialized.
@param {string} key
@param {*} value
|
[
"Adds",
"a",
"value",
"to",
"the",
"context",
"by",
"key",
".",
"If",
"the",
"key",
"already",
"exists",
"its",
"value",
"will",
"be",
"overwritten",
".",
"No",
"value",
"will",
"persist",
"if",
"the",
"context",
"has",
"not",
"yet",
"been",
"initialized",
"."
] |
e390acadb41219cc5c763b41cd5e959758594ef5
|
https://github.com/skonves/express-http-context/blob/e390acadb41219cc5c763b41cd5e959758594ef5/index.js#L28-L32
|
15,745
|
devote/HTML5-History-API
|
history.js
|
function(basepath, type, redirect) {
settings["basepath"] = ('' + (basepath == null ? settings["basepath"] : basepath))
.replace(/(?:^|\/)[^\/]*$/, '/');
settings["type"] = type == null ? settings["type"] : type;
settings["redirect"] = redirect == null ? settings["redirect"] : !!redirect;
}
|
javascript
|
function(basepath, type, redirect) {
settings["basepath"] = ('' + (basepath == null ? settings["basepath"] : basepath))
.replace(/(?:^|\/)[^\/]*$/, '/');
settings["type"] = type == null ? settings["type"] : type;
settings["redirect"] = redirect == null ? settings["redirect"] : !!redirect;
}
|
[
"function",
"(",
"basepath",
",",
"type",
",",
"redirect",
")",
"{",
"settings",
"[",
"\"basepath\"",
"]",
"=",
"(",
"''",
"+",
"(",
"basepath",
"==",
"null",
"?",
"settings",
"[",
"\"basepath\"",
"]",
":",
"basepath",
")",
")",
".",
"replace",
"(",
"/",
"(?:^|\\/)[^\\/]*$",
"/",
",",
"'/'",
")",
";",
"settings",
"[",
"\"type\"",
"]",
"=",
"type",
"==",
"null",
"?",
"settings",
"[",
"\"type\"",
"]",
":",
"type",
";",
"settings",
"[",
"\"redirect\"",
"]",
"=",
"redirect",
"==",
"null",
"?",
"settings",
"[",
"\"redirect\"",
"]",
":",
"!",
"!",
"redirect",
";",
"}"
] |
Setting library initialization
@param {null|String} [basepath] The base path to the site; defaults to the root "/".
@param {null|String} [type] Substitute the string after the anchor; by default "/".
@param {null|Boolean} [redirect] Enable link translation.
|
[
"Setting",
"library",
"initialization"
] |
2cad95c15985c7e7ba7091ff80d894f63a3c3c03
|
https://github.com/devote/HTML5-History-API/blob/2cad95c15985c7e7ba7091ff80d894f63a3c3c03/history.js#L149-L154
|
|
15,746
|
devote/HTML5-History-API
|
history.js
|
function(state, title, url) {
var t = document.title;
if (lastTitle != null) {
document.title = lastTitle;
}
historyPushState && fastFixChrome(historyPushState, arguments);
changeState(state, url);
document.title = t;
lastTitle = title;
}
|
javascript
|
function(state, title, url) {
var t = document.title;
if (lastTitle != null) {
document.title = lastTitle;
}
historyPushState && fastFixChrome(historyPushState, arguments);
changeState(state, url);
document.title = t;
lastTitle = title;
}
|
[
"function",
"(",
"state",
",",
"title",
",",
"url",
")",
"{",
"var",
"t",
"=",
"document",
".",
"title",
";",
"if",
"(",
"lastTitle",
"!=",
"null",
")",
"{",
"document",
".",
"title",
"=",
"lastTitle",
";",
"}",
"historyPushState",
"&&",
"fastFixChrome",
"(",
"historyPushState",
",",
"arguments",
")",
";",
"changeState",
"(",
"state",
",",
"url",
")",
";",
"document",
".",
"title",
"=",
"t",
";",
"lastTitle",
"=",
"title",
";",
"}"
] |
The method adds a state object entry
to the history.
@namespace history
@param {Object} state
@param {string} title
@param {string} [url]
|
[
"The",
"method",
"adds",
"a",
"state",
"object",
"entry",
"to",
"the",
"history",
"."
] |
2cad95c15985c7e7ba7091ff80d894f63a3c3c03
|
https://github.com/devote/HTML5-History-API/blob/2cad95c15985c7e7ba7091ff80d894f63a3c3c03/history.js#L189-L198
|
|
15,747
|
devote/HTML5-History-API
|
history.js
|
function(state, title, url) {
var t = document.title;
if (lastTitle != null) {
document.title = lastTitle;
}
delete stateStorage[windowLocation.href];
historyReplaceState && fastFixChrome(historyReplaceState, arguments);
changeState(state, url, true);
document.title = t;
lastTitle = title;
}
|
javascript
|
function(state, title, url) {
var t = document.title;
if (lastTitle != null) {
document.title = lastTitle;
}
delete stateStorage[windowLocation.href];
historyReplaceState && fastFixChrome(historyReplaceState, arguments);
changeState(state, url, true);
document.title = t;
lastTitle = title;
}
|
[
"function",
"(",
"state",
",",
"title",
",",
"url",
")",
"{",
"var",
"t",
"=",
"document",
".",
"title",
";",
"if",
"(",
"lastTitle",
"!=",
"null",
")",
"{",
"document",
".",
"title",
"=",
"lastTitle",
";",
"}",
"delete",
"stateStorage",
"[",
"windowLocation",
".",
"href",
"]",
";",
"historyReplaceState",
"&&",
"fastFixChrome",
"(",
"historyReplaceState",
",",
"arguments",
")",
";",
"changeState",
"(",
"state",
",",
"url",
",",
"true",
")",
";",
"document",
".",
"title",
"=",
"t",
";",
"lastTitle",
"=",
"title",
";",
"}"
] |
The method updates the state object,
title, and optionally the URL of the
current entry in the history.
@namespace history
@param {Object} state
@param {string} title
@param {string} [url]
|
[
"The",
"method",
"updates",
"the",
"state",
"object",
"title",
"and",
"optionally",
"the",
"URL",
"of",
"the",
"current",
"entry",
"in",
"the",
"history",
"."
] |
2cad95c15985c7e7ba7091ff80d894f63a3c3c03
|
https://github.com/devote/HTML5-History-API/blob/2cad95c15985c7e7ba7091ff80d894f63a3c3c03/history.js#L209-L219
|
|
15,748
|
devote/HTML5-History-API
|
history.js
|
function(url) {
if (!isSupportHistoryAPI && ('' + url).indexOf('#') === 0) {
changeState(null, url);
} else {
windowLocation.assign(url);
}
}
|
javascript
|
function(url) {
if (!isSupportHistoryAPI && ('' + url).indexOf('#') === 0) {
changeState(null, url);
} else {
windowLocation.assign(url);
}
}
|
[
"function",
"(",
"url",
")",
"{",
"if",
"(",
"!",
"isSupportHistoryAPI",
"&&",
"(",
"''",
"+",
"url",
")",
".",
"indexOf",
"(",
"'#'",
")",
"===",
"0",
")",
"{",
"changeState",
"(",
"null",
",",
"url",
")",
";",
"}",
"else",
"{",
"windowLocation",
".",
"assign",
"(",
"url",
")",
";",
"}",
"}"
] |
Navigates to the given page.
@namespace history.location
|
[
"Navigates",
"to",
"the",
"given",
"page",
"."
] |
2cad95c15985c7e7ba7091ff80d894f63a3c3c03
|
https://github.com/devote/HTML5-History-API/blob/2cad95c15985c7e7ba7091ff80d894f63a3c3c03/history.js#L270-L276
|
|
15,749
|
devote/HTML5-History-API
|
history.js
|
function(url) {
if (!isSupportHistoryAPI && ('' + url).indexOf('#') === 0) {
changeState(null, url, true);
} else {
windowLocation.replace(url);
}
}
|
javascript
|
function(url) {
if (!isSupportHistoryAPI && ('' + url).indexOf('#') === 0) {
changeState(null, url, true);
} else {
windowLocation.replace(url);
}
}
|
[
"function",
"(",
"url",
")",
"{",
"if",
"(",
"!",
"isSupportHistoryAPI",
"&&",
"(",
"''",
"+",
"url",
")",
".",
"indexOf",
"(",
"'#'",
")",
"===",
"0",
")",
"{",
"changeState",
"(",
"null",
",",
"url",
",",
"true",
")",
";",
"}",
"else",
"{",
"windowLocation",
".",
"replace",
"(",
"url",
")",
";",
"}",
"}"
] |
Removes the current page from
the session history and navigates
to the given page.
@namespace history.location
|
[
"Removes",
"the",
"current",
"page",
"from",
"the",
"session",
"history",
"and",
"navigates",
"to",
"the",
"given",
"page",
"."
] |
2cad95c15985c7e7ba7091ff80d894f63a3c3c03
|
https://github.com/devote/HTML5-History-API/blob/2cad95c15985c7e7ba7091ff80d894f63a3c3c03/history.js#L292-L298
|
|
15,750
|
devote/HTML5-History-API
|
history.js
|
parseURL
|
function parseURL(href, isWindowLocation, isNotAPI) {
var re = /(?:([a-zA-Z0-9\-]+\:))?(?:\/\/(?:[^@]*@)?([^\/:\?#]+)(?::([0-9]+))?)?([^\?#]*)(?:(\?[^#]+)|\?)?(?:(#.*))?/;
if (href != null && href !== '' && !isWindowLocation) {
var current = parseURL(),
base = document.getElementsByTagName('base')[0];
if (!isNotAPI && base && base.getAttribute('href')) {
// Fix for IE ignoring relative base tags.
// See http://stackoverflow.com/questions/3926197/html-base-tag-and-local-folder-path-with-internet-explorer
base.href = base.href;
current = parseURL(base.href, null, true);
}
var _pathname = current._pathname, _protocol = current._protocol;
// convert to type of string
href = '' + href;
// convert relative link to the absolute
href = /^(?:\w+\:)?\/\//.test(href) ? href.indexOf("/") === 0
? _protocol + href : href : _protocol + "//" + current._host + (
href.indexOf("/") === 0 ? href : href.indexOf("?") === 0
? _pathname + href : href.indexOf("#") === 0
? _pathname + current._search + href : _pathname.replace(/[^\/]+$/g, '') + href
);
} else {
href = isWindowLocation ? href : windowLocation.href;
// if current browser not support History-API
if (!isSupportHistoryAPI || isNotAPI) {
// get hash fragment
href = href.replace(/^[^#]*/, '') || "#";
// form the absolute link from the hash
// https://github.com/devote/HTML5-History-API/issues/50
href = windowLocation.protocol.replace(/:.*$|$/, ':') + '//' + windowLocation.host + settings['basepath']
+ href.replace(new RegExp("^#[\/]?(?:" + settings["type"] + ")?"), "");
}
}
// that would get rid of the links of the form: /../../
anchorElement.href = href;
// decompose the link in parts
var result = re.exec(anchorElement.href);
// host name with the port number
var host = result[2] + (result[3] ? ':' + result[3] : '');
// folder
var pathname = result[4] || '/';
// the query string
var search = result[5] || '';
// hash
var hash = result[6] === '#' ? '' : (result[6] || '');
// relative link, no protocol, no host
var relative = pathname + search + hash;
// special links for set to hash-link, if browser not support History API
var nohash = pathname.replace(new RegExp("^" + settings["basepath"], "i"), settings["type"]) + search;
// result
return {
_href: result[1] + '//' + host + relative,
_protocol: result[1],
_host: host,
_hostname: result[2],
_port: result[3] || '',
_pathname: pathname,
_search: search,
_hash: hash,
_relative: relative,
_nohash: nohash,
_special: nohash + hash
}
}
|
javascript
|
function parseURL(href, isWindowLocation, isNotAPI) {
var re = /(?:([a-zA-Z0-9\-]+\:))?(?:\/\/(?:[^@]*@)?([^\/:\?#]+)(?::([0-9]+))?)?([^\?#]*)(?:(\?[^#]+)|\?)?(?:(#.*))?/;
if (href != null && href !== '' && !isWindowLocation) {
var current = parseURL(),
base = document.getElementsByTagName('base')[0];
if (!isNotAPI && base && base.getAttribute('href')) {
// Fix for IE ignoring relative base tags.
// See http://stackoverflow.com/questions/3926197/html-base-tag-and-local-folder-path-with-internet-explorer
base.href = base.href;
current = parseURL(base.href, null, true);
}
var _pathname = current._pathname, _protocol = current._protocol;
// convert to type of string
href = '' + href;
// convert relative link to the absolute
href = /^(?:\w+\:)?\/\//.test(href) ? href.indexOf("/") === 0
? _protocol + href : href : _protocol + "//" + current._host + (
href.indexOf("/") === 0 ? href : href.indexOf("?") === 0
? _pathname + href : href.indexOf("#") === 0
? _pathname + current._search + href : _pathname.replace(/[^\/]+$/g, '') + href
);
} else {
href = isWindowLocation ? href : windowLocation.href;
// if current browser not support History-API
if (!isSupportHistoryAPI || isNotAPI) {
// get hash fragment
href = href.replace(/^[^#]*/, '') || "#";
// form the absolute link from the hash
// https://github.com/devote/HTML5-History-API/issues/50
href = windowLocation.protocol.replace(/:.*$|$/, ':') + '//' + windowLocation.host + settings['basepath']
+ href.replace(new RegExp("^#[\/]?(?:" + settings["type"] + ")?"), "");
}
}
// that would get rid of the links of the form: /../../
anchorElement.href = href;
// decompose the link in parts
var result = re.exec(anchorElement.href);
// host name with the port number
var host = result[2] + (result[3] ? ':' + result[3] : '');
// folder
var pathname = result[4] || '/';
// the query string
var search = result[5] || '';
// hash
var hash = result[6] === '#' ? '' : (result[6] || '');
// relative link, no protocol, no host
var relative = pathname + search + hash;
// special links for set to hash-link, if browser not support History API
var nohash = pathname.replace(new RegExp("^" + settings["basepath"], "i"), settings["type"]) + search;
// result
return {
_href: result[1] + '//' + host + relative,
_protocol: result[1],
_host: host,
_hostname: result[2],
_port: result[3] || '',
_pathname: pathname,
_search: search,
_hash: hash,
_relative: relative,
_nohash: nohash,
_special: nohash + hash
}
}
|
[
"function",
"parseURL",
"(",
"href",
",",
"isWindowLocation",
",",
"isNotAPI",
")",
"{",
"var",
"re",
"=",
"/",
"(?:([a-zA-Z0-9\\-]+\\:))?(?:\\/\\/(?:[^@]*@)?([^\\/:\\?#]+)(?::([0-9]+))?)?([^\\?#]*)(?:(\\?[^#]+)|\\?)?(?:(#.*))?",
"/",
";",
"if",
"(",
"href",
"!=",
"null",
"&&",
"href",
"!==",
"''",
"&&",
"!",
"isWindowLocation",
")",
"{",
"var",
"current",
"=",
"parseURL",
"(",
")",
",",
"base",
"=",
"document",
".",
"getElementsByTagName",
"(",
"'base'",
")",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"isNotAPI",
"&&",
"base",
"&&",
"base",
".",
"getAttribute",
"(",
"'href'",
")",
")",
"{",
"// Fix for IE ignoring relative base tags.",
"// See http://stackoverflow.com/questions/3926197/html-base-tag-and-local-folder-path-with-internet-explorer",
"base",
".",
"href",
"=",
"base",
".",
"href",
";",
"current",
"=",
"parseURL",
"(",
"base",
".",
"href",
",",
"null",
",",
"true",
")",
";",
"}",
"var",
"_pathname",
"=",
"current",
".",
"_pathname",
",",
"_protocol",
"=",
"current",
".",
"_protocol",
";",
"// convert to type of string",
"href",
"=",
"''",
"+",
"href",
";",
"// convert relative link to the absolute",
"href",
"=",
"/",
"^(?:\\w+\\:)?\\/\\/",
"/",
".",
"test",
"(",
"href",
")",
"?",
"href",
".",
"indexOf",
"(",
"\"/\"",
")",
"===",
"0",
"?",
"_protocol",
"+",
"href",
":",
"href",
":",
"_protocol",
"+",
"\"//\"",
"+",
"current",
".",
"_host",
"+",
"(",
"href",
".",
"indexOf",
"(",
"\"/\"",
")",
"===",
"0",
"?",
"href",
":",
"href",
".",
"indexOf",
"(",
"\"?\"",
")",
"===",
"0",
"?",
"_pathname",
"+",
"href",
":",
"href",
".",
"indexOf",
"(",
"\"#\"",
")",
"===",
"0",
"?",
"_pathname",
"+",
"current",
".",
"_search",
"+",
"href",
":",
"_pathname",
".",
"replace",
"(",
"/",
"[^\\/]+$",
"/",
"g",
",",
"''",
")",
"+",
"href",
")",
";",
"}",
"else",
"{",
"href",
"=",
"isWindowLocation",
"?",
"href",
":",
"windowLocation",
".",
"href",
";",
"// if current browser not support History-API",
"if",
"(",
"!",
"isSupportHistoryAPI",
"||",
"isNotAPI",
")",
"{",
"// get hash fragment",
"href",
"=",
"href",
".",
"replace",
"(",
"/",
"^[^#]*",
"/",
",",
"''",
")",
"||",
"\"#\"",
";",
"// form the absolute link from the hash",
"// https://github.com/devote/HTML5-History-API/issues/50",
"href",
"=",
"windowLocation",
".",
"protocol",
".",
"replace",
"(",
"/",
":.*$|$",
"/",
",",
"':'",
")",
"+",
"'//'",
"+",
"windowLocation",
".",
"host",
"+",
"settings",
"[",
"'basepath'",
"]",
"+",
"href",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"\"^#[\\/]?(?:\"",
"+",
"settings",
"[",
"\"type\"",
"]",
"+",
"\")?\"",
")",
",",
"\"\"",
")",
";",
"}",
"}",
"// that would get rid of the links of the form: /../../",
"anchorElement",
".",
"href",
"=",
"href",
";",
"// decompose the link in parts",
"var",
"result",
"=",
"re",
".",
"exec",
"(",
"anchorElement",
".",
"href",
")",
";",
"// host name with the port number",
"var",
"host",
"=",
"result",
"[",
"2",
"]",
"+",
"(",
"result",
"[",
"3",
"]",
"?",
"':'",
"+",
"result",
"[",
"3",
"]",
":",
"''",
")",
";",
"// folder",
"var",
"pathname",
"=",
"result",
"[",
"4",
"]",
"||",
"'/'",
";",
"// the query string",
"var",
"search",
"=",
"result",
"[",
"5",
"]",
"||",
"''",
";",
"// hash",
"var",
"hash",
"=",
"result",
"[",
"6",
"]",
"===",
"'#'",
"?",
"''",
":",
"(",
"result",
"[",
"6",
"]",
"||",
"''",
")",
";",
"// relative link, no protocol, no host",
"var",
"relative",
"=",
"pathname",
"+",
"search",
"+",
"hash",
";",
"// special links for set to hash-link, if browser not support History API",
"var",
"nohash",
"=",
"pathname",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"\"^\"",
"+",
"settings",
"[",
"\"basepath\"",
"]",
",",
"\"i\"",
")",
",",
"settings",
"[",
"\"type\"",
"]",
")",
"+",
"search",
";",
"// result",
"return",
"{",
"_href",
":",
"result",
"[",
"1",
"]",
"+",
"'//'",
"+",
"host",
"+",
"relative",
",",
"_protocol",
":",
"result",
"[",
"1",
"]",
",",
"_host",
":",
"host",
",",
"_hostname",
":",
"result",
"[",
"2",
"]",
",",
"_port",
":",
"result",
"[",
"3",
"]",
"||",
"''",
",",
"_pathname",
":",
"pathname",
",",
"_search",
":",
"search",
",",
"_hash",
":",
"hash",
",",
"_relative",
":",
"relative",
",",
"_nohash",
":",
"nohash",
",",
"_special",
":",
"nohash",
"+",
"hash",
"}",
"}"
] |
Prepares a parts of the current or specified reference for later use in the library
@param {string} [href]
@param {boolean} [isWindowLocation]
@param {boolean} [isNotAPI]
@return {Object}
|
[
"Prepares",
"a",
"parts",
"of",
"the",
"current",
"or",
"specified",
"reference",
"for",
"later",
"use",
"in",
"the",
"library"
] |
2cad95c15985c7e7ba7091ff80d894f63a3c3c03
|
https://github.com/devote/HTML5-History-API/blob/2cad95c15985c7e7ba7091ff80d894f63a3c3c03/history.js#L417-L480
|
15,751
|
devote/HTML5-History-API
|
history.js
|
maybeBindToGlobal
|
function maybeBindToGlobal(func) {
if (func && global &&
global['EventTarget'] &&
typeof global['EventTarget'].prototype.addEventListener === 'function' &&
typeof func.bind === 'function') {
return func.bind(global);
}
return func;
}
|
javascript
|
function maybeBindToGlobal(func) {
if (func && global &&
global['EventTarget'] &&
typeof global['EventTarget'].prototype.addEventListener === 'function' &&
typeof func.bind === 'function') {
return func.bind(global);
}
return func;
}
|
[
"function",
"maybeBindToGlobal",
"(",
"func",
")",
"{",
"if",
"(",
"func",
"&&",
"global",
"&&",
"global",
"[",
"'EventTarget'",
"]",
"&&",
"typeof",
"global",
"[",
"'EventTarget'",
"]",
".",
"prototype",
".",
"addEventListener",
"===",
"'function'",
"&&",
"typeof",
"func",
".",
"bind",
"===",
"'function'",
")",
"{",
"return",
"func",
".",
"bind",
"(",
"global",
")",
";",
"}",
"return",
"func",
";",
"}"
] |
This method attempts to bind a function to global.
@param {Function} [func] The function to be bound
@return {Function} Returns the bound function or func
|
[
"This",
"method",
"attempts",
"to",
"bind",
"a",
"function",
"to",
"global",
"."
] |
2cad95c15985c7e7ba7091ff80d894f63a3c3c03
|
https://github.com/devote/HTML5-History-API/blob/2cad95c15985c7e7ba7091ff80d894f63a3c3c03/history.js#L508-L516
|
15,752
|
devote/HTML5-History-API
|
history.js
|
storageInitialize
|
function storageInitialize() {
var sessionStorage;
/**
* sessionStorage throws error when cookies are disabled
* Chrome content settings when running the site in a Facebook IFrame.
* see: https://github.com/devote/HTML5-History-API/issues/34
* and: http://stackoverflow.com/a/12976988/669360
*/
try {
sessionStorage = global['sessionStorage'];
sessionStorage.setItem(sessionStorageKey + 't', '1');
sessionStorage.removeItem(sessionStorageKey + 't');
} catch(_e_) {
sessionStorage = {
getItem: function(key) {
var cookie = document.cookie.split(key + "=");
return cookie.length > 1 && cookie.pop().split(";").shift() || 'null';
},
setItem: function(key, value) {
var state = {};
// insert one current element to cookie
if (state[windowLocation.href] = historyObject.state) {
document.cookie = key + '=' + JSON.stringify(state);
}
}
}
}
try {
// get cache from the storage in browser
stateStorage = JSON.parse(sessionStorage.getItem(sessionStorageKey)) || {};
} catch(_e_) {
stateStorage = {};
}
// hang up the event handler to event unload page
addEvent(eventNamePrefix + 'unload', function() {
// save current state's object
sessionStorage.setItem(sessionStorageKey, JSON.stringify(stateStorage));
}, false);
}
|
javascript
|
function storageInitialize() {
var sessionStorage;
/**
* sessionStorage throws error when cookies are disabled
* Chrome content settings when running the site in a Facebook IFrame.
* see: https://github.com/devote/HTML5-History-API/issues/34
* and: http://stackoverflow.com/a/12976988/669360
*/
try {
sessionStorage = global['sessionStorage'];
sessionStorage.setItem(sessionStorageKey + 't', '1');
sessionStorage.removeItem(sessionStorageKey + 't');
} catch(_e_) {
sessionStorage = {
getItem: function(key) {
var cookie = document.cookie.split(key + "=");
return cookie.length > 1 && cookie.pop().split(";").shift() || 'null';
},
setItem: function(key, value) {
var state = {};
// insert one current element to cookie
if (state[windowLocation.href] = historyObject.state) {
document.cookie = key + '=' + JSON.stringify(state);
}
}
}
}
try {
// get cache from the storage in browser
stateStorage = JSON.parse(sessionStorage.getItem(sessionStorageKey)) || {};
} catch(_e_) {
stateStorage = {};
}
// hang up the event handler to event unload page
addEvent(eventNamePrefix + 'unload', function() {
// save current state's object
sessionStorage.setItem(sessionStorageKey, JSON.stringify(stateStorage));
}, false);
}
|
[
"function",
"storageInitialize",
"(",
")",
"{",
"var",
"sessionStorage",
";",
"/**\n * sessionStorage throws error when cookies are disabled\n * Chrome content settings when running the site in a Facebook IFrame.\n * see: https://github.com/devote/HTML5-History-API/issues/34\n * and: http://stackoverflow.com/a/12976988/669360\n */",
"try",
"{",
"sessionStorage",
"=",
"global",
"[",
"'sessionStorage'",
"]",
";",
"sessionStorage",
".",
"setItem",
"(",
"sessionStorageKey",
"+",
"'t'",
",",
"'1'",
")",
";",
"sessionStorage",
".",
"removeItem",
"(",
"sessionStorageKey",
"+",
"'t'",
")",
";",
"}",
"catch",
"(",
"_e_",
")",
"{",
"sessionStorage",
"=",
"{",
"getItem",
":",
"function",
"(",
"key",
")",
"{",
"var",
"cookie",
"=",
"document",
".",
"cookie",
".",
"split",
"(",
"key",
"+",
"\"=\"",
")",
";",
"return",
"cookie",
".",
"length",
">",
"1",
"&&",
"cookie",
".",
"pop",
"(",
")",
".",
"split",
"(",
"\";\"",
")",
".",
"shift",
"(",
")",
"||",
"'null'",
";",
"}",
",",
"setItem",
":",
"function",
"(",
"key",
",",
"value",
")",
"{",
"var",
"state",
"=",
"{",
"}",
";",
"// insert one current element to cookie",
"if",
"(",
"state",
"[",
"windowLocation",
".",
"href",
"]",
"=",
"historyObject",
".",
"state",
")",
"{",
"document",
".",
"cookie",
"=",
"key",
"+",
"'='",
"+",
"JSON",
".",
"stringify",
"(",
"state",
")",
";",
"}",
"}",
"}",
"}",
"try",
"{",
"// get cache from the storage in browser",
"stateStorage",
"=",
"JSON",
".",
"parse",
"(",
"sessionStorage",
".",
"getItem",
"(",
"sessionStorageKey",
")",
")",
"||",
"{",
"}",
";",
"}",
"catch",
"(",
"_e_",
")",
"{",
"stateStorage",
"=",
"{",
"}",
";",
"}",
"// hang up the event handler to event unload page",
"addEvent",
"(",
"eventNamePrefix",
"+",
"'unload'",
",",
"function",
"(",
")",
"{",
"// save current state's object",
"sessionStorage",
".",
"setItem",
"(",
"sessionStorageKey",
",",
"JSON",
".",
"stringify",
"(",
"stateStorage",
")",
")",
";",
"}",
",",
"false",
")",
";",
"}"
] |
Initializing storage for the custom state's object
|
[
"Initializing",
"storage",
"for",
"the",
"custom",
"state",
"s",
"object"
] |
2cad95c15985c7e7ba7091ff80d894f63a3c3c03
|
https://github.com/devote/HTML5-History-API/blob/2cad95c15985c7e7ba7091ff80d894f63a3c3c03/history.js#L521-L561
|
15,753
|
devote/HTML5-History-API
|
history.js
|
prepareDescriptorsForObject
|
function prepareDescriptorsForObject(object, prop, descriptor) {
descriptor = descriptor || {};
// the default for the object 'location' is the standard object 'window.location'
object = object === locationDescriptors ? windowLocation : object;
// setter for object properties
descriptor.set = (descriptor.set || function(value) {
object[prop] = value;
});
// getter for object properties
descriptor.get = (descriptor.get || function() {
return object[prop];
});
return descriptor;
}
|
javascript
|
function prepareDescriptorsForObject(object, prop, descriptor) {
descriptor = descriptor || {};
// the default for the object 'location' is the standard object 'window.location'
object = object === locationDescriptors ? windowLocation : object;
// setter for object properties
descriptor.set = (descriptor.set || function(value) {
object[prop] = value;
});
// getter for object properties
descriptor.get = (descriptor.get || function() {
return object[prop];
});
return descriptor;
}
|
[
"function",
"prepareDescriptorsForObject",
"(",
"object",
",",
"prop",
",",
"descriptor",
")",
"{",
"descriptor",
"=",
"descriptor",
"||",
"{",
"}",
";",
"// the default for the object 'location' is the standard object 'window.location'",
"object",
"=",
"object",
"===",
"locationDescriptors",
"?",
"windowLocation",
":",
"object",
";",
"// setter for object properties",
"descriptor",
".",
"set",
"=",
"(",
"descriptor",
".",
"set",
"||",
"function",
"(",
"value",
")",
"{",
"object",
"[",
"prop",
"]",
"=",
"value",
";",
"}",
")",
";",
"// getter for object properties",
"descriptor",
".",
"get",
"=",
"(",
"descriptor",
".",
"get",
"||",
"function",
"(",
")",
"{",
"return",
"object",
"[",
"prop",
"]",
";",
"}",
")",
";",
"return",
"descriptor",
";",
"}"
] |
Adds the missing property in descriptor
@param {Object} object An object that stores values
@param {String} prop Name of the property in the object
@param {Object|null} descriptor Descriptor
@return {Object} Returns the generated descriptor
|
[
"Adds",
"the",
"missing",
"property",
"in",
"descriptor"
] |
2cad95c15985c7e7ba7091ff80d894f63a3c3c03
|
https://github.com/devote/HTML5-History-API/blob/2cad95c15985c7e7ba7091ff80d894f63a3c3c03/history.js#L714-L727
|
15,754
|
devote/HTML5-History-API
|
history.js
|
firePopState
|
function firePopState() {
var o = document.createEvent ? document.createEvent('Event') : document.createEventObject();
if (o.initEvent) {
o.initEvent('popstate', false, false);
} else {
o.type = 'popstate';
}
o.state = historyObject.state;
// send a newly created events to be processed
dispatchEvent(o);
}
|
javascript
|
function firePopState() {
var o = document.createEvent ? document.createEvent('Event') : document.createEventObject();
if (o.initEvent) {
o.initEvent('popstate', false, false);
} else {
o.type = 'popstate';
}
o.state = historyObject.state;
// send a newly created events to be processed
dispatchEvent(o);
}
|
[
"function",
"firePopState",
"(",
")",
"{",
"var",
"o",
"=",
"document",
".",
"createEvent",
"?",
"document",
".",
"createEvent",
"(",
"'Event'",
")",
":",
"document",
".",
"createEventObject",
"(",
")",
";",
"if",
"(",
"o",
".",
"initEvent",
")",
"{",
"o",
".",
"initEvent",
"(",
"'popstate'",
",",
"false",
",",
"false",
")",
";",
"}",
"else",
"{",
"o",
".",
"type",
"=",
"'popstate'",
";",
"}",
"o",
".",
"state",
"=",
"historyObject",
".",
"state",
";",
"// send a newly created events to be processed",
"dispatchEvent",
"(",
"o",
")",
";",
"}"
] |
dispatch current state event
|
[
"dispatch",
"current",
"state",
"event"
] |
2cad95c15985c7e7ba7091ff80d894f63a3c3c03
|
https://github.com/devote/HTML5-History-API/blob/2cad95c15985c7e7ba7091ff80d894f63a3c3c03/history.js#L818-L828
|
15,755
|
devote/HTML5-History-API
|
history.js
|
changeState
|
function changeState(state, url, replace, lastURLValue) {
if (!isSupportHistoryAPI) {
// if not used implementation history.location
if (isUsedHistoryLocationFlag === 0) isUsedHistoryLocationFlag = 2;
// normalization url
var urlObject = parseURL(url, isUsedHistoryLocationFlag === 2 && ('' + url).indexOf("#") !== -1);
// if current url not equal new url
if (urlObject._relative !== parseURL()._relative) {
// if empty lastURLValue to skip hash change event
lastURL = lastURLValue;
if (replace) {
// only replace hash, not store to history
windowLocation.replace("#" + urlObject._special);
} else {
// change hash and add new record to history
windowLocation.hash = urlObject._special;
}
}
} else {
lastURL = windowLocation.href;
}
if (!isSupportStateObjectInHistory && state) {
stateStorage[windowLocation.href] = state;
}
isFireInitialState = false;
}
|
javascript
|
function changeState(state, url, replace, lastURLValue) {
if (!isSupportHistoryAPI) {
// if not used implementation history.location
if (isUsedHistoryLocationFlag === 0) isUsedHistoryLocationFlag = 2;
// normalization url
var urlObject = parseURL(url, isUsedHistoryLocationFlag === 2 && ('' + url).indexOf("#") !== -1);
// if current url not equal new url
if (urlObject._relative !== parseURL()._relative) {
// if empty lastURLValue to skip hash change event
lastURL = lastURLValue;
if (replace) {
// only replace hash, not store to history
windowLocation.replace("#" + urlObject._special);
} else {
// change hash and add new record to history
windowLocation.hash = urlObject._special;
}
}
} else {
lastURL = windowLocation.href;
}
if (!isSupportStateObjectInHistory && state) {
stateStorage[windowLocation.href] = state;
}
isFireInitialState = false;
}
|
[
"function",
"changeState",
"(",
"state",
",",
"url",
",",
"replace",
",",
"lastURLValue",
")",
"{",
"if",
"(",
"!",
"isSupportHistoryAPI",
")",
"{",
"// if not used implementation history.location",
"if",
"(",
"isUsedHistoryLocationFlag",
"===",
"0",
")",
"isUsedHistoryLocationFlag",
"=",
"2",
";",
"// normalization url",
"var",
"urlObject",
"=",
"parseURL",
"(",
"url",
",",
"isUsedHistoryLocationFlag",
"===",
"2",
"&&",
"(",
"''",
"+",
"url",
")",
".",
"indexOf",
"(",
"\"#\"",
")",
"!==",
"-",
"1",
")",
";",
"// if current url not equal new url",
"if",
"(",
"urlObject",
".",
"_relative",
"!==",
"parseURL",
"(",
")",
".",
"_relative",
")",
"{",
"// if empty lastURLValue to skip hash change event",
"lastURL",
"=",
"lastURLValue",
";",
"if",
"(",
"replace",
")",
"{",
"// only replace hash, not store to history",
"windowLocation",
".",
"replace",
"(",
"\"#\"",
"+",
"urlObject",
".",
"_special",
")",
";",
"}",
"else",
"{",
"// change hash and add new record to history",
"windowLocation",
".",
"hash",
"=",
"urlObject",
".",
"_special",
";",
"}",
"}",
"}",
"else",
"{",
"lastURL",
"=",
"windowLocation",
".",
"href",
";",
"}",
"if",
"(",
"!",
"isSupportStateObjectInHistory",
"&&",
"state",
")",
"{",
"stateStorage",
"[",
"windowLocation",
".",
"href",
"]",
"=",
"state",
";",
"}",
"isFireInitialState",
"=",
"false",
";",
"}"
] |
Change the data of the current history for HTML4 browsers
@param {Object} state
@param {string} [url]
@param {Boolean} [replace]
@param {string} [lastURLValue]
@return void
|
[
"Change",
"the",
"data",
"of",
"the",
"current",
"history",
"for",
"HTML4",
"browsers"
] |
2cad95c15985c7e7ba7091ff80d894f63a3c3c03
|
https://github.com/devote/HTML5-History-API/blob/2cad95c15985c7e7ba7091ff80d894f63a3c3c03/history.js#L849-L874
|
15,756
|
devote/HTML5-History-API
|
history.js
|
onHashChange
|
function onHashChange(event) {
// https://github.com/devote/HTML5-History-API/issues/46
var fireNow = lastURL;
// new value to lastURL
lastURL = windowLocation.href;
// if not empty fireNow, otherwise skipped the current handler event
if (fireNow) {
// if checkUrlForPopState equal current url, this means that the event was raised popstate browser
if (checkUrlForPopState !== windowLocation.href) {
// otherwise,
// the browser does not support popstate event or just does not run the event by changing the hash.
firePopState();
}
// current event object
event = event || global.event;
var oldURLObject = parseURL(fireNow, true);
var newURLObject = parseURL();
// HTML4 browser not support properties oldURL/newURL
if (!event.oldURL) {
event.oldURL = oldURLObject._href;
event.newURL = newURLObject._href;
}
if (oldURLObject._hash !== newURLObject._hash) {
// if current hash not equal previous hash
dispatchEvent(event);
}
}
}
|
javascript
|
function onHashChange(event) {
// https://github.com/devote/HTML5-History-API/issues/46
var fireNow = lastURL;
// new value to lastURL
lastURL = windowLocation.href;
// if not empty fireNow, otherwise skipped the current handler event
if (fireNow) {
// if checkUrlForPopState equal current url, this means that the event was raised popstate browser
if (checkUrlForPopState !== windowLocation.href) {
// otherwise,
// the browser does not support popstate event or just does not run the event by changing the hash.
firePopState();
}
// current event object
event = event || global.event;
var oldURLObject = parseURL(fireNow, true);
var newURLObject = parseURL();
// HTML4 browser not support properties oldURL/newURL
if (!event.oldURL) {
event.oldURL = oldURLObject._href;
event.newURL = newURLObject._href;
}
if (oldURLObject._hash !== newURLObject._hash) {
// if current hash not equal previous hash
dispatchEvent(event);
}
}
}
|
[
"function",
"onHashChange",
"(",
"event",
")",
"{",
"// https://github.com/devote/HTML5-History-API/issues/46",
"var",
"fireNow",
"=",
"lastURL",
";",
"// new value to lastURL",
"lastURL",
"=",
"windowLocation",
".",
"href",
";",
"// if not empty fireNow, otherwise skipped the current handler event",
"if",
"(",
"fireNow",
")",
"{",
"// if checkUrlForPopState equal current url, this means that the event was raised popstate browser",
"if",
"(",
"checkUrlForPopState",
"!==",
"windowLocation",
".",
"href",
")",
"{",
"// otherwise,",
"// the browser does not support popstate event or just does not run the event by changing the hash.",
"firePopState",
"(",
")",
";",
"}",
"// current event object",
"event",
"=",
"event",
"||",
"global",
".",
"event",
";",
"var",
"oldURLObject",
"=",
"parseURL",
"(",
"fireNow",
",",
"true",
")",
";",
"var",
"newURLObject",
"=",
"parseURL",
"(",
")",
";",
"// HTML4 browser not support properties oldURL/newURL",
"if",
"(",
"!",
"event",
".",
"oldURL",
")",
"{",
"event",
".",
"oldURL",
"=",
"oldURLObject",
".",
"_href",
";",
"event",
".",
"newURL",
"=",
"newURLObject",
".",
"_href",
";",
"}",
"if",
"(",
"oldURLObject",
".",
"_hash",
"!==",
"newURLObject",
".",
"_hash",
")",
"{",
"// if current hash not equal previous hash",
"dispatchEvent",
"(",
"event",
")",
";",
"}",
"}",
"}"
] |
Event handler function changes the hash in the address bar
@param {Event} event
@return void
|
[
"Event",
"handler",
"function",
"changes",
"the",
"hash",
"in",
"the",
"address",
"bar"
] |
2cad95c15985c7e7ba7091ff80d894f63a3c3c03
|
https://github.com/devote/HTML5-History-API/blob/2cad95c15985c7e7ba7091ff80d894f63a3c3c03/history.js#L882-L910
|
15,757
|
devote/HTML5-History-API
|
history.js
|
onLoad
|
function onLoad(noScroll) {
// Get rid of the events popstate when the first loading a document in the webkit browsers
setTimeout(function() {
// hang up the event handler for the built-in popstate event in the browser
addEvent('popstate', function(e) {
// set the current url, that suppress the creation of the popstate event by changing the hash
checkUrlForPopState = windowLocation.href;
// for Safari browser in OS Windows not implemented 'state' object in 'History' interface
// and not implemented in old HTML4 browsers
if (!isSupportStateObjectInHistory) {
e = redefineProperty(e, 'state', {get: function() {
return historyObject.state;
}});
}
// send events to be processed
dispatchEvent(e);
}, false);
}, 0);
// for non-HTML5 browsers
if (!isSupportHistoryAPI && noScroll !== true && "location" in historyObject) {
// scroll window to anchor element
scrollToAnchorId(locationObject.hash);
// fire initial state for non-HTML5 browser after load page
fireInitialState();
}
}
|
javascript
|
function onLoad(noScroll) {
// Get rid of the events popstate when the first loading a document in the webkit browsers
setTimeout(function() {
// hang up the event handler for the built-in popstate event in the browser
addEvent('popstate', function(e) {
// set the current url, that suppress the creation of the popstate event by changing the hash
checkUrlForPopState = windowLocation.href;
// for Safari browser in OS Windows not implemented 'state' object in 'History' interface
// and not implemented in old HTML4 browsers
if (!isSupportStateObjectInHistory) {
e = redefineProperty(e, 'state', {get: function() {
return historyObject.state;
}});
}
// send events to be processed
dispatchEvent(e);
}, false);
}, 0);
// for non-HTML5 browsers
if (!isSupportHistoryAPI && noScroll !== true && "location" in historyObject) {
// scroll window to anchor element
scrollToAnchorId(locationObject.hash);
// fire initial state for non-HTML5 browser after load page
fireInitialState();
}
}
|
[
"function",
"onLoad",
"(",
"noScroll",
")",
"{",
"// Get rid of the events popstate when the first loading a document in the webkit browsers",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"// hang up the event handler for the built-in popstate event in the browser",
"addEvent",
"(",
"'popstate'",
",",
"function",
"(",
"e",
")",
"{",
"// set the current url, that suppress the creation of the popstate event by changing the hash",
"checkUrlForPopState",
"=",
"windowLocation",
".",
"href",
";",
"// for Safari browser in OS Windows not implemented 'state' object in 'History' interface",
"// and not implemented in old HTML4 browsers",
"if",
"(",
"!",
"isSupportStateObjectInHistory",
")",
"{",
"e",
"=",
"redefineProperty",
"(",
"e",
",",
"'state'",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"historyObject",
".",
"state",
";",
"}",
"}",
")",
";",
"}",
"// send events to be processed",
"dispatchEvent",
"(",
"e",
")",
";",
"}",
",",
"false",
")",
";",
"}",
",",
"0",
")",
";",
"// for non-HTML5 browsers",
"if",
"(",
"!",
"isSupportHistoryAPI",
"&&",
"noScroll",
"!==",
"true",
"&&",
"\"location\"",
"in",
"historyObject",
")",
"{",
"// scroll window to anchor element",
"scrollToAnchorId",
"(",
"locationObject",
".",
"hash",
")",
";",
"// fire initial state for non-HTML5 browser after load page",
"fireInitialState",
"(",
")",
";",
"}",
"}"
] |
The event handler is fully loaded document
@param {*} [noScroll]
@return void
|
[
"The",
"event",
"handler",
"is",
"fully",
"loaded",
"document"
] |
2cad95c15985c7e7ba7091ff80d894f63a3c3c03
|
https://github.com/devote/HTML5-History-API/blob/2cad95c15985c7e7ba7091ff80d894f63a3c3c03/history.js#L918-L943
|
15,758
|
devote/HTML5-History-API
|
history.js
|
onAnchorClick
|
function onAnchorClick(e) {
var event = e || global.event;
var target = anchorTarget(event.target || event.srcElement);
var defaultPrevented = "defaultPrevented" in event ? event['defaultPrevented'] : event.returnValue === false;
if (target && target.nodeName === "A" && !defaultPrevented) {
var current = parseURL();
var expect = parseURL(target.getAttribute("href", 2));
var isEqualBaseURL = current._href.split('#').shift() === expect._href.split('#').shift();
if (isEqualBaseURL && expect._hash) {
if (current._hash !== expect._hash) {
locationObject.hash = expect._hash;
}
scrollToAnchorId(expect._hash);
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
}
}
|
javascript
|
function onAnchorClick(e) {
var event = e || global.event;
var target = anchorTarget(event.target || event.srcElement);
var defaultPrevented = "defaultPrevented" in event ? event['defaultPrevented'] : event.returnValue === false;
if (target && target.nodeName === "A" && !defaultPrevented) {
var current = parseURL();
var expect = parseURL(target.getAttribute("href", 2));
var isEqualBaseURL = current._href.split('#').shift() === expect._href.split('#').shift();
if (isEqualBaseURL && expect._hash) {
if (current._hash !== expect._hash) {
locationObject.hash = expect._hash;
}
scrollToAnchorId(expect._hash);
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
}
}
|
[
"function",
"onAnchorClick",
"(",
"e",
")",
"{",
"var",
"event",
"=",
"e",
"||",
"global",
".",
"event",
";",
"var",
"target",
"=",
"anchorTarget",
"(",
"event",
".",
"target",
"||",
"event",
".",
"srcElement",
")",
";",
"var",
"defaultPrevented",
"=",
"\"defaultPrevented\"",
"in",
"event",
"?",
"event",
"[",
"'defaultPrevented'",
"]",
":",
"event",
".",
"returnValue",
"===",
"false",
";",
"if",
"(",
"target",
"&&",
"target",
".",
"nodeName",
"===",
"\"A\"",
"&&",
"!",
"defaultPrevented",
")",
"{",
"var",
"current",
"=",
"parseURL",
"(",
")",
";",
"var",
"expect",
"=",
"parseURL",
"(",
"target",
".",
"getAttribute",
"(",
"\"href\"",
",",
"2",
")",
")",
";",
"var",
"isEqualBaseURL",
"=",
"current",
".",
"_href",
".",
"split",
"(",
"'#'",
")",
".",
"shift",
"(",
")",
"===",
"expect",
".",
"_href",
".",
"split",
"(",
"'#'",
")",
".",
"shift",
"(",
")",
";",
"if",
"(",
"isEqualBaseURL",
"&&",
"expect",
".",
"_hash",
")",
"{",
"if",
"(",
"current",
".",
"_hash",
"!==",
"expect",
".",
"_hash",
")",
"{",
"locationObject",
".",
"hash",
"=",
"expect",
".",
"_hash",
";",
"}",
"scrollToAnchorId",
"(",
"expect",
".",
"_hash",
")",
";",
"if",
"(",
"event",
".",
"preventDefault",
")",
"{",
"event",
".",
"preventDefault",
"(",
")",
";",
"}",
"else",
"{",
"event",
".",
"returnValue",
"=",
"false",
";",
"}",
"}",
"}",
"}"
] |
Handles anchor elements with a hash fragment for non-HTML5 browsers
@param {Event} e
|
[
"Handles",
"anchor",
"elements",
"with",
"a",
"hash",
"fragment",
"for",
"non",
"-",
"HTML5",
"browsers"
] |
2cad95c15985c7e7ba7091ff80d894f63a3c3c03
|
https://github.com/devote/HTML5-History-API/blob/2cad95c15985c7e7ba7091ff80d894f63a3c3c03/history.js#L963-L983
|
15,759
|
devote/HTML5-History-API
|
history.js
|
scrollToAnchorId
|
function scrollToAnchorId(hash) {
var target = document.getElementById(hash = (hash || '').replace(/^#/, ''));
if (target && target.id === hash && target.nodeName === "A") {
var rect = target.getBoundingClientRect();
global.scrollTo((documentElement.scrollLeft || 0), rect.top + (documentElement.scrollTop || 0)
- (documentElement.clientTop || 0));
}
}
|
javascript
|
function scrollToAnchorId(hash) {
var target = document.getElementById(hash = (hash || '').replace(/^#/, ''));
if (target && target.id === hash && target.nodeName === "A") {
var rect = target.getBoundingClientRect();
global.scrollTo((documentElement.scrollLeft || 0), rect.top + (documentElement.scrollTop || 0)
- (documentElement.clientTop || 0));
}
}
|
[
"function",
"scrollToAnchorId",
"(",
"hash",
")",
"{",
"var",
"target",
"=",
"document",
".",
"getElementById",
"(",
"hash",
"=",
"(",
"hash",
"||",
"''",
")",
".",
"replace",
"(",
"/",
"^#",
"/",
",",
"''",
")",
")",
";",
"if",
"(",
"target",
"&&",
"target",
".",
"id",
"===",
"hash",
"&&",
"target",
".",
"nodeName",
"===",
"\"A\"",
")",
"{",
"var",
"rect",
"=",
"target",
".",
"getBoundingClientRect",
"(",
")",
";",
"global",
".",
"scrollTo",
"(",
"(",
"documentElement",
".",
"scrollLeft",
"||",
"0",
")",
",",
"rect",
".",
"top",
"+",
"(",
"documentElement",
".",
"scrollTop",
"||",
"0",
")",
"-",
"(",
"documentElement",
".",
"clientTop",
"||",
"0",
")",
")",
";",
"}",
"}"
] |
Scroll page to current anchor in url-hash
@param hash
|
[
"Scroll",
"page",
"to",
"current",
"anchor",
"in",
"url",
"-",
"hash"
] |
2cad95c15985c7e7ba7091ff80d894f63a3c3c03
|
https://github.com/devote/HTML5-History-API/blob/2cad95c15985c7e7ba7091ff80d894f63a3c3c03/history.js#L990-L997
|
15,760
|
catamphetamine/webpack-isomorphic-tools
|
source/plugin/write assets.js
|
get_assets
|
function get_assets(name, extension = 'js')
{
let chunk = json.assetsByChunkName[name]
// a chunk could be a string or an array, so make sure it is an array
if (!(Array.isArray(chunk)))
{
chunk = [chunk]
}
return chunk
// filter by extension
.filter(name => path.extname(extract_path(name)) === `.${extension}`)
// adjust the real path (can be http, filesystem)
.map(name => options.assets_base_url + name)
}
|
javascript
|
function get_assets(name, extension = 'js')
{
let chunk = json.assetsByChunkName[name]
// a chunk could be a string or an array, so make sure it is an array
if (!(Array.isArray(chunk)))
{
chunk = [chunk]
}
return chunk
// filter by extension
.filter(name => path.extname(extract_path(name)) === `.${extension}`)
// adjust the real path (can be http, filesystem)
.map(name => options.assets_base_url + name)
}
|
[
"function",
"get_assets",
"(",
"name",
",",
"extension",
"=",
"'js'",
")",
"{",
"let",
"chunk",
"=",
"json",
".",
"assetsByChunkName",
"[",
"name",
"]",
"// a chunk could be a string or an array, so make sure it is an array",
"if",
"(",
"!",
"(",
"Array",
".",
"isArray",
"(",
"chunk",
")",
")",
")",
"{",
"chunk",
"=",
"[",
"chunk",
"]",
"}",
"return",
"chunk",
"// filter by extension",
".",
"filter",
"(",
"name",
"=>",
"path",
".",
"extname",
"(",
"extract_path",
"(",
"name",
")",
")",
"===",
"`",
"${",
"extension",
"}",
"`",
")",
"// adjust the real path (can be http, filesystem)",
".",
"map",
"(",
"name",
"=>",
"options",
".",
"assets_base_url",
"+",
"name",
")",
"}"
] |
gets asset paths by name and extension of their chunk
|
[
"gets",
"asset",
"paths",
"by",
"name",
"and",
"extension",
"of",
"their",
"chunk"
] |
59aa50fbde327ec0921a9acd370868851260a4e0
|
https://github.com/catamphetamine/webpack-isomorphic-tools/blob/59aa50fbde327ec0921a9acd370868851260a4e0/source/plugin/write assets.js#L144-L159
|
15,761
|
catamphetamine/webpack-isomorphic-tools
|
source/index.js
|
wait_for
|
function wait_for(condition, proceed)
{
function check()
{
// if the condition is met, then proceed
if (condition())
{
return proceed()
}
message_timer += check_interval
if (message_timer >= message_interval)
{
message_timer = 0
tools.log.debug(`(${tools.webpack_assets_path} not found)`)
tools.log.info('(waiting for the first Webpack build to finish)')
}
setTimeout(check, check_interval)
}
check()
}
|
javascript
|
function wait_for(condition, proceed)
{
function check()
{
// if the condition is met, then proceed
if (condition())
{
return proceed()
}
message_timer += check_interval
if (message_timer >= message_interval)
{
message_timer = 0
tools.log.debug(`(${tools.webpack_assets_path} not found)`)
tools.log.info('(waiting for the first Webpack build to finish)')
}
setTimeout(check, check_interval)
}
check()
}
|
[
"function",
"wait_for",
"(",
"condition",
",",
"proceed",
")",
"{",
"function",
"check",
"(",
")",
"{",
"// if the condition is met, then proceed",
"if",
"(",
"condition",
"(",
")",
")",
"{",
"return",
"proceed",
"(",
")",
"}",
"message_timer",
"+=",
"check_interval",
"if",
"(",
"message_timer",
">=",
"message_interval",
")",
"{",
"message_timer",
"=",
"0",
"tools",
".",
"log",
".",
"debug",
"(",
"`",
"${",
"tools",
".",
"webpack_assets_path",
"}",
"`",
")",
"tools",
".",
"log",
".",
"info",
"(",
"'(waiting for the first Webpack build to finish)'",
")",
"}",
"setTimeout",
"(",
"check",
",",
"check_interval",
")",
"}",
"check",
"(",
")",
"}"
] |
waits for condition to be met, then proceeds
|
[
"waits",
"for",
"condition",
"to",
"be",
"met",
"then",
"proceeds"
] |
59aa50fbde327ec0921a9acd370868851260a4e0
|
https://github.com/catamphetamine/webpack-isomorphic-tools/blob/59aa50fbde327ec0921a9acd370868851260a4e0/source/index.js#L764-L788
|
15,762
|
catamphetamine/webpack-isomorphic-tools
|
source/tools/log.js
|
generate_log_message
|
function generate_log_message(parameters)
{
// преобразовать все аргументы функции в текстовый вид
return parameters.map(argument =>
{
// преобразование объектов в строку
if (typeof argument === 'object')
{
// для ошибок - распечатывать стек вызовов
if (argument instanceof Error)
{
return argument.stack
}
// для остальных объектов вызывать JSON.stringify()
return JSON.stringify(argument, null, 2)
}
// если undefined
if (typeof argument === 'undefined')
{
return '[undefined]'
}
// прочие переменные - просто .toString()
return argument.toString()
})
// собрать всё это в одну строку через пробел
.reduce((message, argument) =>
{
if (message.length > 0)
{
message += ' '
}
return message + argument
},
'')
}
|
javascript
|
function generate_log_message(parameters)
{
// преобразовать все аргументы функции в текстовый вид
return parameters.map(argument =>
{
// преобразование объектов в строку
if (typeof argument === 'object')
{
// для ошибок - распечатывать стек вызовов
if (argument instanceof Error)
{
return argument.stack
}
// для остальных объектов вызывать JSON.stringify()
return JSON.stringify(argument, null, 2)
}
// если undefined
if (typeof argument === 'undefined')
{
return '[undefined]'
}
// прочие переменные - просто .toString()
return argument.toString()
})
// собрать всё это в одну строку через пробел
.reduce((message, argument) =>
{
if (message.length > 0)
{
message += ' '
}
return message + argument
},
'')
}
|
[
"function",
"generate_log_message",
"(",
"parameters",
")",
"{",
"// преобразовать все аргументы функции в текстовый вид",
"return",
"parameters",
".",
"map",
"(",
"argument",
"=>",
"{",
"// преобразование объектов в строку",
"if",
"(",
"typeof",
"argument",
"===",
"'object'",
")",
"{",
"// для ошибок - распечатывать стек вызовов",
"if",
"(",
"argument",
"instanceof",
"Error",
")",
"{",
"return",
"argument",
".",
"stack",
"}",
"// для остальных объектов вызывать JSON.stringify()",
"return",
"JSON",
".",
"stringify",
"(",
"argument",
",",
"null",
",",
"2",
")",
"}",
"// если undefined",
"if",
"(",
"typeof",
"argument",
"===",
"'undefined'",
")",
"{",
"return",
"'[undefined]'",
"}",
"// прочие переменные - просто .toString()",
"return",
"argument",
".",
"toString",
"(",
")",
"}",
")",
"// собрать всё это в одну строку через пробел",
".",
"reduce",
"(",
"(",
"message",
",",
"argument",
")",
"=>",
"{",
"if",
"(",
"message",
".",
"length",
">",
"0",
")",
"{",
"message",
"+=",
"' '",
"}",
"return",
"message",
"+",
"argument",
"}",
",",
"''",
")",
"}"
] |
transforms arguments to text
|
[
"transforms",
"arguments",
"to",
"text"
] |
59aa50fbde327ec0921a9acd370868851260a4e0
|
https://github.com/catamphetamine/webpack-isomorphic-tools/blob/59aa50fbde327ec0921a9acd370868851260a4e0/source/tools/log.js#L51-L85
|
15,763
|
catamphetamine/webpack-isomorphic-tools
|
source/common.js
|
alias
|
function alias(path, aliases)
{
// if it's a path to a file - don't interfere
if (!is_package_path(path))
{
return
}
// extract module name from the path
const slash_index = path.indexOf('/')
const module_name = slash_index >= 0 ? path.substring(0, slash_index) : path
const rest = slash_index >= 0 ? path.substring(slash_index) : ''
// find an alias
const alias = aliases[module_name]
// if an alias is found, require() the correct path
if (alias)
{
return alias + rest
}
}
|
javascript
|
function alias(path, aliases)
{
// if it's a path to a file - don't interfere
if (!is_package_path(path))
{
return
}
// extract module name from the path
const slash_index = path.indexOf('/')
const module_name = slash_index >= 0 ? path.substring(0, slash_index) : path
const rest = slash_index >= 0 ? path.substring(slash_index) : ''
// find an alias
const alias = aliases[module_name]
// if an alias is found, require() the correct path
if (alias)
{
return alias + rest
}
}
|
[
"function",
"alias",
"(",
"path",
",",
"aliases",
")",
"{",
"// if it's a path to a file - don't interfere",
"if",
"(",
"!",
"is_package_path",
"(",
"path",
")",
")",
"{",
"return",
"}",
"// extract module name from the path",
"const",
"slash_index",
"=",
"path",
".",
"indexOf",
"(",
"'/'",
")",
"const",
"module_name",
"=",
"slash_index",
">=",
"0",
"?",
"path",
".",
"substring",
"(",
"0",
",",
"slash_index",
")",
":",
"path",
"const",
"rest",
"=",
"slash_index",
">=",
"0",
"?",
"path",
".",
"substring",
"(",
"slash_index",
")",
":",
"''",
"// find an alias",
"const",
"alias",
"=",
"aliases",
"[",
"module_name",
"]",
"// if an alias is found, require() the correct path",
"if",
"(",
"alias",
")",
"{",
"return",
"alias",
"+",
"rest",
"}",
"}"
] |
alias the path provided the aliases map
|
[
"alias",
"the",
"path",
"provided",
"the",
"aliases",
"map"
] |
59aa50fbde327ec0921a9acd370868851260a4e0
|
https://github.com/catamphetamine/webpack-isomorphic-tools/blob/59aa50fbde327ec0921a9acd370868851260a4e0/source/common.js#L265-L286
|
15,764
|
untu/comedy
|
lib/threaded-actor-worker.js
|
compileDefinition
|
function compileDefinition(def) {
if (_.isArray(def)) {
return _.map(def, compileDefinition);
}
try {
if (def[0] == '{') {
// Plain object defined behaviour => wrap in braces.
return eval(`(${def})`);
}
else if (def[0] == '[') {
// Definition array => first deserialize array, then definitions inside.
let behArr = eval(`(${def})`);
return _.map(behArr, item => compileDefinition(item));
}
return eval(def);
}
catch (err) {
parentPort.postMessage({ error: 'Compilation error: ' + err });
process.exit(1);
}
}
|
javascript
|
function compileDefinition(def) {
if (_.isArray(def)) {
return _.map(def, compileDefinition);
}
try {
if (def[0] == '{') {
// Plain object defined behaviour => wrap in braces.
return eval(`(${def})`);
}
else if (def[0] == '[') {
// Definition array => first deserialize array, then definitions inside.
let behArr = eval(`(${def})`);
return _.map(behArr, item => compileDefinition(item));
}
return eval(def);
}
catch (err) {
parentPort.postMessage({ error: 'Compilation error: ' + err });
process.exit(1);
}
}
|
[
"function",
"compileDefinition",
"(",
"def",
")",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"def",
")",
")",
"{",
"return",
"_",
".",
"map",
"(",
"def",
",",
"compileDefinition",
")",
";",
"}",
"try",
"{",
"if",
"(",
"def",
"[",
"0",
"]",
"==",
"'{'",
")",
"{",
"// Plain object defined behaviour => wrap in braces.",
"return",
"eval",
"(",
"`",
"${",
"def",
"}",
"`",
")",
";",
"}",
"else",
"if",
"(",
"def",
"[",
"0",
"]",
"==",
"'['",
")",
"{",
"// Definition array => first deserialize array, then definitions inside.",
"let",
"behArr",
"=",
"eval",
"(",
"`",
"${",
"def",
"}",
"`",
")",
";",
"return",
"_",
".",
"map",
"(",
"behArr",
",",
"item",
"=>",
"compileDefinition",
"(",
"item",
")",
")",
";",
"}",
"return",
"eval",
"(",
"def",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"parentPort",
".",
"postMessage",
"(",
"{",
"error",
":",
"'Compilation error: '",
"+",
"err",
"}",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"}"
] |
Compiles a serialized actor definition.
@param {String|String[]} def Serialized definition.
@returns {*} Compiled actor definition.
|
[
"Compiles",
"a",
"serialized",
"actor",
"definition",
"."
] |
cdbfd95b0ab5af85f6cdde44b0f1d536e8fd445d
|
https://github.com/untu/comedy/blob/cdbfd95b0ab5af85f6cdde44b0f1d536e8fd445d/lib/threaded-actor-worker.js#L166-L190
|
15,765
|
HumbleSoftware/Flotr2
|
examples/lib/codemirror/mode/gfm/gfm.js
|
handleText
|
function handleText(stream, mdState) {
var match;
if (stream.match(/^\w+:\/\/\S+/)) {
return 'linkhref';
}
if (stream.match(/^[^\[*\\<>` _][^\[*\\<>` ]*[^\[*\\<>` _]/)) {
return mdMode.getType(mdState);
}
if (match = stream.match(/^[^\[*\\<>` ]+/)) {
var word = match[0];
if (word[0] === '_' && word[word.length-1] === '_') {
stream.backUp(word.length);
return undefined;
}
return mdMode.getType(mdState);
}
if (stream.eatSpace()) {
return null;
}
}
|
javascript
|
function handleText(stream, mdState) {
var match;
if (stream.match(/^\w+:\/\/\S+/)) {
return 'linkhref';
}
if (stream.match(/^[^\[*\\<>` _][^\[*\\<>` ]*[^\[*\\<>` _]/)) {
return mdMode.getType(mdState);
}
if (match = stream.match(/^[^\[*\\<>` ]+/)) {
var word = match[0];
if (word[0] === '_' && word[word.length-1] === '_') {
stream.backUp(word.length);
return undefined;
}
return mdMode.getType(mdState);
}
if (stream.eatSpace()) {
return null;
}
}
|
[
"function",
"handleText",
"(",
"stream",
",",
"mdState",
")",
"{",
"var",
"match",
";",
"if",
"(",
"stream",
".",
"match",
"(",
"/",
"^\\w+:\\/\\/\\S+",
"/",
")",
")",
"{",
"return",
"'linkhref'",
";",
"}",
"if",
"(",
"stream",
".",
"match",
"(",
"/",
"^[^\\[*\\\\<>` _][^\\[*\\\\<>` ]*[^\\[*\\\\<>` _]",
"/",
")",
")",
"{",
"return",
"mdMode",
".",
"getType",
"(",
"mdState",
")",
";",
"}",
"if",
"(",
"match",
"=",
"stream",
".",
"match",
"(",
"/",
"^[^\\[*\\\\<>` ]+",
"/",
")",
")",
"{",
"var",
"word",
"=",
"match",
"[",
"0",
"]",
";",
"if",
"(",
"word",
"[",
"0",
"]",
"===",
"'_'",
"&&",
"word",
"[",
"word",
".",
"length",
"-",
"1",
"]",
"===",
"'_'",
")",
"{",
"stream",
".",
"backUp",
"(",
"word",
".",
"length",
")",
";",
"return",
"undefined",
";",
"}",
"return",
"mdMode",
".",
"getType",
"(",
"mdState",
")",
";",
"}",
"if",
"(",
"stream",
".",
"eatSpace",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"}"
] |
custom handleText to prevent emphasis in the middle of a word and add autolinking
|
[
"custom",
"handleText",
"to",
"prevent",
"emphasis",
"in",
"the",
"middle",
"of",
"a",
"word",
"and",
"add",
"autolinking"
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/examples/lib/codemirror/mode/gfm/gfm.js#L69-L88
|
15,766
|
HumbleSoftware/Flotr2
|
lib/prototype.js
|
function(a, b) {
for (var i = 0, node; node = b[i]; i++)
a.push(node);
return a;
}
|
javascript
|
function(a, b) {
for (var i = 0, node; node = b[i]; i++)
a.push(node);
return a;
}
|
[
"function",
"(",
"a",
",",
"b",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"node",
";",
"node",
"=",
"b",
"[",
"i",
"]",
";",
"i",
"++",
")",
"a",
".",
"push",
"(",
"node",
")",
";",
"return",
"a",
";",
"}"
] |
UTILITY FUNCTIONS joins two collections
|
[
"UTILITY",
"FUNCTIONS",
"joins",
"two",
"collections"
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/lib/prototype.js#L3069-L3073
|
|
15,767
|
HumbleSoftware/Flotr2
|
lib/prototype.js
|
function(a, b, total) {
if (a == 0) return b > 0 ? [b] : [];
return $R(1, total).inject([], function(memo, i) {
if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
return memo;
});
}
|
javascript
|
function(a, b, total) {
if (a == 0) return b > 0 ? [b] : [];
return $R(1, total).inject([], function(memo, i) {
if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
return memo;
});
}
|
[
"function",
"(",
"a",
",",
"b",
",",
"total",
")",
"{",
"if",
"(",
"a",
"==",
"0",
")",
"return",
"b",
">",
"0",
"?",
"[",
"b",
"]",
":",
"[",
"]",
";",
"return",
"$R",
"(",
"1",
",",
"total",
")",
".",
"inject",
"(",
"[",
"]",
",",
"function",
"(",
"memo",
",",
"i",
")",
"{",
"if",
"(",
"0",
"==",
"(",
"i",
"-",
"b",
")",
"%",
"a",
"&&",
"(",
"i",
"-",
"b",
")",
"/",
"a",
">=",
"0",
")",
"memo",
".",
"push",
"(",
"i",
")",
";",
"return",
"memo",
";",
"}",
")",
";",
"}"
] |
handles the an+b logic
|
[
"handles",
"the",
"an",
"+",
"b",
"logic"
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/lib/prototype.js#L3297-L3303
|
|
15,768
|
HumbleSoftware/Flotr2
|
flotr2.examples.types.js
|
drawGraph
|
function drawGraph (opts) {
// Clone the options, so the 'options' variable always keeps intact.
var o = Flotr._.extend(Flotr._.clone(options), opts || {});
// Return a new graph.
return Flotr.draw(
container,
[ d1, d2, d3 ],
o
);
}
|
javascript
|
function drawGraph (opts) {
// Clone the options, so the 'options' variable always keeps intact.
var o = Flotr._.extend(Flotr._.clone(options), opts || {});
// Return a new graph.
return Flotr.draw(
container,
[ d1, d2, d3 ],
o
);
}
|
[
"function",
"drawGraph",
"(",
"opts",
")",
"{",
"// Clone the options, so the 'options' variable always keeps intact.",
"var",
"o",
"=",
"Flotr",
".",
"_",
".",
"extend",
"(",
"Flotr",
".",
"_",
".",
"clone",
"(",
"options",
")",
",",
"opts",
"||",
"{",
"}",
")",
";",
"// Return a new graph.",
"return",
"Flotr",
".",
"draw",
"(",
"container",
",",
"[",
"d1",
",",
"d2",
",",
"d3",
"]",
",",
"o",
")",
";",
"}"
] |
Draw graph with default options, overwriting with passed options
|
[
"Draw",
"graph",
"with",
"default",
"options",
"overwriting",
"with",
"passed",
"options"
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.examples.types.js#L666-L677
|
15,769
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(name, graphType){
Flotr.graphTypes[name] = graphType;
Flotr.defaultOptions[name] = graphType.options || {};
Flotr.defaultOptions.defaultType = Flotr.defaultOptions.defaultType || name;
}
|
javascript
|
function(name, graphType){
Flotr.graphTypes[name] = graphType;
Flotr.defaultOptions[name] = graphType.options || {};
Flotr.defaultOptions.defaultType = Flotr.defaultOptions.defaultType || name;
}
|
[
"function",
"(",
"name",
",",
"graphType",
")",
"{",
"Flotr",
".",
"graphTypes",
"[",
"name",
"]",
"=",
"graphType",
";",
"Flotr",
".",
"defaultOptions",
"[",
"name",
"]",
"=",
"graphType",
".",
"options",
"||",
"{",
"}",
";",
"Flotr",
".",
"defaultOptions",
".",
"defaultType",
"=",
"Flotr",
".",
"defaultOptions",
".",
"defaultType",
"||",
"name",
";",
"}"
] |
Can be used to add your own chart type.
@param {String} name - Type of chart, like 'pies', 'bars' etc.
@param {String} graphType - The object containing the basic drawing functions (draw, etc)
|
[
"Can",
"be",
"used",
"to",
"add",
"your",
"own",
"chart",
"type",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L37-L41
|
|
15,770
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(name, plugin){
Flotr.plugins[name] = plugin;
Flotr.defaultOptions[name] = plugin.options || {};
}
|
javascript
|
function(name, plugin){
Flotr.plugins[name] = plugin;
Flotr.defaultOptions[name] = plugin.options || {};
}
|
[
"function",
"(",
"name",
",",
"plugin",
")",
"{",
"Flotr",
".",
"plugins",
"[",
"name",
"]",
"=",
"plugin",
";",
"Flotr",
".",
"defaultOptions",
"[",
"name",
"]",
"=",
"plugin",
".",
"options",
"||",
"{",
"}",
";",
"}"
] |
Can be used to add a plugin
@param {String} name - The name of the plugin
@param {String} plugin - The object containing the plugin's data (callbacks, options, function1, function2, ...)
|
[
"Can",
"be",
"used",
"to",
"add",
"a",
"plugin"
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L48-L51
|
|
15,771
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(noTicks, min, max, decimals){
var delta = (max - min) / noTicks,
magn = Flotr.getMagnitude(delta),
tickSize = 10,
norm = delta / magn; // Norm is between 1.0 and 10.0.
if(norm < 1.5) tickSize = 1;
else if(norm < 2.25) tickSize = 2;
else if(norm < 3) tickSize = ((decimals === 0) ? 2 : 2.5);
else if(norm < 7.5) tickSize = 5;
return tickSize * magn;
}
|
javascript
|
function(noTicks, min, max, decimals){
var delta = (max - min) / noTicks,
magn = Flotr.getMagnitude(delta),
tickSize = 10,
norm = delta / magn; // Norm is between 1.0 and 10.0.
if(norm < 1.5) tickSize = 1;
else if(norm < 2.25) tickSize = 2;
else if(norm < 3) tickSize = ((decimals === 0) ? 2 : 2.5);
else if(norm < 7.5) tickSize = 5;
return tickSize * magn;
}
|
[
"function",
"(",
"noTicks",
",",
"min",
",",
"max",
",",
"decimals",
")",
"{",
"var",
"delta",
"=",
"(",
"max",
"-",
"min",
")",
"/",
"noTicks",
",",
"magn",
"=",
"Flotr",
".",
"getMagnitude",
"(",
"delta",
")",
",",
"tickSize",
"=",
"10",
",",
"norm",
"=",
"delta",
"/",
"magn",
";",
"// Norm is between 1.0 and 10.0.",
"if",
"(",
"norm",
"<",
"1.5",
")",
"tickSize",
"=",
"1",
";",
"else",
"if",
"(",
"norm",
"<",
"2.25",
")",
"tickSize",
"=",
"2",
";",
"else",
"if",
"(",
"norm",
"<",
"3",
")",
"tickSize",
"=",
"(",
"(",
"decimals",
"===",
"0",
")",
"?",
"2",
":",
"2.5",
")",
";",
"else",
"if",
"(",
"norm",
"<",
"7.5",
")",
"tickSize",
"=",
"5",
";",
"return",
"tickSize",
"*",
"magn",
";",
"}"
] |
Function calculates the ticksize and returns it.
@param {Integer} noTicks - number of ticks
@param {Integer} min - lower bound integer value for the current axis
@param {Integer} max - upper bound integer value for the current axis
@param {Integer} decimals - number of decimals for the ticks
@return {Integer} returns the ticksize in pixels
|
[
"Function",
"calculates",
"the",
"ticksize",
"and",
"returns",
"it",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L117-L129
|
|
15,772
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(x){
return Math.pow(10, Math.floor(Math.log(x) / Math.LN10));
}
|
javascript
|
function(x){
return Math.pow(10, Math.floor(Math.log(x) / Math.LN10));
}
|
[
"function",
"(",
"x",
")",
"{",
"return",
"Math",
".",
"pow",
"(",
"10",
",",
"Math",
".",
"floor",
"(",
"Math",
".",
"log",
"(",
"x",
")",
"/",
"Math",
".",
"LN10",
")",
")",
";",
"}"
] |
Returns the magnitude of the input value.
@param {Integer, Float} x - integer or float value
@return {Integer, Float} returns the magnitude of the input value
|
[
"Returns",
"the",
"magnitude",
"of",
"the",
"input",
"value",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L183-L185
|
|
15,773
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(color, options) {
var opacity = options.opacity;
if (!color) return 'rgba(0, 0, 0, 0)';
if (color instanceof Color) return color.alpha(opacity).toString();
if (_.isString(color)) return Color.parse(color).alpha(opacity).toString();
var grad = color.colors ? color : {colors: color};
if (!options.ctx) {
if (!_.isArray(grad.colors)) return 'rgba(0, 0, 0, 0)';
return Color.parse(_.isArray(grad.colors[0]) ? grad.colors[0][1] : grad.colors[0]).alpha(opacity).toString();
}
grad = _.extend({start: 'top', end: 'bottom'}, grad);
if (/top/i.test(grad.start)) options.x1 = 0;
if (/left/i.test(grad.start)) options.y1 = 0;
if (/bottom/i.test(grad.end)) options.x2 = 0;
if (/right/i.test(grad.end)) options.y2 = 0;
var i, c, stop, gradient = options.ctx.createLinearGradient(options.x1, options.y1, options.x2, options.y2);
for (i = 0; i < grad.colors.length; i++) {
c = grad.colors[i];
if (_.isArray(c)) {
stop = c[0];
c = c[1];
}
else stop = i / (grad.colors.length-1);
gradient.addColorStop(stop, Color.parse(c).alpha(opacity));
}
return gradient;
}
|
javascript
|
function(color, options) {
var opacity = options.opacity;
if (!color) return 'rgba(0, 0, 0, 0)';
if (color instanceof Color) return color.alpha(opacity).toString();
if (_.isString(color)) return Color.parse(color).alpha(opacity).toString();
var grad = color.colors ? color : {colors: color};
if (!options.ctx) {
if (!_.isArray(grad.colors)) return 'rgba(0, 0, 0, 0)';
return Color.parse(_.isArray(grad.colors[0]) ? grad.colors[0][1] : grad.colors[0]).alpha(opacity).toString();
}
grad = _.extend({start: 'top', end: 'bottom'}, grad);
if (/top/i.test(grad.start)) options.x1 = 0;
if (/left/i.test(grad.start)) options.y1 = 0;
if (/bottom/i.test(grad.end)) options.x2 = 0;
if (/right/i.test(grad.end)) options.y2 = 0;
var i, c, stop, gradient = options.ctx.createLinearGradient(options.x1, options.y1, options.x2, options.y2);
for (i = 0; i < grad.colors.length; i++) {
c = grad.colors[i];
if (_.isArray(c)) {
stop = c[0];
c = c[1];
}
else stop = i / (grad.colors.length-1);
gradient.addColorStop(stop, Color.parse(c).alpha(opacity));
}
return gradient;
}
|
[
"function",
"(",
"color",
",",
"options",
")",
"{",
"var",
"opacity",
"=",
"options",
".",
"opacity",
";",
"if",
"(",
"!",
"color",
")",
"return",
"'rgba(0, 0, 0, 0)'",
";",
"if",
"(",
"color",
"instanceof",
"Color",
")",
"return",
"color",
".",
"alpha",
"(",
"opacity",
")",
".",
"toString",
"(",
")",
";",
"if",
"(",
"_",
".",
"isString",
"(",
"color",
")",
")",
"return",
"Color",
".",
"parse",
"(",
"color",
")",
".",
"alpha",
"(",
"opacity",
")",
".",
"toString",
"(",
")",
";",
"var",
"grad",
"=",
"color",
".",
"colors",
"?",
"color",
":",
"{",
"colors",
":",
"color",
"}",
";",
"if",
"(",
"!",
"options",
".",
"ctx",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"grad",
".",
"colors",
")",
")",
"return",
"'rgba(0, 0, 0, 0)'",
";",
"return",
"Color",
".",
"parse",
"(",
"_",
".",
"isArray",
"(",
"grad",
".",
"colors",
"[",
"0",
"]",
")",
"?",
"grad",
".",
"colors",
"[",
"0",
"]",
"[",
"1",
"]",
":",
"grad",
".",
"colors",
"[",
"0",
"]",
")",
".",
"alpha",
"(",
"opacity",
")",
".",
"toString",
"(",
")",
";",
"}",
"grad",
"=",
"_",
".",
"extend",
"(",
"{",
"start",
":",
"'top'",
",",
"end",
":",
"'bottom'",
"}",
",",
"grad",
")",
";",
"if",
"(",
"/",
"top",
"/",
"i",
".",
"test",
"(",
"grad",
".",
"start",
")",
")",
"options",
".",
"x1",
"=",
"0",
";",
"if",
"(",
"/",
"left",
"/",
"i",
".",
"test",
"(",
"grad",
".",
"start",
")",
")",
"options",
".",
"y1",
"=",
"0",
";",
"if",
"(",
"/",
"bottom",
"/",
"i",
".",
"test",
"(",
"grad",
".",
"end",
")",
")",
"options",
".",
"x2",
"=",
"0",
";",
"if",
"(",
"/",
"right",
"/",
"i",
".",
"test",
"(",
"grad",
".",
"end",
")",
")",
"options",
".",
"y2",
"=",
"0",
";",
"var",
"i",
",",
"c",
",",
"stop",
",",
"gradient",
"=",
"options",
".",
"ctx",
".",
"createLinearGradient",
"(",
"options",
".",
"x1",
",",
"options",
".",
"y1",
",",
"options",
".",
"x2",
",",
"options",
".",
"y2",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"grad",
".",
"colors",
".",
"length",
";",
"i",
"++",
")",
"{",
"c",
"=",
"grad",
".",
"colors",
"[",
"i",
"]",
";",
"if",
"(",
"_",
".",
"isArray",
"(",
"c",
")",
")",
"{",
"stop",
"=",
"c",
"[",
"0",
"]",
";",
"c",
"=",
"c",
"[",
"1",
"]",
";",
"}",
"else",
"stop",
"=",
"i",
"/",
"(",
"grad",
".",
"colors",
".",
"length",
"-",
"1",
")",
";",
"gradient",
".",
"addColorStop",
"(",
"stop",
",",
"Color",
".",
"parse",
"(",
"c",
")",
".",
"alpha",
"(",
"opacity",
")",
")",
";",
"}",
"return",
"gradient",
";",
"}"
] |
Process color and options into color style.
|
[
"Process",
"color",
"and",
"options",
"into",
"color",
"style",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L482-L513
|
|
15,774
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(element){
element = getEl(element);
return {
height : element.offsetHeight,
width : element.offsetWidth };
}
|
javascript
|
function(element){
element = getEl(element);
return {
height : element.offsetHeight,
width : element.offsetWidth };
}
|
[
"function",
"(",
"element",
")",
"{",
"element",
"=",
"getEl",
"(",
"element",
")",
";",
"return",
"{",
"height",
":",
"element",
".",
"offsetHeight",
",",
"width",
":",
"element",
".",
"offsetWidth",
"}",
";",
"}"
] |
Return element size.
|
[
"Return",
"element",
"size",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L823-L828
|
|
15,775
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(){
var a = this.axes,
xaxis, yaxis, range;
_.each(this.series, function (series) {
range = series.getRange();
if (range) {
xaxis = series.xaxis;
yaxis = series.yaxis;
xaxis.datamin = Math.min(range.xmin, xaxis.datamin);
xaxis.datamax = Math.max(range.xmax, xaxis.datamax);
yaxis.datamin = Math.min(range.ymin, yaxis.datamin);
yaxis.datamax = Math.max(range.ymax, yaxis.datamax);
xaxis.used = (xaxis.used || range.xused);
yaxis.used = (yaxis.used || range.yused);
}
}, this);
// Check for empty data, no data case (none used)
if (!a.x.used && !a.x2.used) a.x.used = true;
if (!a.y.used && !a.y2.used) a.y.used = true;
_.each(a, function (axis) {
axis.calculateRange();
});
var
types = _.keys(flotr.graphTypes),
drawn = false;
_.each(this.series, function (series) {
if (series.hide) return;
_.each(types, function (type) {
if (series[type] && series[type].show) {
this.extendRange(type, series);
drawn = true;
}
}, this);
if (!drawn) {
this.extendRange(this.options.defaultType, series);
}
}, this);
}
|
javascript
|
function(){
var a = this.axes,
xaxis, yaxis, range;
_.each(this.series, function (series) {
range = series.getRange();
if (range) {
xaxis = series.xaxis;
yaxis = series.yaxis;
xaxis.datamin = Math.min(range.xmin, xaxis.datamin);
xaxis.datamax = Math.max(range.xmax, xaxis.datamax);
yaxis.datamin = Math.min(range.ymin, yaxis.datamin);
yaxis.datamax = Math.max(range.ymax, yaxis.datamax);
xaxis.used = (xaxis.used || range.xused);
yaxis.used = (yaxis.used || range.yused);
}
}, this);
// Check for empty data, no data case (none used)
if (!a.x.used && !a.x2.used) a.x.used = true;
if (!a.y.used && !a.y2.used) a.y.used = true;
_.each(a, function (axis) {
axis.calculateRange();
});
var
types = _.keys(flotr.graphTypes),
drawn = false;
_.each(this.series, function (series) {
if (series.hide) return;
_.each(types, function (type) {
if (series[type] && series[type].show) {
this.extendRange(type, series);
drawn = true;
}
}, this);
if (!drawn) {
this.extendRange(this.options.defaultType, series);
}
}, this);
}
|
[
"function",
"(",
")",
"{",
"var",
"a",
"=",
"this",
".",
"axes",
",",
"xaxis",
",",
"yaxis",
",",
"range",
";",
"_",
".",
"each",
"(",
"this",
".",
"series",
",",
"function",
"(",
"series",
")",
"{",
"range",
"=",
"series",
".",
"getRange",
"(",
")",
";",
"if",
"(",
"range",
")",
"{",
"xaxis",
"=",
"series",
".",
"xaxis",
";",
"yaxis",
"=",
"series",
".",
"yaxis",
";",
"xaxis",
".",
"datamin",
"=",
"Math",
".",
"min",
"(",
"range",
".",
"xmin",
",",
"xaxis",
".",
"datamin",
")",
";",
"xaxis",
".",
"datamax",
"=",
"Math",
".",
"max",
"(",
"range",
".",
"xmax",
",",
"xaxis",
".",
"datamax",
")",
";",
"yaxis",
".",
"datamin",
"=",
"Math",
".",
"min",
"(",
"range",
".",
"ymin",
",",
"yaxis",
".",
"datamin",
")",
";",
"yaxis",
".",
"datamax",
"=",
"Math",
".",
"max",
"(",
"range",
".",
"ymax",
",",
"yaxis",
".",
"datamax",
")",
";",
"xaxis",
".",
"used",
"=",
"(",
"xaxis",
".",
"used",
"||",
"range",
".",
"xused",
")",
";",
"yaxis",
".",
"used",
"=",
"(",
"yaxis",
".",
"used",
"||",
"range",
".",
"yused",
")",
";",
"}",
"}",
",",
"this",
")",
";",
"// Check for empty data, no data case (none used)",
"if",
"(",
"!",
"a",
".",
"x",
".",
"used",
"&&",
"!",
"a",
".",
"x2",
".",
"used",
")",
"a",
".",
"x",
".",
"used",
"=",
"true",
";",
"if",
"(",
"!",
"a",
".",
"y",
".",
"used",
"&&",
"!",
"a",
".",
"y2",
".",
"used",
")",
"a",
".",
"y",
".",
"used",
"=",
"true",
";",
"_",
".",
"each",
"(",
"a",
",",
"function",
"(",
"axis",
")",
"{",
"axis",
".",
"calculateRange",
"(",
")",
";",
"}",
")",
";",
"var",
"types",
"=",
"_",
".",
"keys",
"(",
"flotr",
".",
"graphTypes",
")",
",",
"drawn",
"=",
"false",
";",
"_",
".",
"each",
"(",
"this",
".",
"series",
",",
"function",
"(",
"series",
")",
"{",
"if",
"(",
"series",
".",
"hide",
")",
"return",
";",
"_",
".",
"each",
"(",
"types",
",",
"function",
"(",
"type",
")",
"{",
"if",
"(",
"series",
"[",
"type",
"]",
"&&",
"series",
"[",
"type",
"]",
".",
"show",
")",
"{",
"this",
".",
"extendRange",
"(",
"type",
",",
"series",
")",
";",
"drawn",
"=",
"true",
";",
"}",
"}",
",",
"this",
")",
";",
"if",
"(",
"!",
"drawn",
")",
"{",
"this",
".",
"extendRange",
"(",
"this",
".",
"options",
".",
"defaultType",
",",
"series",
")",
";",
"}",
"}",
",",
"this",
")",
";",
"}"
] |
Function determines the min and max values for the xaxis and yaxis.
TODO logarithmic range validation (consideration of 0)
|
[
"Function",
"determines",
"the",
"min",
"and",
"max",
"values",
"for",
"the",
"xaxis",
"and",
"yaxis",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L1063-L1105
|
|
15,776
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(after) {
var
context = this.ctx,
i;
E.fire(this.el, 'flotr:beforedraw', [this.series, this]);
if (this.series.length) {
context.save();
context.translate(this.plotOffset.left, this.plotOffset.top);
for (i = 0; i < this.series.length; i++) {
if (!this.series[i].hide) this.drawSeries(this.series[i]);
}
context.restore();
this.clip();
}
E.fire(this.el, 'flotr:afterdraw', [this.series, this]);
if (after) after();
}
|
javascript
|
function(after) {
var
context = this.ctx,
i;
E.fire(this.el, 'flotr:beforedraw', [this.series, this]);
if (this.series.length) {
context.save();
context.translate(this.plotOffset.left, this.plotOffset.top);
for (i = 0; i < this.series.length; i++) {
if (!this.series[i].hide) this.drawSeries(this.series[i]);
}
context.restore();
this.clip();
}
E.fire(this.el, 'flotr:afterdraw', [this.series, this]);
if (after) after();
}
|
[
"function",
"(",
"after",
")",
"{",
"var",
"context",
"=",
"this",
".",
"ctx",
",",
"i",
";",
"E",
".",
"fire",
"(",
"this",
".",
"el",
",",
"'flotr:beforedraw'",
",",
"[",
"this",
".",
"series",
",",
"this",
"]",
")",
";",
"if",
"(",
"this",
".",
"series",
".",
"length",
")",
"{",
"context",
".",
"save",
"(",
")",
";",
"context",
".",
"translate",
"(",
"this",
".",
"plotOffset",
".",
"left",
",",
"this",
".",
"plotOffset",
".",
"top",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"series",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"this",
".",
"series",
"[",
"i",
"]",
".",
"hide",
")",
"this",
".",
"drawSeries",
"(",
"this",
".",
"series",
"[",
"i",
"]",
")",
";",
"}",
"context",
".",
"restore",
"(",
")",
";",
"this",
".",
"clip",
"(",
")",
";",
"}",
"E",
".",
"fire",
"(",
"this",
".",
"el",
",",
"'flotr:afterdraw'",
",",
"[",
"this",
".",
"series",
",",
"this",
"]",
")",
";",
"if",
"(",
"after",
")",
"after",
"(",
")",
";",
"}"
] |
Draws grid, labels, series and outline.
|
[
"Draws",
"grid",
"labels",
"series",
"and",
"outline",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L1207-L1230
|
|
15,777
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(series){
function drawChart (series, typeKey) {
var options = this.getOptions(series, typeKey);
this[typeKey].draw(options);
}
var drawn = false;
series = series || this.series;
_.each(flotr.graphTypes, function (type, typeKey) {
if (series[typeKey] && series[typeKey].show && this[typeKey]) {
drawn = true;
drawChart.call(this, series, typeKey);
}
}, this);
if (!drawn) drawChart.call(this, series, this.options.defaultType);
}
|
javascript
|
function(series){
function drawChart (series, typeKey) {
var options = this.getOptions(series, typeKey);
this[typeKey].draw(options);
}
var drawn = false;
series = series || this.series;
_.each(flotr.graphTypes, function (type, typeKey) {
if (series[typeKey] && series[typeKey].show && this[typeKey]) {
drawn = true;
drawChart.call(this, series, typeKey);
}
}, this);
if (!drawn) drawChart.call(this, series, this.options.defaultType);
}
|
[
"function",
"(",
"series",
")",
"{",
"function",
"drawChart",
"(",
"series",
",",
"typeKey",
")",
"{",
"var",
"options",
"=",
"this",
".",
"getOptions",
"(",
"series",
",",
"typeKey",
")",
";",
"this",
"[",
"typeKey",
"]",
".",
"draw",
"(",
"options",
")",
";",
"}",
"var",
"drawn",
"=",
"false",
";",
"series",
"=",
"series",
"||",
"this",
".",
"series",
";",
"_",
".",
"each",
"(",
"flotr",
".",
"graphTypes",
",",
"function",
"(",
"type",
",",
"typeKey",
")",
"{",
"if",
"(",
"series",
"[",
"typeKey",
"]",
"&&",
"series",
"[",
"typeKey",
"]",
".",
"show",
"&&",
"this",
"[",
"typeKey",
"]",
")",
"{",
"drawn",
"=",
"true",
";",
"drawChart",
".",
"call",
"(",
"this",
",",
"series",
",",
"typeKey",
")",
";",
"}",
"}",
",",
"this",
")",
";",
"if",
"(",
"!",
"drawn",
")",
"drawChart",
".",
"call",
"(",
"this",
",",
"series",
",",
"this",
".",
"options",
".",
"defaultType",
")",
";",
"}"
] |
Actually draws the graph.
@param {Object} series - series to draw
|
[
"Actually",
"draws",
"the",
"graph",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L1235-L1253
|
|
15,778
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function (e){
var
d = document,
b = d.body,
de = d.documentElement,
axes = this.axes,
plotOffset = this.plotOffset,
lastMousePos = this.lastMousePos,
pointer = E.eventPointer(e),
dx = pointer.x - lastMousePos.pageX,
dy = pointer.y - lastMousePos.pageY,
r, rx, ry;
if ('ontouchstart' in this.el) {
r = D.position(this.overlay);
rx = pointer.x - r.left - plotOffset.left;
ry = pointer.y - r.top - plotOffset.top;
} else {
r = this.overlay.getBoundingClientRect();
rx = e.clientX - r.left - plotOffset.left - b.scrollLeft - de.scrollLeft;
ry = e.clientY - r.top - plotOffset.top - b.scrollTop - de.scrollTop;
}
return {
x: axes.x.p2d(rx),
x2: axes.x2.p2d(rx),
y: axes.y.p2d(ry),
y2: axes.y2.p2d(ry),
relX: rx,
relY: ry,
dX: dx,
dY: dy,
absX: pointer.x,
absY: pointer.y,
pageX: pointer.x,
pageY: pointer.y
};
}
|
javascript
|
function (e){
var
d = document,
b = d.body,
de = d.documentElement,
axes = this.axes,
plotOffset = this.plotOffset,
lastMousePos = this.lastMousePos,
pointer = E.eventPointer(e),
dx = pointer.x - lastMousePos.pageX,
dy = pointer.y - lastMousePos.pageY,
r, rx, ry;
if ('ontouchstart' in this.el) {
r = D.position(this.overlay);
rx = pointer.x - r.left - plotOffset.left;
ry = pointer.y - r.top - plotOffset.top;
} else {
r = this.overlay.getBoundingClientRect();
rx = e.clientX - r.left - plotOffset.left - b.scrollLeft - de.scrollLeft;
ry = e.clientY - r.top - plotOffset.top - b.scrollTop - de.scrollTop;
}
return {
x: axes.x.p2d(rx),
x2: axes.x2.p2d(rx),
y: axes.y.p2d(ry),
y2: axes.y2.p2d(ry),
relX: rx,
relY: ry,
dX: dx,
dY: dy,
absX: pointer.x,
absY: pointer.y,
pageX: pointer.x,
pageY: pointer.y
};
}
|
[
"function",
"(",
"e",
")",
"{",
"var",
"d",
"=",
"document",
",",
"b",
"=",
"d",
".",
"body",
",",
"de",
"=",
"d",
".",
"documentElement",
",",
"axes",
"=",
"this",
".",
"axes",
",",
"plotOffset",
"=",
"this",
".",
"plotOffset",
",",
"lastMousePos",
"=",
"this",
".",
"lastMousePos",
",",
"pointer",
"=",
"E",
".",
"eventPointer",
"(",
"e",
")",
",",
"dx",
"=",
"pointer",
".",
"x",
"-",
"lastMousePos",
".",
"pageX",
",",
"dy",
"=",
"pointer",
".",
"y",
"-",
"lastMousePos",
".",
"pageY",
",",
"r",
",",
"rx",
",",
"ry",
";",
"if",
"(",
"'ontouchstart'",
"in",
"this",
".",
"el",
")",
"{",
"r",
"=",
"D",
".",
"position",
"(",
"this",
".",
"overlay",
")",
";",
"rx",
"=",
"pointer",
".",
"x",
"-",
"r",
".",
"left",
"-",
"plotOffset",
".",
"left",
";",
"ry",
"=",
"pointer",
".",
"y",
"-",
"r",
".",
"top",
"-",
"plotOffset",
".",
"top",
";",
"}",
"else",
"{",
"r",
"=",
"this",
".",
"overlay",
".",
"getBoundingClientRect",
"(",
")",
";",
"rx",
"=",
"e",
".",
"clientX",
"-",
"r",
".",
"left",
"-",
"plotOffset",
".",
"left",
"-",
"b",
".",
"scrollLeft",
"-",
"de",
".",
"scrollLeft",
";",
"ry",
"=",
"e",
".",
"clientY",
"-",
"r",
".",
"top",
"-",
"plotOffset",
".",
"top",
"-",
"b",
".",
"scrollTop",
"-",
"de",
".",
"scrollTop",
";",
"}",
"return",
"{",
"x",
":",
"axes",
".",
"x",
".",
"p2d",
"(",
"rx",
")",
",",
"x2",
":",
"axes",
".",
"x2",
".",
"p2d",
"(",
"rx",
")",
",",
"y",
":",
"axes",
".",
"y",
".",
"p2d",
"(",
"ry",
")",
",",
"y2",
":",
"axes",
".",
"y2",
".",
"p2d",
"(",
"ry",
")",
",",
"relX",
":",
"rx",
",",
"relY",
":",
"ry",
",",
"dX",
":",
"dx",
",",
"dY",
":",
"dy",
",",
"absX",
":",
"pointer",
".",
"x",
",",
"absY",
":",
"pointer",
".",
"y",
",",
"pageX",
":",
"pointer",
".",
"x",
",",
"pageY",
":",
"pointer",
".",
"y",
"}",
";",
"}"
] |
Calculates the coordinates from a mouse event object.
@param {Event} event - Mouse Event object.
@return {Object} Object with coordinates of the mouse.
|
[
"Calculates",
"the",
"coordinates",
"from",
"a",
"mouse",
"event",
"object",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L1295-L1333
|
|
15,779
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function (event){
/*
// @TODO Context menu?
if(event.isRightClick()) {
event.stop();
var overlay = this.overlay;
overlay.hide();
function cancelContextMenu () {
overlay.show();
E.stopObserving(document, 'mousemove', cancelContextMenu);
}
E.observe(document, 'mousemove', cancelContextMenu);
return;
}
*/
if (this.mouseUpHandler) return;
this.mouseUpHandler = _.bind(function (e) {
E.stopObserving(document, 'mouseup', this.mouseUpHandler);
E.stopObserving(document, 'mousemove', this.mouseDownMoveHandler);
this.mouseDownMoveHandler = null;
this.mouseUpHandler = null;
// @TODO why?
//e.stop();
E.fire(this.el, 'flotr:mouseup', [e, this]);
}, this);
this.mouseDownMoveHandler = _.bind(function (e) {
var pos = this.getEventPosition(e);
E.fire(this.el, 'flotr:mousemove', [event, pos, this]);
this.lastMousePos = pos;
}, this);
E.observe(document, 'mouseup', this.mouseUpHandler);
E.observe(document, 'mousemove', this.mouseDownMoveHandler);
E.fire(this.el, 'flotr:mousedown', [event, this]);
this.ignoreClick = false;
}
|
javascript
|
function (event){
/*
// @TODO Context menu?
if(event.isRightClick()) {
event.stop();
var overlay = this.overlay;
overlay.hide();
function cancelContextMenu () {
overlay.show();
E.stopObserving(document, 'mousemove', cancelContextMenu);
}
E.observe(document, 'mousemove', cancelContextMenu);
return;
}
*/
if (this.mouseUpHandler) return;
this.mouseUpHandler = _.bind(function (e) {
E.stopObserving(document, 'mouseup', this.mouseUpHandler);
E.stopObserving(document, 'mousemove', this.mouseDownMoveHandler);
this.mouseDownMoveHandler = null;
this.mouseUpHandler = null;
// @TODO why?
//e.stop();
E.fire(this.el, 'flotr:mouseup', [e, this]);
}, this);
this.mouseDownMoveHandler = _.bind(function (e) {
var pos = this.getEventPosition(e);
E.fire(this.el, 'flotr:mousemove', [event, pos, this]);
this.lastMousePos = pos;
}, this);
E.observe(document, 'mouseup', this.mouseUpHandler);
E.observe(document, 'mousemove', this.mouseDownMoveHandler);
E.fire(this.el, 'flotr:mousedown', [event, this]);
this.ignoreClick = false;
}
|
[
"function",
"(",
"event",
")",
"{",
"/*\n // @TODO Context menu?\n if(event.isRightClick()) {\n event.stop();\n\n var overlay = this.overlay;\n overlay.hide();\n\n function cancelContextMenu () {\n overlay.show();\n E.stopObserving(document, 'mousemove', cancelContextMenu);\n }\n E.observe(document, 'mousemove', cancelContextMenu);\n return;\n }\n */",
"if",
"(",
"this",
".",
"mouseUpHandler",
")",
"return",
";",
"this",
".",
"mouseUpHandler",
"=",
"_",
".",
"bind",
"(",
"function",
"(",
"e",
")",
"{",
"E",
".",
"stopObserving",
"(",
"document",
",",
"'mouseup'",
",",
"this",
".",
"mouseUpHandler",
")",
";",
"E",
".",
"stopObserving",
"(",
"document",
",",
"'mousemove'",
",",
"this",
".",
"mouseDownMoveHandler",
")",
";",
"this",
".",
"mouseDownMoveHandler",
"=",
"null",
";",
"this",
".",
"mouseUpHandler",
"=",
"null",
";",
"// @TODO why?",
"//e.stop();",
"E",
".",
"fire",
"(",
"this",
".",
"el",
",",
"'flotr:mouseup'",
",",
"[",
"e",
",",
"this",
"]",
")",
";",
"}",
",",
"this",
")",
";",
"this",
".",
"mouseDownMoveHandler",
"=",
"_",
".",
"bind",
"(",
"function",
"(",
"e",
")",
"{",
"var",
"pos",
"=",
"this",
".",
"getEventPosition",
"(",
"e",
")",
";",
"E",
".",
"fire",
"(",
"this",
".",
"el",
",",
"'flotr:mousemove'",
",",
"[",
"event",
",",
"pos",
",",
"this",
"]",
")",
";",
"this",
".",
"lastMousePos",
"=",
"pos",
";",
"}",
",",
"this",
")",
";",
"E",
".",
"observe",
"(",
"document",
",",
"'mouseup'",
",",
"this",
".",
"mouseUpHandler",
")",
";",
"E",
".",
"observe",
"(",
"document",
",",
"'mousemove'",
",",
"this",
".",
"mouseDownMoveHandler",
")",
";",
"E",
".",
"fire",
"(",
"this",
".",
"el",
",",
"'flotr:mousedown'",
",",
"[",
"event",
",",
"this",
"]",
")",
";",
"this",
".",
"ignoreClick",
"=",
"false",
";",
"}"
] |
Observes the 'mousedown' event.
@param {Event} event - 'mousedown' Event object.
|
[
"Observes",
"the",
"mousedown",
"event",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L1359-L1397
|
|
15,780
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
getCanvas
|
function getCanvas(canvas, name){
if(!canvas){
canvas = D.create('canvas');
if (typeof FlashCanvas != "undefined" && typeof canvas.getContext === 'function') {
FlashCanvas.initElement(canvas);
this.isFlashCanvas = true;
}
canvas.className = 'flotr-'+name;
canvas.style.cssText = 'position:absolute;left:0px;top:0px;';
D.insert(el, canvas);
}
_.each(size, function(size, attribute){
D.show(canvas);
if (name == 'canvas' && canvas.getAttribute(attribute) === size) {
return;
}
canvas.setAttribute(attribute, size * o.resolution);
canvas.style[attribute] = size + 'px';
});
canvas.context_ = null; // Reset the ExCanvas context
return canvas;
}
|
javascript
|
function getCanvas(canvas, name){
if(!canvas){
canvas = D.create('canvas');
if (typeof FlashCanvas != "undefined" && typeof canvas.getContext === 'function') {
FlashCanvas.initElement(canvas);
this.isFlashCanvas = true;
}
canvas.className = 'flotr-'+name;
canvas.style.cssText = 'position:absolute;left:0px;top:0px;';
D.insert(el, canvas);
}
_.each(size, function(size, attribute){
D.show(canvas);
if (name == 'canvas' && canvas.getAttribute(attribute) === size) {
return;
}
canvas.setAttribute(attribute, size * o.resolution);
canvas.style[attribute] = size + 'px';
});
canvas.context_ = null; // Reset the ExCanvas context
return canvas;
}
|
[
"function",
"getCanvas",
"(",
"canvas",
",",
"name",
")",
"{",
"if",
"(",
"!",
"canvas",
")",
"{",
"canvas",
"=",
"D",
".",
"create",
"(",
"'canvas'",
")",
";",
"if",
"(",
"typeof",
"FlashCanvas",
"!=",
"\"undefined\"",
"&&",
"typeof",
"canvas",
".",
"getContext",
"===",
"'function'",
")",
"{",
"FlashCanvas",
".",
"initElement",
"(",
"canvas",
")",
";",
"this",
".",
"isFlashCanvas",
"=",
"true",
";",
"}",
"canvas",
".",
"className",
"=",
"'flotr-'",
"+",
"name",
";",
"canvas",
".",
"style",
".",
"cssText",
"=",
"'position:absolute;left:0px;top:0px;'",
";",
"D",
".",
"insert",
"(",
"el",
",",
"canvas",
")",
";",
"}",
"_",
".",
"each",
"(",
"size",
",",
"function",
"(",
"size",
",",
"attribute",
")",
"{",
"D",
".",
"show",
"(",
"canvas",
")",
";",
"if",
"(",
"name",
"==",
"'canvas'",
"&&",
"canvas",
".",
"getAttribute",
"(",
"attribute",
")",
"===",
"size",
")",
"{",
"return",
";",
"}",
"canvas",
".",
"setAttribute",
"(",
"attribute",
",",
"size",
"*",
"o",
".",
"resolution",
")",
";",
"canvas",
".",
"style",
"[",
"attribute",
"]",
"=",
"size",
"+",
"'px'",
";",
"}",
")",
";",
"canvas",
".",
"context_",
"=",
"null",
";",
"// Reset the ExCanvas context",
"return",
"canvas",
";",
"}"
] |
Enable text functions
|
[
"Enable",
"text",
"functions"
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L1591-L1612
|
15,781
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function () {
if (!this.used) return;
var axis = this,
o = axis.options,
min = o.min !== null ? o.min : axis.datamin,
max = o.max !== null ? o.max : axis.datamax,
margin = o.autoscaleMargin;
if (o.scaling == 'logarithmic') {
if (min <= 0) min = axis.datamin;
// Let it widen later on
if (max <= 0) max = min;
}
if (max == min) {
var widen = max ? 0.01 : 1.00;
if (o.min === null) min -= widen;
if (o.max === null) max += widen;
}
if (o.scaling === 'logarithmic') {
if (min < 0) min = max / o.base; // Could be the result of widening
var maxexp = Math.log(max);
if (o.base != Math.E) maxexp /= Math.log(o.base);
maxexp = Math.ceil(maxexp);
var minexp = Math.log(min);
if (o.base != Math.E) minexp /= Math.log(o.base);
minexp = Math.ceil(minexp);
axis.tickSize = Flotr.getTickSize(o.noTicks, minexp, maxexp, o.tickDecimals === null ? 0 : o.tickDecimals);
// Try to determine a suitable amount of miniticks based on the length of a decade
if (o.minorTickFreq === null) {
if (maxexp - minexp > 10)
o.minorTickFreq = 0;
else if (maxexp - minexp > 5)
o.minorTickFreq = 2;
else
o.minorTickFreq = 5;
}
} else {
axis.tickSize = Flotr.getTickSize(o.noTicks, min, max, o.tickDecimals);
}
axis.min = min;
axis.max = max; //extendRange may use axis.min or axis.max, so it should be set before it is caled
// Autoscaling. @todo This probably fails with log scale. Find a testcase and fix it
if(o.min === null && o.autoscale){
axis.min -= axis.tickSize * margin;
// Make sure we don't go below zero if all values are positive.
if(axis.min < 0 && axis.datamin >= 0) axis.min = 0;
axis.min = axis.tickSize * Math.floor(axis.min / axis.tickSize);
}
if(o.max === null && o.autoscale){
axis.max += axis.tickSize * margin;
if(axis.max > 0 && axis.datamax <= 0 && axis.datamax != axis.datamin) axis.max = 0;
axis.max = axis.tickSize * Math.ceil(axis.max / axis.tickSize);
}
if (axis.min == axis.max) axis.max = axis.min + 1;
}
|
javascript
|
function () {
if (!this.used) return;
var axis = this,
o = axis.options,
min = o.min !== null ? o.min : axis.datamin,
max = o.max !== null ? o.max : axis.datamax,
margin = o.autoscaleMargin;
if (o.scaling == 'logarithmic') {
if (min <= 0) min = axis.datamin;
// Let it widen later on
if (max <= 0) max = min;
}
if (max == min) {
var widen = max ? 0.01 : 1.00;
if (o.min === null) min -= widen;
if (o.max === null) max += widen;
}
if (o.scaling === 'logarithmic') {
if (min < 0) min = max / o.base; // Could be the result of widening
var maxexp = Math.log(max);
if (o.base != Math.E) maxexp /= Math.log(o.base);
maxexp = Math.ceil(maxexp);
var minexp = Math.log(min);
if (o.base != Math.E) minexp /= Math.log(o.base);
minexp = Math.ceil(minexp);
axis.tickSize = Flotr.getTickSize(o.noTicks, minexp, maxexp, o.tickDecimals === null ? 0 : o.tickDecimals);
// Try to determine a suitable amount of miniticks based on the length of a decade
if (o.minorTickFreq === null) {
if (maxexp - minexp > 10)
o.minorTickFreq = 0;
else if (maxexp - minexp > 5)
o.minorTickFreq = 2;
else
o.minorTickFreq = 5;
}
} else {
axis.tickSize = Flotr.getTickSize(o.noTicks, min, max, o.tickDecimals);
}
axis.min = min;
axis.max = max; //extendRange may use axis.min or axis.max, so it should be set before it is caled
// Autoscaling. @todo This probably fails with log scale. Find a testcase and fix it
if(o.min === null && o.autoscale){
axis.min -= axis.tickSize * margin;
// Make sure we don't go below zero if all values are positive.
if(axis.min < 0 && axis.datamin >= 0) axis.min = 0;
axis.min = axis.tickSize * Math.floor(axis.min / axis.tickSize);
}
if(o.max === null && o.autoscale){
axis.max += axis.tickSize * margin;
if(axis.max > 0 && axis.datamax <= 0 && axis.datamax != axis.datamin) axis.max = 0;
axis.max = axis.tickSize * Math.ceil(axis.max / axis.tickSize);
}
if (axis.min == axis.max) axis.max = axis.min + 1;
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"used",
")",
"return",
";",
"var",
"axis",
"=",
"this",
",",
"o",
"=",
"axis",
".",
"options",
",",
"min",
"=",
"o",
".",
"min",
"!==",
"null",
"?",
"o",
".",
"min",
":",
"axis",
".",
"datamin",
",",
"max",
"=",
"o",
".",
"max",
"!==",
"null",
"?",
"o",
".",
"max",
":",
"axis",
".",
"datamax",
",",
"margin",
"=",
"o",
".",
"autoscaleMargin",
";",
"if",
"(",
"o",
".",
"scaling",
"==",
"'logarithmic'",
")",
"{",
"if",
"(",
"min",
"<=",
"0",
")",
"min",
"=",
"axis",
".",
"datamin",
";",
"// Let it widen later on",
"if",
"(",
"max",
"<=",
"0",
")",
"max",
"=",
"min",
";",
"}",
"if",
"(",
"max",
"==",
"min",
")",
"{",
"var",
"widen",
"=",
"max",
"?",
"0.01",
":",
"1.00",
";",
"if",
"(",
"o",
".",
"min",
"===",
"null",
")",
"min",
"-=",
"widen",
";",
"if",
"(",
"o",
".",
"max",
"===",
"null",
")",
"max",
"+=",
"widen",
";",
"}",
"if",
"(",
"o",
".",
"scaling",
"===",
"'logarithmic'",
")",
"{",
"if",
"(",
"min",
"<",
"0",
")",
"min",
"=",
"max",
"/",
"o",
".",
"base",
";",
"// Could be the result of widening",
"var",
"maxexp",
"=",
"Math",
".",
"log",
"(",
"max",
")",
";",
"if",
"(",
"o",
".",
"base",
"!=",
"Math",
".",
"E",
")",
"maxexp",
"/=",
"Math",
".",
"log",
"(",
"o",
".",
"base",
")",
";",
"maxexp",
"=",
"Math",
".",
"ceil",
"(",
"maxexp",
")",
";",
"var",
"minexp",
"=",
"Math",
".",
"log",
"(",
"min",
")",
";",
"if",
"(",
"o",
".",
"base",
"!=",
"Math",
".",
"E",
")",
"minexp",
"/=",
"Math",
".",
"log",
"(",
"o",
".",
"base",
")",
";",
"minexp",
"=",
"Math",
".",
"ceil",
"(",
"minexp",
")",
";",
"axis",
".",
"tickSize",
"=",
"Flotr",
".",
"getTickSize",
"(",
"o",
".",
"noTicks",
",",
"minexp",
",",
"maxexp",
",",
"o",
".",
"tickDecimals",
"===",
"null",
"?",
"0",
":",
"o",
".",
"tickDecimals",
")",
";",
"// Try to determine a suitable amount of miniticks based on the length of a decade",
"if",
"(",
"o",
".",
"minorTickFreq",
"===",
"null",
")",
"{",
"if",
"(",
"maxexp",
"-",
"minexp",
">",
"10",
")",
"o",
".",
"minorTickFreq",
"=",
"0",
";",
"else",
"if",
"(",
"maxexp",
"-",
"minexp",
">",
"5",
")",
"o",
".",
"minorTickFreq",
"=",
"2",
";",
"else",
"o",
".",
"minorTickFreq",
"=",
"5",
";",
"}",
"}",
"else",
"{",
"axis",
".",
"tickSize",
"=",
"Flotr",
".",
"getTickSize",
"(",
"o",
".",
"noTicks",
",",
"min",
",",
"max",
",",
"o",
".",
"tickDecimals",
")",
";",
"}",
"axis",
".",
"min",
"=",
"min",
";",
"axis",
".",
"max",
"=",
"max",
";",
"//extendRange may use axis.min or axis.max, so it should be set before it is caled",
"// Autoscaling. @todo This probably fails with log scale. Find a testcase and fix it",
"if",
"(",
"o",
".",
"min",
"===",
"null",
"&&",
"o",
".",
"autoscale",
")",
"{",
"axis",
".",
"min",
"-=",
"axis",
".",
"tickSize",
"*",
"margin",
";",
"// Make sure we don't go below zero if all values are positive.",
"if",
"(",
"axis",
".",
"min",
"<",
"0",
"&&",
"axis",
".",
"datamin",
">=",
"0",
")",
"axis",
".",
"min",
"=",
"0",
";",
"axis",
".",
"min",
"=",
"axis",
".",
"tickSize",
"*",
"Math",
".",
"floor",
"(",
"axis",
".",
"min",
"/",
"axis",
".",
"tickSize",
")",
";",
"}",
"if",
"(",
"o",
".",
"max",
"===",
"null",
"&&",
"o",
".",
"autoscale",
")",
"{",
"axis",
".",
"max",
"+=",
"axis",
".",
"tickSize",
"*",
"margin",
";",
"if",
"(",
"axis",
".",
"max",
">",
"0",
"&&",
"axis",
".",
"datamax",
"<=",
"0",
"&&",
"axis",
".",
"datamax",
"!=",
"axis",
".",
"datamin",
")",
"axis",
".",
"max",
"=",
"0",
";",
"axis",
".",
"max",
"=",
"axis",
".",
"tickSize",
"*",
"Math",
".",
"ceil",
"(",
"axis",
".",
"max",
"/",
"axis",
".",
"tickSize",
")",
";",
"}",
"if",
"(",
"axis",
".",
"min",
"==",
"axis",
".",
"max",
")",
"axis",
".",
"max",
"=",
"axis",
".",
"min",
"+",
"1",
";",
"}"
] |
Calculates the range of an axis to apply autoscaling.
|
[
"Calculates",
"the",
"range",
"of",
"an",
"axis",
"to",
"apply",
"autoscaling",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L1836-L1903
|
|
15,782
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(data){
return _.map(data, function(s){
var series;
if (s.data) {
series = new Series();
_.extend(series, s);
} else {
series = new Series({data:s});
}
return series;
});
}
|
javascript
|
function(data){
return _.map(data, function(s){
var series;
if (s.data) {
series = new Series();
_.extend(series, s);
} else {
series = new Series({data:s});
}
return series;
});
}
|
[
"function",
"(",
"data",
")",
"{",
"return",
"_",
".",
"map",
"(",
"data",
",",
"function",
"(",
"s",
")",
"{",
"var",
"series",
";",
"if",
"(",
"s",
".",
"data",
")",
"{",
"series",
"=",
"new",
"Series",
"(",
")",
";",
"_",
".",
"extend",
"(",
"series",
",",
"s",
")",
";",
"}",
"else",
"{",
"series",
"=",
"new",
"Series",
"(",
"{",
"data",
":",
"s",
"}",
")",
";",
"}",
"return",
"series",
";",
"}",
")",
";",
"}"
] |
Collects dataseries from input and parses the series into the right format. It returns an Array
of Objects each having at least the 'data' key set.
@param {Array, Object} data - Object or array of dataseries
@return {Array} Array of Objects parsed into the right format ({(...,) data: [[x1,y1], [x2,y2], ...] (, ...)})
|
[
"Collects",
"dataseries",
"from",
"input",
"and",
"parses",
"the",
"series",
"into",
"the",
"right",
"format",
".",
"It",
"returns",
"an",
"Array",
"of",
"Objects",
"each",
"having",
"at",
"least",
"the",
"data",
"key",
"set",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L2121-L2132
|
|
15,783
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function (options) {
var
context = options.context,
lineWidth = options.lineWidth,
shadowSize = options.shadowSize,
offset;
context.save();
context.lineJoin = 'round';
if (shadowSize) {
context.lineWidth = shadowSize / 2;
offset = lineWidth / 2 + context.lineWidth / 2;
// @TODO do this instead with a linear gradient
context.strokeStyle = "rgba(0,0,0,0.1)";
this.plot(options, offset + shadowSize / 2, false);
context.strokeStyle = "rgba(0,0,0,0.2)";
this.plot(options, offset, false);
}
context.lineWidth = lineWidth;
context.strokeStyle = options.color;
this.plot(options, 0, true);
context.restore();
}
|
javascript
|
function (options) {
var
context = options.context,
lineWidth = options.lineWidth,
shadowSize = options.shadowSize,
offset;
context.save();
context.lineJoin = 'round';
if (shadowSize) {
context.lineWidth = shadowSize / 2;
offset = lineWidth / 2 + context.lineWidth / 2;
// @TODO do this instead with a linear gradient
context.strokeStyle = "rgba(0,0,0,0.1)";
this.plot(options, offset + shadowSize / 2, false);
context.strokeStyle = "rgba(0,0,0,0.2)";
this.plot(options, offset, false);
}
context.lineWidth = lineWidth;
context.strokeStyle = options.color;
this.plot(options, 0, true);
context.restore();
}
|
[
"function",
"(",
"options",
")",
"{",
"var",
"context",
"=",
"options",
".",
"context",
",",
"lineWidth",
"=",
"options",
".",
"lineWidth",
",",
"shadowSize",
"=",
"options",
".",
"shadowSize",
",",
"offset",
";",
"context",
".",
"save",
"(",
")",
";",
"context",
".",
"lineJoin",
"=",
"'round'",
";",
"if",
"(",
"shadowSize",
")",
"{",
"context",
".",
"lineWidth",
"=",
"shadowSize",
"/",
"2",
";",
"offset",
"=",
"lineWidth",
"/",
"2",
"+",
"context",
".",
"lineWidth",
"/",
"2",
";",
"// @TODO do this instead with a linear gradient",
"context",
".",
"strokeStyle",
"=",
"\"rgba(0,0,0,0.1)\"",
";",
"this",
".",
"plot",
"(",
"options",
",",
"offset",
"+",
"shadowSize",
"/",
"2",
",",
"false",
")",
";",
"context",
".",
"strokeStyle",
"=",
"\"rgba(0,0,0,0.2)\"",
";",
"this",
".",
"plot",
"(",
"options",
",",
"offset",
",",
"false",
")",
";",
"}",
"context",
".",
"lineWidth",
"=",
"lineWidth",
";",
"context",
".",
"strokeStyle",
"=",
"options",
".",
"color",
";",
"this",
".",
"plot",
"(",
"options",
",",
"0",
",",
"true",
")",
";",
"context",
".",
"restore",
"(",
")",
";",
"}"
] |
Draws lines series in the canvas element.
@param {Object} options
|
[
"Draws",
"lines",
"series",
"in",
"the",
"canvas",
"element",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L2160-L2190
|
|
15,784
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(series) {
var ctx = this.ctx,
bw = series.gantt.barWidth,
lw = Math.min(series.gantt.lineWidth, bw);
ctx.save();
ctx.translate(this.plotOffset.left, this.plotOffset.top);
ctx.lineJoin = 'miter';
/**
* @todo linewidth not interpreted the right way.
*/
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
ctx.save();
this.gantt.plotShadows(series, bw, 0, series.gantt.fill);
ctx.restore();
if(series.gantt.fill){
var color = series.gantt.fillColor || series.color;
ctx.fillStyle = this.processColor(color, {opacity: series.gantt.fillOpacity});
}
this.gantt.plot(series, bw, 0, series.gantt.fill);
ctx.restore();
}
|
javascript
|
function(series) {
var ctx = this.ctx,
bw = series.gantt.barWidth,
lw = Math.min(series.gantt.lineWidth, bw);
ctx.save();
ctx.translate(this.plotOffset.left, this.plotOffset.top);
ctx.lineJoin = 'miter';
/**
* @todo linewidth not interpreted the right way.
*/
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
ctx.save();
this.gantt.plotShadows(series, bw, 0, series.gantt.fill);
ctx.restore();
if(series.gantt.fill){
var color = series.gantt.fillColor || series.color;
ctx.fillStyle = this.processColor(color, {opacity: series.gantt.fillOpacity});
}
this.gantt.plot(series, bw, 0, series.gantt.fill);
ctx.restore();
}
|
[
"function",
"(",
"series",
")",
"{",
"var",
"ctx",
"=",
"this",
".",
"ctx",
",",
"bw",
"=",
"series",
".",
"gantt",
".",
"barWidth",
",",
"lw",
"=",
"Math",
".",
"min",
"(",
"series",
".",
"gantt",
".",
"lineWidth",
",",
"bw",
")",
";",
"ctx",
".",
"save",
"(",
")",
";",
"ctx",
".",
"translate",
"(",
"this",
".",
"plotOffset",
".",
"left",
",",
"this",
".",
"plotOffset",
".",
"top",
")",
";",
"ctx",
".",
"lineJoin",
"=",
"'miter'",
";",
"/**\n * @todo linewidth not interpreted the right way.\n */",
"ctx",
".",
"lineWidth",
"=",
"lw",
";",
"ctx",
".",
"strokeStyle",
"=",
"series",
".",
"color",
";",
"ctx",
".",
"save",
"(",
")",
";",
"this",
".",
"gantt",
".",
"plotShadows",
"(",
"series",
",",
"bw",
",",
"0",
",",
"series",
".",
"gantt",
".",
"fill",
")",
";",
"ctx",
".",
"restore",
"(",
")",
";",
"if",
"(",
"series",
".",
"gantt",
".",
"fill",
")",
"{",
"var",
"color",
"=",
"series",
".",
"gantt",
".",
"fillColor",
"||",
"series",
".",
"color",
";",
"ctx",
".",
"fillStyle",
"=",
"this",
".",
"processColor",
"(",
"color",
",",
"{",
"opacity",
":",
"series",
".",
"gantt",
".",
"fillOpacity",
"}",
")",
";",
"}",
"this",
".",
"gantt",
".",
"plot",
"(",
"series",
",",
"bw",
",",
"0",
",",
"series",
".",
"gantt",
".",
"fill",
")",
";",
"ctx",
".",
"restore",
"(",
")",
";",
"}"
] |
Draws gantt series in the canvas element.
@param {Object} series - Series with options.gantt.show = true.
|
[
"Draws",
"gantt",
"series",
"in",
"the",
"canvas",
"element",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L3063-L3089
|
|
15,785
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(s, method, args){
var
success = false,
options;
if (!_.isArray(s)) s = [s];
function e(s, index) {
_.each(_.keys(flotr.graphTypes), function (type) {
if (s[type] && s[type].show && !s.hide && this[type][method]) {
options = this.getOptions(s, type);
options.fill = !!s.mouse.fillColor;
options.fillStyle = this.processColor(s.mouse.fillColor || '#ffffff', {opacity: s.mouse.fillOpacity});
options.color = s.mouse.lineColor;
options.context = this.octx;
options.index = index;
if (args) options.args = args;
this[type][method].call(this[type], options);
success = true;
}
}, this);
}
_.each(s, e, this);
return success;
}
|
javascript
|
function(s, method, args){
var
success = false,
options;
if (!_.isArray(s)) s = [s];
function e(s, index) {
_.each(_.keys(flotr.graphTypes), function (type) {
if (s[type] && s[type].show && !s.hide && this[type][method]) {
options = this.getOptions(s, type);
options.fill = !!s.mouse.fillColor;
options.fillStyle = this.processColor(s.mouse.fillColor || '#ffffff', {opacity: s.mouse.fillOpacity});
options.color = s.mouse.lineColor;
options.context = this.octx;
options.index = index;
if (args) options.args = args;
this[type][method].call(this[type], options);
success = true;
}
}, this);
}
_.each(s, e, this);
return success;
}
|
[
"function",
"(",
"s",
",",
"method",
",",
"args",
")",
"{",
"var",
"success",
"=",
"false",
",",
"options",
";",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"s",
")",
")",
"s",
"=",
"[",
"s",
"]",
";",
"function",
"e",
"(",
"s",
",",
"index",
")",
"{",
"_",
".",
"each",
"(",
"_",
".",
"keys",
"(",
"flotr",
".",
"graphTypes",
")",
",",
"function",
"(",
"type",
")",
"{",
"if",
"(",
"s",
"[",
"type",
"]",
"&&",
"s",
"[",
"type",
"]",
".",
"show",
"&&",
"!",
"s",
".",
"hide",
"&&",
"this",
"[",
"type",
"]",
"[",
"method",
"]",
")",
"{",
"options",
"=",
"this",
".",
"getOptions",
"(",
"s",
",",
"type",
")",
";",
"options",
".",
"fill",
"=",
"!",
"!",
"s",
".",
"mouse",
".",
"fillColor",
";",
"options",
".",
"fillStyle",
"=",
"this",
".",
"processColor",
"(",
"s",
".",
"mouse",
".",
"fillColor",
"||",
"'#ffffff'",
",",
"{",
"opacity",
":",
"s",
".",
"mouse",
".",
"fillOpacity",
"}",
")",
";",
"options",
".",
"color",
"=",
"s",
".",
"mouse",
".",
"lineColor",
";",
"options",
".",
"context",
"=",
"this",
".",
"octx",
";",
"options",
".",
"index",
"=",
"index",
";",
"if",
"(",
"args",
")",
"options",
".",
"args",
"=",
"args",
";",
"this",
"[",
"type",
"]",
"[",
"method",
"]",
".",
"call",
"(",
"this",
"[",
"type",
"]",
",",
"options",
")",
";",
"success",
"=",
"true",
";",
"}",
"}",
",",
"this",
")",
";",
"}",
"_",
".",
"each",
"(",
"s",
",",
"e",
",",
"this",
")",
";",
"return",
"success",
";",
"}"
] |
Try a method on a graph type. If the method exists, execute it.
@param {Object} series
@param {String} method Method name.
@param {Array} args Arguments applied to method.
@return executed successfully or failed.
|
[
"Try",
"a",
"method",
"on",
"a",
"graph",
"type",
".",
"If",
"the",
"method",
"exists",
"execute",
"it",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L4340-L4367
|
|
15,786
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(n){
var octx = this.octx,
s = n.series;
if (s.mouse.lineColor) {
octx.save();
octx.lineWidth = (s.points ? s.points.lineWidth : 1);
octx.strokeStyle = s.mouse.lineColor;
octx.fillStyle = this.processColor(s.mouse.fillColor || '#ffffff', {opacity: s.mouse.fillOpacity});
octx.translate(this.plotOffset.left, this.plotOffset.top);
if (!this.hit.executeOnType(s, 'drawHit', n)) {
var
xa = n.xaxis,
ya = n.yaxis;
octx.beginPath();
// TODO fix this (points) should move to general testable graph mixin
octx.arc(xa.d2p(n.x), ya.d2p(n.y), s.points.hitRadius || s.points.radius || s.mouse.radius, 0, 2 * Math.PI, true);
octx.fill();
octx.stroke();
octx.closePath();
}
octx.restore();
this.clip(octx);
}
this.prevHit = n;
}
|
javascript
|
function(n){
var octx = this.octx,
s = n.series;
if (s.mouse.lineColor) {
octx.save();
octx.lineWidth = (s.points ? s.points.lineWidth : 1);
octx.strokeStyle = s.mouse.lineColor;
octx.fillStyle = this.processColor(s.mouse.fillColor || '#ffffff', {opacity: s.mouse.fillOpacity});
octx.translate(this.plotOffset.left, this.plotOffset.top);
if (!this.hit.executeOnType(s, 'drawHit', n)) {
var
xa = n.xaxis,
ya = n.yaxis;
octx.beginPath();
// TODO fix this (points) should move to general testable graph mixin
octx.arc(xa.d2p(n.x), ya.d2p(n.y), s.points.hitRadius || s.points.radius || s.mouse.radius, 0, 2 * Math.PI, true);
octx.fill();
octx.stroke();
octx.closePath();
}
octx.restore();
this.clip(octx);
}
this.prevHit = n;
}
|
[
"function",
"(",
"n",
")",
"{",
"var",
"octx",
"=",
"this",
".",
"octx",
",",
"s",
"=",
"n",
".",
"series",
";",
"if",
"(",
"s",
".",
"mouse",
".",
"lineColor",
")",
"{",
"octx",
".",
"save",
"(",
")",
";",
"octx",
".",
"lineWidth",
"=",
"(",
"s",
".",
"points",
"?",
"s",
".",
"points",
".",
"lineWidth",
":",
"1",
")",
";",
"octx",
".",
"strokeStyle",
"=",
"s",
".",
"mouse",
".",
"lineColor",
";",
"octx",
".",
"fillStyle",
"=",
"this",
".",
"processColor",
"(",
"s",
".",
"mouse",
".",
"fillColor",
"||",
"'#ffffff'",
",",
"{",
"opacity",
":",
"s",
".",
"mouse",
".",
"fillOpacity",
"}",
")",
";",
"octx",
".",
"translate",
"(",
"this",
".",
"plotOffset",
".",
"left",
",",
"this",
".",
"plotOffset",
".",
"top",
")",
";",
"if",
"(",
"!",
"this",
".",
"hit",
".",
"executeOnType",
"(",
"s",
",",
"'drawHit'",
",",
"n",
")",
")",
"{",
"var",
"xa",
"=",
"n",
".",
"xaxis",
",",
"ya",
"=",
"n",
".",
"yaxis",
";",
"octx",
".",
"beginPath",
"(",
")",
";",
"// TODO fix this (points) should move to general testable graph mixin",
"octx",
".",
"arc",
"(",
"xa",
".",
"d2p",
"(",
"n",
".",
"x",
")",
",",
"ya",
".",
"d2p",
"(",
"n",
".",
"y",
")",
",",
"s",
".",
"points",
".",
"hitRadius",
"||",
"s",
".",
"points",
".",
"radius",
"||",
"s",
".",
"mouse",
".",
"radius",
",",
"0",
",",
"2",
"*",
"Math",
".",
"PI",
",",
"true",
")",
";",
"octx",
".",
"fill",
"(",
")",
";",
"octx",
".",
"stroke",
"(",
")",
";",
"octx",
".",
"closePath",
"(",
")",
";",
"}",
"octx",
".",
"restore",
"(",
")",
";",
"this",
".",
"clip",
"(",
"octx",
")",
";",
"}",
"this",
".",
"prevHit",
"=",
"n",
";",
"}"
] |
Updates the mouse tracking point on the overlay.
|
[
"Updates",
"the",
"mouse",
"tracking",
"point",
"on",
"the",
"overlay",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L4371-L4398
|
|
15,787
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(){
var prev = this.prevHit,
octx = this.octx,
plotOffset = this.plotOffset;
octx.save();
octx.translate(plotOffset.left, plotOffset.top);
if (prev) {
if (!this.hit.executeOnType(prev.series, 'clearHit', this.prevHit)) {
// TODO fix this (points) should move to general testable graph mixin
var
s = prev.series,
lw = (s.points ? s.points.lineWidth : 1);
offset = (s.points.hitRadius || s.points.radius || s.mouse.radius) + lw;
octx.clearRect(
prev.xaxis.d2p(prev.x) - offset,
prev.yaxis.d2p(prev.y) - offset,
offset*2,
offset*2
);
}
D.hide(this.mouseTrack);
this.prevHit = null;
}
octx.restore();
}
|
javascript
|
function(){
var prev = this.prevHit,
octx = this.octx,
plotOffset = this.plotOffset;
octx.save();
octx.translate(plotOffset.left, plotOffset.top);
if (prev) {
if (!this.hit.executeOnType(prev.series, 'clearHit', this.prevHit)) {
// TODO fix this (points) should move to general testable graph mixin
var
s = prev.series,
lw = (s.points ? s.points.lineWidth : 1);
offset = (s.points.hitRadius || s.points.radius || s.mouse.radius) + lw;
octx.clearRect(
prev.xaxis.d2p(prev.x) - offset,
prev.yaxis.d2p(prev.y) - offset,
offset*2,
offset*2
);
}
D.hide(this.mouseTrack);
this.prevHit = null;
}
octx.restore();
}
|
[
"function",
"(",
")",
"{",
"var",
"prev",
"=",
"this",
".",
"prevHit",
",",
"octx",
"=",
"this",
".",
"octx",
",",
"plotOffset",
"=",
"this",
".",
"plotOffset",
";",
"octx",
".",
"save",
"(",
")",
";",
"octx",
".",
"translate",
"(",
"plotOffset",
".",
"left",
",",
"plotOffset",
".",
"top",
")",
";",
"if",
"(",
"prev",
")",
"{",
"if",
"(",
"!",
"this",
".",
"hit",
".",
"executeOnType",
"(",
"prev",
".",
"series",
",",
"'clearHit'",
",",
"this",
".",
"prevHit",
")",
")",
"{",
"// TODO fix this (points) should move to general testable graph mixin",
"var",
"s",
"=",
"prev",
".",
"series",
",",
"lw",
"=",
"(",
"s",
".",
"points",
"?",
"s",
".",
"points",
".",
"lineWidth",
":",
"1",
")",
";",
"offset",
"=",
"(",
"s",
".",
"points",
".",
"hitRadius",
"||",
"s",
".",
"points",
".",
"radius",
"||",
"s",
".",
"mouse",
".",
"radius",
")",
"+",
"lw",
";",
"octx",
".",
"clearRect",
"(",
"prev",
".",
"xaxis",
".",
"d2p",
"(",
"prev",
".",
"x",
")",
"-",
"offset",
",",
"prev",
".",
"yaxis",
".",
"d2p",
"(",
"prev",
".",
"y",
")",
"-",
"offset",
",",
"offset",
"*",
"2",
",",
"offset",
"*",
"2",
")",
";",
"}",
"D",
".",
"hide",
"(",
"this",
".",
"mouseTrack",
")",
";",
"this",
".",
"prevHit",
"=",
"null",
";",
"}",
"octx",
".",
"restore",
"(",
")",
";",
"}"
] |
Removes the mouse tracking point from the overlay.
|
[
"Removes",
"the",
"mouse",
"tracking",
"point",
"from",
"the",
"overlay",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L4402-L4426
|
|
15,788
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(area, preventEvent){
var options = this.options,
xa = this.axes.x,
ya = this.axes.y,
vertScale = ya.scale,
hozScale = xa.scale,
selX = options.selection.mode.indexOf('x') != -1,
selY = options.selection.mode.indexOf('y') != -1,
s = this.selection.selection;
this.selection.clearSelection();
s.first.y = boundY((selX && !selY) ? 0 : (ya.max - area.y1) * vertScale, this);
s.second.y = boundY((selX && !selY) ? this.plotHeight - 1: (ya.max - area.y2) * vertScale, this);
s.first.x = boundX((selY && !selX) ? 0 : (area.x1 - xa.min) * hozScale, this);
s.second.x = boundX((selY && !selX) ? this.plotWidth : (area.x2 - xa.min) * hozScale, this);
this.selection.drawSelection();
if (!preventEvent)
this.selection.fireSelectEvent();
}
|
javascript
|
function(area, preventEvent){
var options = this.options,
xa = this.axes.x,
ya = this.axes.y,
vertScale = ya.scale,
hozScale = xa.scale,
selX = options.selection.mode.indexOf('x') != -1,
selY = options.selection.mode.indexOf('y') != -1,
s = this.selection.selection;
this.selection.clearSelection();
s.first.y = boundY((selX && !selY) ? 0 : (ya.max - area.y1) * vertScale, this);
s.second.y = boundY((selX && !selY) ? this.plotHeight - 1: (ya.max - area.y2) * vertScale, this);
s.first.x = boundX((selY && !selX) ? 0 : (area.x1 - xa.min) * hozScale, this);
s.second.x = boundX((selY && !selX) ? this.plotWidth : (area.x2 - xa.min) * hozScale, this);
this.selection.drawSelection();
if (!preventEvent)
this.selection.fireSelectEvent();
}
|
[
"function",
"(",
"area",
",",
"preventEvent",
")",
"{",
"var",
"options",
"=",
"this",
".",
"options",
",",
"xa",
"=",
"this",
".",
"axes",
".",
"x",
",",
"ya",
"=",
"this",
".",
"axes",
".",
"y",
",",
"vertScale",
"=",
"ya",
".",
"scale",
",",
"hozScale",
"=",
"xa",
".",
"scale",
",",
"selX",
"=",
"options",
".",
"selection",
".",
"mode",
".",
"indexOf",
"(",
"'x'",
")",
"!=",
"-",
"1",
",",
"selY",
"=",
"options",
".",
"selection",
".",
"mode",
".",
"indexOf",
"(",
"'y'",
")",
"!=",
"-",
"1",
",",
"s",
"=",
"this",
".",
"selection",
".",
"selection",
";",
"this",
".",
"selection",
".",
"clearSelection",
"(",
")",
";",
"s",
".",
"first",
".",
"y",
"=",
"boundY",
"(",
"(",
"selX",
"&&",
"!",
"selY",
")",
"?",
"0",
":",
"(",
"ya",
".",
"max",
"-",
"area",
".",
"y1",
")",
"*",
"vertScale",
",",
"this",
")",
";",
"s",
".",
"second",
".",
"y",
"=",
"boundY",
"(",
"(",
"selX",
"&&",
"!",
"selY",
")",
"?",
"this",
".",
"plotHeight",
"-",
"1",
":",
"(",
"ya",
".",
"max",
"-",
"area",
".",
"y2",
")",
"*",
"vertScale",
",",
"this",
")",
";",
"s",
".",
"first",
".",
"x",
"=",
"boundX",
"(",
"(",
"selY",
"&&",
"!",
"selX",
")",
"?",
"0",
":",
"(",
"area",
".",
"x1",
"-",
"xa",
".",
"min",
")",
"*",
"hozScale",
",",
"this",
")",
";",
"s",
".",
"second",
".",
"x",
"=",
"boundX",
"(",
"(",
"selY",
"&&",
"!",
"selX",
")",
"?",
"this",
".",
"plotWidth",
":",
"(",
"area",
".",
"x2",
"-",
"xa",
".",
"min",
")",
"*",
"hozScale",
",",
"this",
")",
";",
"this",
".",
"selection",
".",
"drawSelection",
"(",
")",
";",
"if",
"(",
"!",
"preventEvent",
")",
"this",
".",
"selection",
".",
"fireSelectEvent",
"(",
")",
";",
"}"
] |
Allows the user the manually select an area.
@param {Object} area - Object with coordinates to select.
|
[
"Allows",
"the",
"user",
"the",
"manually",
"select",
"an",
"area",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L4825-L4845
|
|
15,789
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(pos, pointer) {
var mode = this.options.selection.mode,
selection = this.selection.selection;
if(mode.indexOf('x') == -1) {
pos.x = (pos == selection.first) ? 0 : this.plotWidth;
}else{
pos.x = boundX(pointer.relX, this);
}
if (mode.indexOf('y') == -1) {
pos.y = (pos == selection.first) ? 0 : this.plotHeight - 1;
}else{
pos.y = boundY(pointer.relY, this);
}
}
|
javascript
|
function(pos, pointer) {
var mode = this.options.selection.mode,
selection = this.selection.selection;
if(mode.indexOf('x') == -1) {
pos.x = (pos == selection.first) ? 0 : this.plotWidth;
}else{
pos.x = boundX(pointer.relX, this);
}
if (mode.indexOf('y') == -1) {
pos.y = (pos == selection.first) ? 0 : this.plotHeight - 1;
}else{
pos.y = boundY(pointer.relY, this);
}
}
|
[
"function",
"(",
"pos",
",",
"pointer",
")",
"{",
"var",
"mode",
"=",
"this",
".",
"options",
".",
"selection",
".",
"mode",
",",
"selection",
"=",
"this",
".",
"selection",
".",
"selection",
";",
"if",
"(",
"mode",
".",
"indexOf",
"(",
"'x'",
")",
"==",
"-",
"1",
")",
"{",
"pos",
".",
"x",
"=",
"(",
"pos",
"==",
"selection",
".",
"first",
")",
"?",
"0",
":",
"this",
".",
"plotWidth",
";",
"}",
"else",
"{",
"pos",
".",
"x",
"=",
"boundX",
"(",
"pointer",
".",
"relX",
",",
"this",
")",
";",
"}",
"if",
"(",
"mode",
".",
"indexOf",
"(",
"'y'",
")",
"==",
"-",
"1",
")",
"{",
"pos",
".",
"y",
"=",
"(",
"pos",
"==",
"selection",
".",
"first",
")",
"?",
"0",
":",
"this",
".",
"plotHeight",
"-",
"1",
";",
"}",
"else",
"{",
"pos",
".",
"y",
"=",
"boundY",
"(",
"pointer",
".",
"relY",
",",
"this",
")",
";",
"}",
"}"
] |
Calculates the position of the selection.
@param {Object} pos - Position object.
@param {Event} event - Event object.
|
[
"Calculates",
"the",
"position",
"of",
"the",
"selection",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L4852-L4867
|
|
15,790
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(){
var s = this.selection.selection;
return Math.abs(s.second.x - s.first.x) >= 5 ||
Math.abs(s.second.y - s.first.y) >= 5;
}
|
javascript
|
function(){
var s = this.selection.selection;
return Math.abs(s.second.x - s.first.x) >= 5 ||
Math.abs(s.second.y - s.first.y) >= 5;
}
|
[
"function",
"(",
")",
"{",
"var",
"s",
"=",
"this",
".",
"selection",
".",
"selection",
";",
"return",
"Math",
".",
"abs",
"(",
"s",
".",
"second",
".",
"x",
"-",
"s",
".",
"first",
".",
"x",
")",
">=",
"5",
"||",
"Math",
".",
"abs",
"(",
"s",
".",
"second",
".",
"y",
"-",
"s",
".",
"first",
".",
"y",
")",
">=",
"5",
";",
"}"
] |
Determines whether or not the selection is sane and should be drawn.
@return {Boolean} - True when sane, false otherwise.
|
[
"Determines",
"whether",
"or",
"not",
"the",
"selection",
"is",
"sane",
"and",
"should",
"be",
"drawn",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L4960-L4964
|
|
15,791
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(){
// If the data grid has already been built, nothing to do here
if (this.spreadsheet.datagrid) return this.spreadsheet.datagrid;
var s = this.series,
datagrid = this.spreadsheet.loadDataGrid(),
colgroup = ['<colgroup><col />'],
buttonDownload, buttonSelect, t;
// First row : series' labels
var html = ['<table class="flotr-datagrid"><tr class="first-row">'];
html.push('<th> </th>');
_.each(s, function(serie,i){
html.push('<th scope="col">'+(serie.label || String.fromCharCode(65+i))+'</th>');
colgroup.push('<col />');
});
html.push('</tr>');
// Data rows
_.each(datagrid, function(row){
html.push('<tr>');
_.times(s.length+1, function(i){
var tag = 'td',
value = row[i],
// TODO: do we really want to handle problems with floating point
// precision here?
content = (!_.isUndefined(value) ? Math.round(value*100000)/100000 : '');
if (i === 0) {
tag = 'th';
var label = getRowLabel.call(this, content);
if (label) content = label;
}
html.push('<'+tag+(tag=='th'?' scope="row"':'')+'>'+content+'</'+tag+'>');
}, this);
html.push('</tr>');
}, this);
colgroup.push('</colgroup>');
t = D.node(html.join(''));
/**
* @TODO disabled this
if (!Flotr.isIE || Flotr.isIE == 9) {
function handleMouseout(){
t.select('colgroup col.hover, th.hover').invoke('removeClassName', 'hover');
}
function handleMouseover(e){
var td = e.element(),
siblings = td.previousSiblings();
t.select('th[scope=col]')[siblings.length-1].addClassName('hover');
t.select('colgroup col')[siblings.length].addClassName('hover');
}
_.each(t.select('td'), function(td) {
Flotr.EventAdapter.
observe(td, 'mouseover', handleMouseover).
observe(td, 'mouseout', handleMouseout);
});
}
*/
buttonDownload = D.node(
'<button type="button" class="flotr-datagrid-toolbar-button">' +
this.options.spreadsheet.toolbarDownload +
'</button>');
buttonSelect = D.node(
'<button type="button" class="flotr-datagrid-toolbar-button">' +
this.options.spreadsheet.toolbarSelectAll+
'</button>');
this.
observe(buttonDownload, 'click', _.bind(this.spreadsheet.downloadCSV, this)).
observe(buttonSelect, 'click', _.bind(this.spreadsheet.selectAllData, this));
var toolbar = D.node('<div class="flotr-datagrid-toolbar"></div>');
D.insert(toolbar, buttonDownload);
D.insert(toolbar, buttonSelect);
var containerHeight =this.canvasHeight - D.size(this.spreadsheet.tabsContainer).height-2,
container = D.node('<div class="flotr-datagrid-container" style="position:absolute;left:0px;top:0px;width:'+
this.canvasWidth+'px;height:'+containerHeight+'px;overflow:auto;z-index:10"></div>');
D.insert(container, toolbar);
D.insert(container, t);
D.insert(this.el, container);
this.spreadsheet.datagrid = t;
this.spreadsheet.container = container;
return t;
}
|
javascript
|
function(){
// If the data grid has already been built, nothing to do here
if (this.spreadsheet.datagrid) return this.spreadsheet.datagrid;
var s = this.series,
datagrid = this.spreadsheet.loadDataGrid(),
colgroup = ['<colgroup><col />'],
buttonDownload, buttonSelect, t;
// First row : series' labels
var html = ['<table class="flotr-datagrid"><tr class="first-row">'];
html.push('<th> </th>');
_.each(s, function(serie,i){
html.push('<th scope="col">'+(serie.label || String.fromCharCode(65+i))+'</th>');
colgroup.push('<col />');
});
html.push('</tr>');
// Data rows
_.each(datagrid, function(row){
html.push('<tr>');
_.times(s.length+1, function(i){
var tag = 'td',
value = row[i],
// TODO: do we really want to handle problems with floating point
// precision here?
content = (!_.isUndefined(value) ? Math.round(value*100000)/100000 : '');
if (i === 0) {
tag = 'th';
var label = getRowLabel.call(this, content);
if (label) content = label;
}
html.push('<'+tag+(tag=='th'?' scope="row"':'')+'>'+content+'</'+tag+'>');
}, this);
html.push('</tr>');
}, this);
colgroup.push('</colgroup>');
t = D.node(html.join(''));
/**
* @TODO disabled this
if (!Flotr.isIE || Flotr.isIE == 9) {
function handleMouseout(){
t.select('colgroup col.hover, th.hover').invoke('removeClassName', 'hover');
}
function handleMouseover(e){
var td = e.element(),
siblings = td.previousSiblings();
t.select('th[scope=col]')[siblings.length-1].addClassName('hover');
t.select('colgroup col')[siblings.length].addClassName('hover');
}
_.each(t.select('td'), function(td) {
Flotr.EventAdapter.
observe(td, 'mouseover', handleMouseover).
observe(td, 'mouseout', handleMouseout);
});
}
*/
buttonDownload = D.node(
'<button type="button" class="flotr-datagrid-toolbar-button">' +
this.options.spreadsheet.toolbarDownload +
'</button>');
buttonSelect = D.node(
'<button type="button" class="flotr-datagrid-toolbar-button">' +
this.options.spreadsheet.toolbarSelectAll+
'</button>');
this.
observe(buttonDownload, 'click', _.bind(this.spreadsheet.downloadCSV, this)).
observe(buttonSelect, 'click', _.bind(this.spreadsheet.selectAllData, this));
var toolbar = D.node('<div class="flotr-datagrid-toolbar"></div>');
D.insert(toolbar, buttonDownload);
D.insert(toolbar, buttonSelect);
var containerHeight =this.canvasHeight - D.size(this.spreadsheet.tabsContainer).height-2,
container = D.node('<div class="flotr-datagrid-container" style="position:absolute;left:0px;top:0px;width:'+
this.canvasWidth+'px;height:'+containerHeight+'px;overflow:auto;z-index:10"></div>');
D.insert(container, toolbar);
D.insert(container, t);
D.insert(this.el, container);
this.spreadsheet.datagrid = t;
this.spreadsheet.container = container;
return t;
}
|
[
"function",
"(",
")",
"{",
"// If the data grid has already been built, nothing to do here",
"if",
"(",
"this",
".",
"spreadsheet",
".",
"datagrid",
")",
"return",
"this",
".",
"spreadsheet",
".",
"datagrid",
";",
"var",
"s",
"=",
"this",
".",
"series",
",",
"datagrid",
"=",
"this",
".",
"spreadsheet",
".",
"loadDataGrid",
"(",
")",
",",
"colgroup",
"=",
"[",
"'<colgroup><col />'",
"]",
",",
"buttonDownload",
",",
"buttonSelect",
",",
"t",
";",
"// First row : series' labels",
"var",
"html",
"=",
"[",
"'<table class=\"flotr-datagrid\"><tr class=\"first-row\">'",
"]",
";",
"html",
".",
"push",
"(",
"'<th> </th>'",
")",
";",
"_",
".",
"each",
"(",
"s",
",",
"function",
"(",
"serie",
",",
"i",
")",
"{",
"html",
".",
"push",
"(",
"'<th scope=\"col\">'",
"+",
"(",
"serie",
".",
"label",
"||",
"String",
".",
"fromCharCode",
"(",
"65",
"+",
"i",
")",
")",
"+",
"'</th>'",
")",
";",
"colgroup",
".",
"push",
"(",
"'<col />'",
")",
";",
"}",
")",
";",
"html",
".",
"push",
"(",
"'</tr>'",
")",
";",
"// Data rows",
"_",
".",
"each",
"(",
"datagrid",
",",
"function",
"(",
"row",
")",
"{",
"html",
".",
"push",
"(",
"'<tr>'",
")",
";",
"_",
".",
"times",
"(",
"s",
".",
"length",
"+",
"1",
",",
"function",
"(",
"i",
")",
"{",
"var",
"tag",
"=",
"'td'",
",",
"value",
"=",
"row",
"[",
"i",
"]",
",",
"// TODO: do we really want to handle problems with floating point",
"// precision here?",
"content",
"=",
"(",
"!",
"_",
".",
"isUndefined",
"(",
"value",
")",
"?",
"Math",
".",
"round",
"(",
"value",
"*",
"100000",
")",
"/",
"100000",
":",
"''",
")",
";",
"if",
"(",
"i",
"===",
"0",
")",
"{",
"tag",
"=",
"'th'",
";",
"var",
"label",
"=",
"getRowLabel",
".",
"call",
"(",
"this",
",",
"content",
")",
";",
"if",
"(",
"label",
")",
"content",
"=",
"label",
";",
"}",
"html",
".",
"push",
"(",
"'<'",
"+",
"tag",
"+",
"(",
"tag",
"==",
"'th'",
"?",
"' scope=\"row\"'",
":",
"''",
")",
"+",
"'>'",
"+",
"content",
"+",
"'</'",
"+",
"tag",
"+",
"'>'",
")",
";",
"}",
",",
"this",
")",
";",
"html",
".",
"push",
"(",
"'</tr>'",
")",
";",
"}",
",",
"this",
")",
";",
"colgroup",
".",
"push",
"(",
"'</colgroup>'",
")",
";",
"t",
"=",
"D",
".",
"node",
"(",
"html",
".",
"join",
"(",
"''",
")",
")",
";",
"/**\n * @TODO disabled this\n if (!Flotr.isIE || Flotr.isIE == 9) {\n function handleMouseout(){\n t.select('colgroup col.hover, th.hover').invoke('removeClassName', 'hover');\n }\n function handleMouseover(e){\n var td = e.element(),\n siblings = td.previousSiblings();\n t.select('th[scope=col]')[siblings.length-1].addClassName('hover');\n t.select('colgroup col')[siblings.length].addClassName('hover');\n }\n _.each(t.select('td'), function(td) {\n Flotr.EventAdapter.\n observe(td, 'mouseover', handleMouseover).\n observe(td, 'mouseout', handleMouseout);\n });\n }\n */",
"buttonDownload",
"=",
"D",
".",
"node",
"(",
"'<button type=\"button\" class=\"flotr-datagrid-toolbar-button\">'",
"+",
"this",
".",
"options",
".",
"spreadsheet",
".",
"toolbarDownload",
"+",
"'</button>'",
")",
";",
"buttonSelect",
"=",
"D",
".",
"node",
"(",
"'<button type=\"button\" class=\"flotr-datagrid-toolbar-button\">'",
"+",
"this",
".",
"options",
".",
"spreadsheet",
".",
"toolbarSelectAll",
"+",
"'</button>'",
")",
";",
"this",
".",
"observe",
"(",
"buttonDownload",
",",
"'click'",
",",
"_",
".",
"bind",
"(",
"this",
".",
"spreadsheet",
".",
"downloadCSV",
",",
"this",
")",
")",
".",
"observe",
"(",
"buttonSelect",
",",
"'click'",
",",
"_",
".",
"bind",
"(",
"this",
".",
"spreadsheet",
".",
"selectAllData",
",",
"this",
")",
")",
";",
"var",
"toolbar",
"=",
"D",
".",
"node",
"(",
"'<div class=\"flotr-datagrid-toolbar\"></div>'",
")",
";",
"D",
".",
"insert",
"(",
"toolbar",
",",
"buttonDownload",
")",
";",
"D",
".",
"insert",
"(",
"toolbar",
",",
"buttonSelect",
")",
";",
"var",
"containerHeight",
"=",
"this",
".",
"canvasHeight",
"-",
"D",
".",
"size",
"(",
"this",
".",
"spreadsheet",
".",
"tabsContainer",
")",
".",
"height",
"-",
"2",
",",
"container",
"=",
"D",
".",
"node",
"(",
"'<div class=\"flotr-datagrid-container\" style=\"position:absolute;left:0px;top:0px;width:'",
"+",
"this",
".",
"canvasWidth",
"+",
"'px;height:'",
"+",
"containerHeight",
"+",
"'px;overflow:auto;z-index:10\"></div>'",
")",
";",
"D",
".",
"insert",
"(",
"container",
",",
"toolbar",
")",
";",
"D",
".",
"insert",
"(",
"container",
",",
"t",
")",
";",
"D",
".",
"insert",
"(",
"this",
".",
"el",
",",
"container",
")",
";",
"this",
".",
"spreadsheet",
".",
"datagrid",
"=",
"t",
";",
"this",
".",
"spreadsheet",
".",
"container",
"=",
"container",
";",
"return",
"t",
";",
"}"
] |
Constructs the data table for the spreadsheet
@todo make a spreadsheet manager (Flotr.Spreadsheet)
@return {Element} The resulting table element
|
[
"Constructs",
"the",
"data",
"table",
"for",
"the",
"spreadsheet"
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L5502-L5590
|
|
15,792
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(tabName){
if (this.spreadsheet.activeTab === tabName){
return;
}
switch(tabName) {
case 'graph':
D.hide(this.spreadsheet.container);
D.removeClass(this.spreadsheet.tabs.data, 'selected');
D.addClass(this.spreadsheet.tabs.graph, 'selected');
break;
case 'data':
if (!this.spreadsheet.datagrid)
this.spreadsheet.constructDataGrid();
D.show(this.spreadsheet.container);
D.addClass(this.spreadsheet.tabs.data, 'selected');
D.removeClass(this.spreadsheet.tabs.graph, 'selected');
break;
default:
throw 'Illegal tab name: ' + tabName;
}
this.spreadsheet.activeTab = tabName;
}
|
javascript
|
function(tabName){
if (this.spreadsheet.activeTab === tabName){
return;
}
switch(tabName) {
case 'graph':
D.hide(this.spreadsheet.container);
D.removeClass(this.spreadsheet.tabs.data, 'selected');
D.addClass(this.spreadsheet.tabs.graph, 'selected');
break;
case 'data':
if (!this.spreadsheet.datagrid)
this.spreadsheet.constructDataGrid();
D.show(this.spreadsheet.container);
D.addClass(this.spreadsheet.tabs.data, 'selected');
D.removeClass(this.spreadsheet.tabs.graph, 'selected');
break;
default:
throw 'Illegal tab name: ' + tabName;
}
this.spreadsheet.activeTab = tabName;
}
|
[
"function",
"(",
"tabName",
")",
"{",
"if",
"(",
"this",
".",
"spreadsheet",
".",
"activeTab",
"===",
"tabName",
")",
"{",
"return",
";",
"}",
"switch",
"(",
"tabName",
")",
"{",
"case",
"'graph'",
":",
"D",
".",
"hide",
"(",
"this",
".",
"spreadsheet",
".",
"container",
")",
";",
"D",
".",
"removeClass",
"(",
"this",
".",
"spreadsheet",
".",
"tabs",
".",
"data",
",",
"'selected'",
")",
";",
"D",
".",
"addClass",
"(",
"this",
".",
"spreadsheet",
".",
"tabs",
".",
"graph",
",",
"'selected'",
")",
";",
"break",
";",
"case",
"'data'",
":",
"if",
"(",
"!",
"this",
".",
"spreadsheet",
".",
"datagrid",
")",
"this",
".",
"spreadsheet",
".",
"constructDataGrid",
"(",
")",
";",
"D",
".",
"show",
"(",
"this",
".",
"spreadsheet",
".",
"container",
")",
";",
"D",
".",
"addClass",
"(",
"this",
".",
"spreadsheet",
".",
"tabs",
".",
"data",
",",
"'selected'",
")",
";",
"D",
".",
"removeClass",
"(",
"this",
".",
"spreadsheet",
".",
"tabs",
".",
"graph",
",",
"'selected'",
")",
";",
"break",
";",
"default",
":",
"throw",
"'Illegal tab name: '",
"+",
"tabName",
";",
"}",
"this",
".",
"spreadsheet",
".",
"activeTab",
"=",
"tabName",
";",
"}"
] |
Shows the specified tab, by its name
@todo make a tab manager (Flotr.Tabs)
@param {String} tabName - The tab name
|
[
"Shows",
"the",
"specified",
"tab",
"by",
"its",
"name"
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L5596-L5617
|
|
15,793
|
HumbleSoftware/Flotr2
|
flotr2.nolibs.js
|
function(){
var csv = '',
series = this.series,
options = this.options,
dg = this.spreadsheet.loadDataGrid(),
separator = encodeURIComponent(options.spreadsheet.csvFileSeparator);
if (options.spreadsheet.decimalSeparator === options.spreadsheet.csvFileSeparator) {
throw "The decimal separator is the same as the column separator ("+options.spreadsheet.decimalSeparator+")";
}
// The first row
_.each(series, function(serie, i){
csv += separator+'"'+(serie.label || String.fromCharCode(65+i)).replace(/\"/g, '\\"')+'"';
});
csv += "%0D%0A"; // \r\n
// For each row
csv += _.reduce(dg, function(memo, row){
var rowLabel = getRowLabel.call(this, row[0]) || '';
rowLabel = '"'+(rowLabel+'').replace(/\"/g, '\\"')+'"';
var numbers = row.slice(1).join(separator);
if (options.spreadsheet.decimalSeparator !== '.') {
numbers = numbers.replace(/\./g, options.spreadsheet.decimalSeparator);
}
return memo + rowLabel+separator+numbers+"%0D%0A"; // \t and \r\n
}, '', this);
if (Flotr.isIE && Flotr.isIE < 9) {
csv = csv.replace(new RegExp(separator, 'g'), decodeURIComponent(separator)).replace(/%0A/g, '\n').replace(/%0D/g, '\r');
window.open().document.write(csv);
}
else window.open('data:text/csv,'+csv);
}
|
javascript
|
function(){
var csv = '',
series = this.series,
options = this.options,
dg = this.spreadsheet.loadDataGrid(),
separator = encodeURIComponent(options.spreadsheet.csvFileSeparator);
if (options.spreadsheet.decimalSeparator === options.spreadsheet.csvFileSeparator) {
throw "The decimal separator is the same as the column separator ("+options.spreadsheet.decimalSeparator+")";
}
// The first row
_.each(series, function(serie, i){
csv += separator+'"'+(serie.label || String.fromCharCode(65+i)).replace(/\"/g, '\\"')+'"';
});
csv += "%0D%0A"; // \r\n
// For each row
csv += _.reduce(dg, function(memo, row){
var rowLabel = getRowLabel.call(this, row[0]) || '';
rowLabel = '"'+(rowLabel+'').replace(/\"/g, '\\"')+'"';
var numbers = row.slice(1).join(separator);
if (options.spreadsheet.decimalSeparator !== '.') {
numbers = numbers.replace(/\./g, options.spreadsheet.decimalSeparator);
}
return memo + rowLabel+separator+numbers+"%0D%0A"; // \t and \r\n
}, '', this);
if (Flotr.isIE && Flotr.isIE < 9) {
csv = csv.replace(new RegExp(separator, 'g'), decodeURIComponent(separator)).replace(/%0A/g, '\n').replace(/%0D/g, '\r');
window.open().document.write(csv);
}
else window.open('data:text/csv,'+csv);
}
|
[
"function",
"(",
")",
"{",
"var",
"csv",
"=",
"''",
",",
"series",
"=",
"this",
".",
"series",
",",
"options",
"=",
"this",
".",
"options",
",",
"dg",
"=",
"this",
".",
"spreadsheet",
".",
"loadDataGrid",
"(",
")",
",",
"separator",
"=",
"encodeURIComponent",
"(",
"options",
".",
"spreadsheet",
".",
"csvFileSeparator",
")",
";",
"if",
"(",
"options",
".",
"spreadsheet",
".",
"decimalSeparator",
"===",
"options",
".",
"spreadsheet",
".",
"csvFileSeparator",
")",
"{",
"throw",
"\"The decimal separator is the same as the column separator (\"",
"+",
"options",
".",
"spreadsheet",
".",
"decimalSeparator",
"+",
"\")\"",
";",
"}",
"// The first row",
"_",
".",
"each",
"(",
"series",
",",
"function",
"(",
"serie",
",",
"i",
")",
"{",
"csv",
"+=",
"separator",
"+",
"'\"'",
"+",
"(",
"serie",
".",
"label",
"||",
"String",
".",
"fromCharCode",
"(",
"65",
"+",
"i",
")",
")",
".",
"replace",
"(",
"/",
"\\\"",
"/",
"g",
",",
"'\\\\\"'",
")",
"+",
"'\"'",
";",
"}",
")",
";",
"csv",
"+=",
"\"%0D%0A\"",
";",
"// \\r\\n",
"// For each row",
"csv",
"+=",
"_",
".",
"reduce",
"(",
"dg",
",",
"function",
"(",
"memo",
",",
"row",
")",
"{",
"var",
"rowLabel",
"=",
"getRowLabel",
".",
"call",
"(",
"this",
",",
"row",
"[",
"0",
"]",
")",
"||",
"''",
";",
"rowLabel",
"=",
"'\"'",
"+",
"(",
"rowLabel",
"+",
"''",
")",
".",
"replace",
"(",
"/",
"\\\"",
"/",
"g",
",",
"'\\\\\"'",
")",
"+",
"'\"'",
";",
"var",
"numbers",
"=",
"row",
".",
"slice",
"(",
"1",
")",
".",
"join",
"(",
"separator",
")",
";",
"if",
"(",
"options",
".",
"spreadsheet",
".",
"decimalSeparator",
"!==",
"'.'",
")",
"{",
"numbers",
"=",
"numbers",
".",
"replace",
"(",
"/",
"\\.",
"/",
"g",
",",
"options",
".",
"spreadsheet",
".",
"decimalSeparator",
")",
";",
"}",
"return",
"memo",
"+",
"rowLabel",
"+",
"separator",
"+",
"numbers",
"+",
"\"%0D%0A\"",
";",
"// \\t and \\r\\n",
"}",
",",
"''",
",",
"this",
")",
";",
"if",
"(",
"Flotr",
".",
"isIE",
"&&",
"Flotr",
".",
"isIE",
"<",
"9",
")",
"{",
"csv",
"=",
"csv",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"separator",
",",
"'g'",
")",
",",
"decodeURIComponent",
"(",
"separator",
")",
")",
".",
"replace",
"(",
"/",
"%0A",
"/",
"g",
",",
"'\\n'",
")",
".",
"replace",
"(",
"/",
"%0D",
"/",
"g",
",",
"'\\r'",
")",
";",
"window",
".",
"open",
"(",
")",
".",
"document",
".",
"write",
"(",
"csv",
")",
";",
"}",
"else",
"window",
".",
"open",
"(",
"'data:text/csv,'",
"+",
"csv",
")",
";",
"}"
] |
Converts the data into CSV in order to download a file
|
[
"Converts",
"the",
"data",
"into",
"CSV",
"in",
"order",
"to",
"download",
"a",
"file"
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.nolibs.js#L5651-L5685
|
|
15,794
|
HumbleSoftware/Flotr2
|
flotr2.amd.js
|
function(src, dest){
var i, v, result = dest || {};
for (i in src) {
v = src[i];
if (v && typeof(v) === 'object') {
if (v.constructor === Array) {
result[i] = this._.clone(v);
} else if (v.constructor !== RegExp && !this._.isElement(v)) {
result[i] = Flotr.merge(v, (dest ? dest[i] : undefined));
} else {
result[i] = v;
}
} else {
result[i] = v;
}
}
return result;
}
|
javascript
|
function(src, dest){
var i, v, result = dest || {};
for (i in src) {
v = src[i];
if (v && typeof(v) === 'object') {
if (v.constructor === Array) {
result[i] = this._.clone(v);
} else if (v.constructor !== RegExp && !this._.isElement(v)) {
result[i] = Flotr.merge(v, (dest ? dest[i] : undefined));
} else {
result[i] = v;
}
} else {
result[i] = v;
}
}
return result;
}
|
[
"function",
"(",
"src",
",",
"dest",
")",
"{",
"var",
"i",
",",
"v",
",",
"result",
"=",
"dest",
"||",
"{",
"}",
";",
"for",
"(",
"i",
"in",
"src",
")",
"{",
"v",
"=",
"src",
"[",
"i",
"]",
";",
"if",
"(",
"v",
"&&",
"typeof",
"(",
"v",
")",
"===",
"'object'",
")",
"{",
"if",
"(",
"v",
".",
"constructor",
"===",
"Array",
")",
"{",
"result",
"[",
"i",
"]",
"=",
"this",
".",
"_",
".",
"clone",
"(",
"v",
")",
";",
"}",
"else",
"if",
"(",
"v",
".",
"constructor",
"!==",
"RegExp",
"&&",
"!",
"this",
".",
"_",
".",
"isElement",
"(",
"v",
")",
")",
"{",
"result",
"[",
"i",
"]",
"=",
"Flotr",
".",
"merge",
"(",
"v",
",",
"(",
"dest",
"?",
"dest",
"[",
"i",
"]",
":",
"undefined",
")",
")",
";",
"}",
"else",
"{",
"result",
"[",
"i",
"]",
"=",
"v",
";",
"}",
"}",
"else",
"{",
"result",
"[",
"i",
"]",
"=",
"v",
";",
"}",
"}",
"return",
"result",
";",
"}"
] |
Recursively merges two objects.
@param {Object} src - source object (likely the object with the least properties)
@param {Object} dest - destination object (optional, object with the most properties)
@return {Object} recursively merged Object
@TODO See if we can't remove this.
|
[
"Recursively",
"merges",
"two",
"objects",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.amd.js#L89-L108
|
|
15,795
|
HumbleSoftware/Flotr2
|
flotr2.amd.js
|
function(element, child){
if(_.isString(child))
element.innerHTML += child;
else if (_.isElement(child))
element.appendChild(child);
}
|
javascript
|
function(element, child){
if(_.isString(child))
element.innerHTML += child;
else if (_.isElement(child))
element.appendChild(child);
}
|
[
"function",
"(",
"element",
",",
"child",
")",
"{",
"if",
"(",
"_",
".",
"isString",
"(",
"child",
")",
")",
"element",
".",
"innerHTML",
"+=",
"child",
";",
"else",
"if",
"(",
"_",
".",
"isElement",
"(",
"child",
")",
")",
"element",
".",
"appendChild",
"(",
"child",
")",
";",
"}"
] |
Insert a child.
@param {Element} element
@param {Element|String} Element or string to be appended.
|
[
"Insert",
"a",
"child",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.amd.js#L781-L786
|
|
15,796
|
HumbleSoftware/Flotr2
|
flotr2.amd.js
|
function (mouse) {
var
options = this.options,
prevHit = this.prevHit,
closest, sensibility, dataIndex, seriesIndex, series, value, xaxis, yaxis, n;
if (this.series.length === 0) return;
// Nearest data element.
// dist, x, y, relX, relY, absX, absY, sAngle, eAngle, fraction, mouse,
// xaxis, yaxis, series, index, seriesIndex
n = {
relX : mouse.relX,
relY : mouse.relY,
absX : mouse.absX,
absY : mouse.absY
};
if (options.mouse.trackY &&
!options.mouse.trackAll &&
this.hit.executeOnType(this.series, 'hit', [mouse, n]) &&
!_.isUndefined(n.seriesIndex))
{
series = this.series[n.seriesIndex];
n.series = series;
n.mouse = series.mouse;
n.xaxis = series.xaxis;
n.yaxis = series.yaxis;
} else {
closest = this.hit.closest(mouse);
if (closest) {
closest = options.mouse.trackY ? closest.point : closest.x;
seriesIndex = closest.seriesIndex;
series = this.series[seriesIndex];
xaxis = series.xaxis;
yaxis = series.yaxis;
sensibility = 2 * series.mouse.sensibility;
if
(options.mouse.trackAll ||
(closest.distanceX < sensibility / xaxis.scale &&
(!options.mouse.trackY || closest.distanceY < sensibility / yaxis.scale)))
{
n.series = series;
n.xaxis = series.xaxis;
n.yaxis = series.yaxis;
n.mouse = series.mouse;
n.x = closest.x;
n.y = closest.y;
n.dist = closest.distance;
n.index = closest.dataIndex;
n.seriesIndex = seriesIndex;
}
}
}
if (!prevHit || (prevHit.index !== n.index || prevHit.seriesIndex !== n.seriesIndex)) {
this.hit.clearHit();
if (n.series && n.mouse && n.mouse.track) {
this.hit.drawMouseTrack(n);
this.hit.drawHit(n);
Flotr.EventAdapter.fire(this.el, 'flotr:hit', [n, this]);
}
}
return n;
}
|
javascript
|
function (mouse) {
var
options = this.options,
prevHit = this.prevHit,
closest, sensibility, dataIndex, seriesIndex, series, value, xaxis, yaxis, n;
if (this.series.length === 0) return;
// Nearest data element.
// dist, x, y, relX, relY, absX, absY, sAngle, eAngle, fraction, mouse,
// xaxis, yaxis, series, index, seriesIndex
n = {
relX : mouse.relX,
relY : mouse.relY,
absX : mouse.absX,
absY : mouse.absY
};
if (options.mouse.trackY &&
!options.mouse.trackAll &&
this.hit.executeOnType(this.series, 'hit', [mouse, n]) &&
!_.isUndefined(n.seriesIndex))
{
series = this.series[n.seriesIndex];
n.series = series;
n.mouse = series.mouse;
n.xaxis = series.xaxis;
n.yaxis = series.yaxis;
} else {
closest = this.hit.closest(mouse);
if (closest) {
closest = options.mouse.trackY ? closest.point : closest.x;
seriesIndex = closest.seriesIndex;
series = this.series[seriesIndex];
xaxis = series.xaxis;
yaxis = series.yaxis;
sensibility = 2 * series.mouse.sensibility;
if
(options.mouse.trackAll ||
(closest.distanceX < sensibility / xaxis.scale &&
(!options.mouse.trackY || closest.distanceY < sensibility / yaxis.scale)))
{
n.series = series;
n.xaxis = series.xaxis;
n.yaxis = series.yaxis;
n.mouse = series.mouse;
n.x = closest.x;
n.y = closest.y;
n.dist = closest.distance;
n.index = closest.dataIndex;
n.seriesIndex = seriesIndex;
}
}
}
if (!prevHit || (prevHit.index !== n.index || prevHit.seriesIndex !== n.seriesIndex)) {
this.hit.clearHit();
if (n.series && n.mouse && n.mouse.track) {
this.hit.drawMouseTrack(n);
this.hit.drawHit(n);
Flotr.EventAdapter.fire(this.el, 'flotr:hit', [n, this]);
}
}
return n;
}
|
[
"function",
"(",
"mouse",
")",
"{",
"var",
"options",
"=",
"this",
".",
"options",
",",
"prevHit",
"=",
"this",
".",
"prevHit",
",",
"closest",
",",
"sensibility",
",",
"dataIndex",
",",
"seriesIndex",
",",
"series",
",",
"value",
",",
"xaxis",
",",
"yaxis",
",",
"n",
";",
"if",
"(",
"this",
".",
"series",
".",
"length",
"===",
"0",
")",
"return",
";",
"// Nearest data element.",
"// dist, x, y, relX, relY, absX, absY, sAngle, eAngle, fraction, mouse,",
"// xaxis, yaxis, series, index, seriesIndex",
"n",
"=",
"{",
"relX",
":",
"mouse",
".",
"relX",
",",
"relY",
":",
"mouse",
".",
"relY",
",",
"absX",
":",
"mouse",
".",
"absX",
",",
"absY",
":",
"mouse",
".",
"absY",
"}",
";",
"if",
"(",
"options",
".",
"mouse",
".",
"trackY",
"&&",
"!",
"options",
".",
"mouse",
".",
"trackAll",
"&&",
"this",
".",
"hit",
".",
"executeOnType",
"(",
"this",
".",
"series",
",",
"'hit'",
",",
"[",
"mouse",
",",
"n",
"]",
")",
"&&",
"!",
"_",
".",
"isUndefined",
"(",
"n",
".",
"seriesIndex",
")",
")",
"{",
"series",
"=",
"this",
".",
"series",
"[",
"n",
".",
"seriesIndex",
"]",
";",
"n",
".",
"series",
"=",
"series",
";",
"n",
".",
"mouse",
"=",
"series",
".",
"mouse",
";",
"n",
".",
"xaxis",
"=",
"series",
".",
"xaxis",
";",
"n",
".",
"yaxis",
"=",
"series",
".",
"yaxis",
";",
"}",
"else",
"{",
"closest",
"=",
"this",
".",
"hit",
".",
"closest",
"(",
"mouse",
")",
";",
"if",
"(",
"closest",
")",
"{",
"closest",
"=",
"options",
".",
"mouse",
".",
"trackY",
"?",
"closest",
".",
"point",
":",
"closest",
".",
"x",
";",
"seriesIndex",
"=",
"closest",
".",
"seriesIndex",
";",
"series",
"=",
"this",
".",
"series",
"[",
"seriesIndex",
"]",
";",
"xaxis",
"=",
"series",
".",
"xaxis",
";",
"yaxis",
"=",
"series",
".",
"yaxis",
";",
"sensibility",
"=",
"2",
"*",
"series",
".",
"mouse",
".",
"sensibility",
";",
"if",
"(",
"options",
".",
"mouse",
".",
"trackAll",
"||",
"(",
"closest",
".",
"distanceX",
"<",
"sensibility",
"/",
"xaxis",
".",
"scale",
"&&",
"(",
"!",
"options",
".",
"mouse",
".",
"trackY",
"||",
"closest",
".",
"distanceY",
"<",
"sensibility",
"/",
"yaxis",
".",
"scale",
")",
")",
")",
"{",
"n",
".",
"series",
"=",
"series",
";",
"n",
".",
"xaxis",
"=",
"series",
".",
"xaxis",
";",
"n",
".",
"yaxis",
"=",
"series",
".",
"yaxis",
";",
"n",
".",
"mouse",
"=",
"series",
".",
"mouse",
";",
"n",
".",
"x",
"=",
"closest",
".",
"x",
";",
"n",
".",
"y",
"=",
"closest",
".",
"y",
";",
"n",
".",
"dist",
"=",
"closest",
".",
"distance",
";",
"n",
".",
"index",
"=",
"closest",
".",
"dataIndex",
";",
"n",
".",
"seriesIndex",
"=",
"seriesIndex",
";",
"}",
"}",
"}",
"if",
"(",
"!",
"prevHit",
"||",
"(",
"prevHit",
".",
"index",
"!==",
"n",
".",
"index",
"||",
"prevHit",
".",
"seriesIndex",
"!==",
"n",
".",
"seriesIndex",
")",
")",
"{",
"this",
".",
"hit",
".",
"clearHit",
"(",
")",
";",
"if",
"(",
"n",
".",
"series",
"&&",
"n",
".",
"mouse",
"&&",
"n",
".",
"mouse",
".",
"track",
")",
"{",
"this",
".",
"hit",
".",
"drawMouseTrack",
"(",
"n",
")",
";",
"this",
".",
"hit",
".",
"drawHit",
"(",
"n",
")",
";",
"Flotr",
".",
"EventAdapter",
".",
"fire",
"(",
"this",
".",
"el",
",",
"'flotr:hit'",
",",
"[",
"n",
",",
"this",
"]",
")",
";",
"}",
"}",
"return",
"n",
";",
"}"
] |
Retrieves the nearest data point from the mouse cursor. If it's within
a certain range, draw a point on the overlay canvas and display the x and y
value of the data.
@param {Object} mouse - Object that holds the relative x and y coordinates of the cursor.
|
[
"Retrieves",
"the",
"nearest",
"data",
"point",
"from",
"the",
"mouse",
"cursor",
".",
"If",
"it",
"s",
"within",
"a",
"certain",
"range",
"draw",
"a",
"point",
"on",
"the",
"overlay",
"canvas",
"and",
"display",
"the",
"x",
"and",
"y",
"value",
"of",
"the",
"data",
"."
] |
df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5
|
https://github.com/HumbleSoftware/Flotr2/blob/df0ddedcab1a8fdb3a7abafc5fe97819931e7bd5/flotr2.amd.js#L4243-L4313
|
|
15,797
|
TooTallNate/NodObjC
|
lib/import.js
|
resolve
|
function resolve (framework) {
// strip off a trailing slash if present
if (framework[framework.length-1] == '/')
framework = framework.slice(0, framework.length-1);
// already absolute, return as-is
if (~framework.indexOf('/')) return framework;
var i=0, l=PATH.length, rtn=null;
for (; i<l; i++) {
rtn = join(PATH[i], framework + SUFFIX);
if (exists(rtn)) return rtn;
}
throw new Error('Could not resolve framework: ' + framework);
}
|
javascript
|
function resolve (framework) {
// strip off a trailing slash if present
if (framework[framework.length-1] == '/')
framework = framework.slice(0, framework.length-1);
// already absolute, return as-is
if (~framework.indexOf('/')) return framework;
var i=0, l=PATH.length, rtn=null;
for (; i<l; i++) {
rtn = join(PATH[i], framework + SUFFIX);
if (exists(rtn)) return rtn;
}
throw new Error('Could not resolve framework: ' + framework);
}
|
[
"function",
"resolve",
"(",
"framework",
")",
"{",
"// strip off a trailing slash if present",
"if",
"(",
"framework",
"[",
"framework",
".",
"length",
"-",
"1",
"]",
"==",
"'/'",
")",
"framework",
"=",
"framework",
".",
"slice",
"(",
"0",
",",
"framework",
".",
"length",
"-",
"1",
")",
";",
"// already absolute, return as-is",
"if",
"(",
"~",
"framework",
".",
"indexOf",
"(",
"'/'",
")",
")",
"return",
"framework",
";",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"PATH",
".",
"length",
",",
"rtn",
"=",
"null",
";",
"for",
"(",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"rtn",
"=",
"join",
"(",
"PATH",
"[",
"i",
"]",
",",
"framework",
"+",
"SUFFIX",
")",
";",
"if",
"(",
"exists",
"(",
"rtn",
")",
")",
"return",
"rtn",
";",
"}",
"throw",
"new",
"Error",
"(",
"'Could not resolve framework: '",
"+",
"framework",
")",
";",
"}"
] |
Accepts a single framework name and resolves it into an absolute path
to the base directory of the framework.
In most cases, you will not need to use this function in your code.
$.resolve('Foundation')
// '/System/Library/Frameworks/Foundation.framework'
@param {String} framework The framework name or path to resolve.
@return {String} The resolved framework path.
|
[
"Accepts",
"a",
"single",
"framework",
"name",
"and",
"resolves",
"it",
"into",
"an",
"absolute",
"path",
"to",
"the",
"base",
"directory",
"of",
"the",
"framework",
"."
] |
e4710fb8b73d3a2860de1e959e335a6de3e2191c
|
https://github.com/TooTallNate/NodObjC/blob/e4710fb8b73d3a2860de1e959e335a6de3e2191c/lib/import.js#L250-L262
|
15,798
|
TooTallNate/NodObjC
|
lib/types.js
|
getStruct
|
function getStruct (type) {
// First check if a regular name was passed in
var rtn = structCache[type];
if (rtn) return rtn;
// If the struct type name has already been created, return that one
var name = parseStructName(type);
rtn = structCache[name];
if (rtn) return rtn;
if(knownStructs[name]) type = knownStructs[name];
// Next parse the type structure
var parsed = parseStruct(type);
// Otherwise we need to create a new Struct constructor
var props = [];
parsed.props.forEach(function (prop) {
props.push([ map(prop[1]), prop[0] ])
});
var z;
try { z = Struct(props); } catch(e) { }
return structCache[parsed.name] = z;
}
|
javascript
|
function getStruct (type) {
// First check if a regular name was passed in
var rtn = structCache[type];
if (rtn) return rtn;
// If the struct type name has already been created, return that one
var name = parseStructName(type);
rtn = structCache[name];
if (rtn) return rtn;
if(knownStructs[name]) type = knownStructs[name];
// Next parse the type structure
var parsed = parseStruct(type);
// Otherwise we need to create a new Struct constructor
var props = [];
parsed.props.forEach(function (prop) {
props.push([ map(prop[1]), prop[0] ])
});
var z;
try { z = Struct(props); } catch(e) { }
return structCache[parsed.name] = z;
}
|
[
"function",
"getStruct",
"(",
"type",
")",
"{",
"// First check if a regular name was passed in",
"var",
"rtn",
"=",
"structCache",
"[",
"type",
"]",
";",
"if",
"(",
"rtn",
")",
"return",
"rtn",
";",
"// If the struct type name has already been created, return that one",
"var",
"name",
"=",
"parseStructName",
"(",
"type",
")",
";",
"rtn",
"=",
"structCache",
"[",
"name",
"]",
";",
"if",
"(",
"rtn",
")",
"return",
"rtn",
";",
"if",
"(",
"knownStructs",
"[",
"name",
"]",
")",
"type",
"=",
"knownStructs",
"[",
"name",
"]",
";",
"// Next parse the type structure",
"var",
"parsed",
"=",
"parseStruct",
"(",
"type",
")",
";",
"// Otherwise we need to create a new Struct constructor",
"var",
"props",
"=",
"[",
"]",
";",
"parsed",
".",
"props",
".",
"forEach",
"(",
"function",
"(",
"prop",
")",
"{",
"props",
".",
"push",
"(",
"[",
"map",
"(",
"prop",
"[",
"1",
"]",
")",
",",
"prop",
"[",
"0",
"]",
"]",
")",
"}",
")",
";",
"var",
"z",
";",
"try",
"{",
"z",
"=",
"Struct",
"(",
"props",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"return",
"structCache",
"[",
"parsed",
".",
"name",
"]",
"=",
"z",
";",
"}"
] |
Returns the struct constructor function for the given struct name or type.
{CGPoint="x"d"y"d}
@api private
|
[
"Returns",
"the",
"struct",
"constructor",
"function",
"for",
"the",
"given",
"struct",
"name",
"or",
"type",
"."
] |
e4710fb8b73d3a2860de1e959e335a6de3e2191c
|
https://github.com/TooTallNate/NodObjC/blob/e4710fb8b73d3a2860de1e959e335a6de3e2191c/lib/types.js#L49-L72
|
15,799
|
TooTallNate/NodObjC
|
lib/types.js
|
parseStructName
|
function parseStructName (struct) {
var s = struct.substring(1, struct.length-1)
, equalIndex = s.indexOf('=')
if (~equalIndex)
s = s.substring(0, equalIndex)
return s
}
|
javascript
|
function parseStructName (struct) {
var s = struct.substring(1, struct.length-1)
, equalIndex = s.indexOf('=')
if (~equalIndex)
s = s.substring(0, equalIndex)
return s
}
|
[
"function",
"parseStructName",
"(",
"struct",
")",
"{",
"var",
"s",
"=",
"struct",
".",
"substring",
"(",
"1",
",",
"struct",
".",
"length",
"-",
"1",
")",
",",
"equalIndex",
"=",
"s",
".",
"indexOf",
"(",
"'='",
")",
"if",
"(",
"~",
"equalIndex",
")",
"s",
"=",
"s",
".",
"substring",
"(",
"0",
",",
"equalIndex",
")",
"return",
"s",
"}"
] |
Extracts only the name of the given struct type encoding string.
@api private
|
[
"Extracts",
"only",
"the",
"name",
"of",
"the",
"given",
"struct",
"type",
"encoding",
"string",
"."
] |
e4710fb8b73d3a2860de1e959e335a6de3e2191c
|
https://github.com/TooTallNate/NodObjC/blob/e4710fb8b73d3a2860de1e959e335a6de3e2191c/lib/types.js#L80-L86
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.