_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q45200
|
train
|
function(options) {
this.debug = options.debug;
this.board = options.board;
this.connection = options.connection;
this.chip = new options.protocol({ quiet: true });
}
|
javascript
|
{
"resource": ""
}
|
|
q45201
|
boardLookupTable
|
train
|
function boardLookupTable() {
var byBoard = {};
for (var i = 0; i < boards.length; i++) {
var currentBoard = boards[i];
byBoard[currentBoard.name] = currentBoard;
var aliases = currentBoard.aliases;
if (Array.isArray(aliases)) {
for (var j = 0; j < aliases.length; j++) {
var currentAlias = aliases[j];
byBoard[currentAlias] = currentBoard;
}
}
}
return byBoard;
}
|
javascript
|
{
"resource": ""
}
|
q45202
|
querystringify
|
train
|
function querystringify(obj, prefix) {
prefix = prefix || '';
var pairs = []
, value
, key;
//
// Optionally prefix with a '?' if needed
//
if ('string' !== typeof prefix) prefix = '?';
for (key in obj) {
if (has.call(obj, key)) {
value = obj[key];
//
// Edge cases where we actually want to encode the value to an empty
// string instead of the stringified value.
//
if (!value && (value === null || value === undef || isNaN(value))) {
value = '';
}
key = encodeURIComponent(key);
value = encodeURIComponent(value);
//
// If we failed to encode the strings, we should bail out as we don't
// want to add invalid strings to the query.
//
if (key === null || value === null) continue;
pairs.push(key +'='+ value);
}
}
return pairs.length ? prefix + pairs.join('&') : '';
}
|
javascript
|
{
"resource": ""
}
|
q45203
|
train
|
function () {
var rand = '' + Math.random() * 1000 * new Date().getTime();
return rand.replace('.', '').split('').sort(function () {
return 0.5 - Math.random();
}).join('');
}
|
javascript
|
{
"resource": ""
}
|
|
q45204
|
train
|
function (prefix, obj) {
if (!obj.attr('id')) {
var generated_id;
do {
generated_id = prefix + '_' + randomNumber();
} while ($('#' + generated_id).length > 0);
obj.attr('id', generated_id);
}
return obj.attr('id');
}
|
javascript
|
{
"resource": ""
}
|
|
q45205
|
train
|
function (selector) {
try {
var jqElem = $(selector);
} catch (e) {
return null;
}
if (jqElem.length === 0) {
return null;
} else if (jqElem.is('input[type="checkbox"]')) {
return (jqElem.prop('checked') === true ? true : false);
} else if (jqElem.is('input[type="radio"]') && jqElem.attr('name') !== undefined) {
return $('input[name="' + jqElem.attr('name') + '"]:checked').val();
} else if (jqElem.prop('value') !== undefined) {
return jqElem.val();
} else {
return jqElem.html();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45206
|
train
|
function (selector, value, physical) {
try {
var jqElem = $(selector);
} catch (e) {
return;
}
if (jqElem.length === 0) {
return;
} else if (jqElem.is('input[type="checkbox"]')) {
if (value) {
jqElem.attr('checked', true);
} else {
jqElem.removeAttr('checked');
}
} else if (jqElem.prop('value') !== undefined) {
if (physical) {
jqElem.attr('value', value);
} else {
jqElem.val(value);
}
} else {
jqElem.html(value);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45207
|
train
|
function (elements, index, toReplace, replaceWith) {
var replaceAttrDataNode = function (node) {
var jqNode = $(node);
if (typeof node === 'object' && 'attributes' in node) {
$.each(node.attributes, function (i, attrib) {
if ($.type(attrib.value) === 'string') {
jqNode.attr(attrib.name.replace(toReplace, replaceWith), attrib.value.replace(toReplace, replaceWith));
}
});
}
if (jqNode.length > 0) {
$.each(jqNode.data(), function (name, value) {
if ($.type(value) === 'string') {
jqNode.data(name.replace(toReplace, replaceWith), value.replace(toReplace, replaceWith));
}
});
}
};
var element = elements.eq(index);
replaceAttrDataNode(element[0]);
element.find('*').each(function () {
replaceAttrDataNode(this);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q45208
|
train
|
function (collection, settings, html, oldIndex, newIndex, oldKey, newKey) {
var toReplace = new RegExp(pregQuote(settings.name_prefix + '[' + oldKey + ']'), 'g');
var replaceWith = settings.name_prefix + '[' + newKey + ']';
html = html.replace(toReplace, replaceWith);
toReplace = new RegExp(pregQuote(collection.attr('id') + '_' + oldIndex), 'g');
replaceWith = collection.attr('id') + '_' + newIndex;
html = html.replace(toReplace, replaceWith);
return html;
}
|
javascript
|
{
"resource": ""
}
|
|
q45209
|
train
|
function (element) {
$(element).find(':input').each(function (index, inputObj) {
putFieldValue(inputObj, getFieldValue(inputObj), true);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q45210
|
train
|
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
|
{
"resource": ""
}
|
|
q45211
|
train
|
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
|
{
"resource": ""
}
|
|
q45212
|
train
|
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
|
{
"resource": ""
}
|
|
q45213
|
dependenciesForElectron
|
train
|
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
|
{
"resource": ""
}
|
q45214
|
logMessage
|
train
|
function logMessage (message) {
if (!process.send) {
console.log(message)
} else {
process.send(message)
}
}
|
javascript
|
{
"resource": ""
}
|
q45215
|
createTeam
|
train
|
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
|
{
"resource": ""
}
|
q45216
|
listTeamPolicies
|
train
|
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
|
{
"resource": ""
}
|
q45217
|
readTeam
|
train
|
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
|
{
"resource": ""
}
|
q45218
|
updateTeam
|
train
|
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
|
{
"resource": ""
}
|
q45219
|
deleteTeam
|
train
|
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
|
{
"resource": ""
}
|
q45220
|
addTeamPolicies
|
train
|
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
|
{
"resource": ""
}
|
q45221
|
replaceTeamPolicies
|
train
|
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
|
{
"resource": ""
}
|
q45222
|
deleteTeamPolicies
|
train
|
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
|
{
"resource": ""
}
|
q45223
|
deleteTeamPolicy
|
train
|
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
|
{
"resource": ""
}
|
q45224
|
readTeamUsers
|
train
|
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
|
{
"resource": ""
}
|
q45225
|
addUsersToTeam
|
train
|
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
|
{
"resource": ""
}
|
q45226
|
deleteTeamMembers
|
train
|
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
|
{
"resource": ""
}
|
q45227
|
search
|
train
|
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
|
{
"resource": ""
}
|
q45228
|
readUser
|
train
|
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
|
{
"resource": ""
}
|
q45229
|
updateUser
|
train
|
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
|
{
"resource": ""
}
|
q45230
|
replaceUserPolicies
|
train
|
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
|
{
"resource": ""
}
|
q45231
|
deleteUserPolicy
|
train
|
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
|
{
"resource": ""
}
|
q45232
|
insertUser
|
train
|
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
|
{
"resource": ""
}
|
q45233
|
listUserTeams
|
train
|
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
|
{
"resource": ""
}
|
q45234
|
batchAuthorization
|
train
|
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
|
{
"resource": ""
}
|
q45235
|
listAuthorizationsOnResources
|
train
|
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
|
{
"resource": ""
}
|
q45236
|
loadUsers
|
train
|
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
|
{
"resource": ""
}
|
q45237
|
readPolicyVariables
|
train
|
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
|
{
"resource": ""
}
|
q45238
|
listPolicyInstances
|
train
|
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
|
{
"resource": ""
}
|
q45239
|
createPolicy
|
train
|
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
|
{
"resource": ""
}
|
q45240
|
updatePolicy
|
train
|
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
|
{
"resource": ""
}
|
q45241
|
deletePolicy
|
train
|
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
|
{
"resource": ""
}
|
q45242
|
listAllUserPolicies
|
train
|
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
|
{
"resource": ""
}
|
q45243
|
readSharedPolicy
|
train
|
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
|
{
"resource": ""
}
|
q45244
|
createSharedPolicy
|
train
|
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
|
{
"resource": ""
}
|
q45245
|
insertOrgAdminUser
|
train
|
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
|
{
"resource": ""
}
|
q45246
|
list
|
train
|
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
|
{
"resource": ""
}
|
q45247
|
readById
|
train
|
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
|
{
"resource": ""
}
|
q45248
|
create
|
train
|
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
|
{
"resource": ""
}
|
q45249
|
replaceOrganizationPolicies
|
train
|
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
|
{
"resource": ""
}
|
q45250
|
deleteOrganizationAttachedPolicies
|
train
|
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
|
{
"resource": ""
}
|
q45251
|
deleteOrganizationAttachedPolicy
|
train
|
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
|
{
"resource": ""
}
|
q45252
|
listOrganizationPolicies
|
train
|
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
|
{
"resource": ""
}
|
q45253
|
set
|
train
|
function set(key, value) {
if (ns && ns.active) {
return ns.set(key, value);
}
}
|
javascript
|
{
"resource": ""
}
|
q45254
|
train
|
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
|
{
"resource": ""
}
|
|
q45255
|
train
|
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
|
{
"resource": ""
}
|
|
q45256
|
train
|
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
|
{
"resource": ""
}
|
|
q45257
|
train
|
function(url) {
if (!isSupportHistoryAPI && ('' + url).indexOf('#') === 0) {
changeState(null, url);
} else {
windowLocation.assign(url);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45258
|
train
|
function(url) {
if (!isSupportHistoryAPI && ('' + url).indexOf('#') === 0) {
changeState(null, url, true);
} else {
windowLocation.replace(url);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45259
|
parseURL
|
train
|
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
|
{
"resource": ""
}
|
q45260
|
maybeBindToGlobal
|
train
|
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
|
{
"resource": ""
}
|
q45261
|
storageInitialize
|
train
|
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
|
{
"resource": ""
}
|
q45262
|
prepareDescriptorsForObject
|
train
|
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
|
{
"resource": ""
}
|
q45263
|
firePopState
|
train
|
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
|
{
"resource": ""
}
|
q45264
|
changeState
|
train
|
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
|
{
"resource": ""
}
|
q45265
|
onHashChange
|
train
|
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
|
{
"resource": ""
}
|
q45266
|
onLoad
|
train
|
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
|
{
"resource": ""
}
|
q45267
|
onAnchorClick
|
train
|
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
|
{
"resource": ""
}
|
q45268
|
scrollToAnchorId
|
train
|
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
|
{
"resource": ""
}
|
q45269
|
get_assets
|
train
|
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
|
{
"resource": ""
}
|
q45270
|
wait_for
|
train
|
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
|
{
"resource": ""
}
|
q45271
|
generate_log_message
|
train
|
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
|
{
"resource": ""
}
|
q45272
|
alias
|
train
|
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
|
{
"resource": ""
}
|
q45273
|
compileDefinition
|
train
|
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
|
{
"resource": ""
}
|
q45274
|
handleText
|
train
|
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
|
{
"resource": ""
}
|
q45275
|
train
|
function(a, b) {
for (var i = 0, node; node = b[i]; i++)
a.push(node);
return a;
}
|
javascript
|
{
"resource": ""
}
|
|
q45276
|
train
|
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
|
{
"resource": ""
}
|
|
q45277
|
drawGraph
|
train
|
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
|
{
"resource": ""
}
|
q45278
|
train
|
function(name, graphType){
Flotr.graphTypes[name] = graphType;
Flotr.defaultOptions[name] = graphType.options || {};
Flotr.defaultOptions.defaultType = Flotr.defaultOptions.defaultType || name;
}
|
javascript
|
{
"resource": ""
}
|
|
q45279
|
train
|
function(name, plugin){
Flotr.plugins[name] = plugin;
Flotr.defaultOptions[name] = plugin.options || {};
}
|
javascript
|
{
"resource": ""
}
|
|
q45280
|
train
|
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
|
{
"resource": ""
}
|
|
q45281
|
train
|
function(x){
return Math.pow(10, Math.floor(Math.log(x) / Math.LN10));
}
|
javascript
|
{
"resource": ""
}
|
|
q45282
|
train
|
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
|
{
"resource": ""
}
|
|
q45283
|
train
|
function(element){
element = getEl(element);
return {
height : element.offsetHeight,
width : element.offsetWidth };
}
|
javascript
|
{
"resource": ""
}
|
|
q45284
|
train
|
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
|
{
"resource": ""
}
|
|
q45285
|
train
|
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
|
{
"resource": ""
}
|
|
q45286
|
train
|
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
|
{
"resource": ""
}
|
|
q45287
|
train
|
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
|
{
"resource": ""
}
|
|
q45288
|
train
|
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
|
{
"resource": ""
}
|
|
q45289
|
getCanvas
|
train
|
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
|
{
"resource": ""
}
|
q45290
|
train
|
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
|
{
"resource": ""
}
|
|
q45291
|
train
|
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
|
{
"resource": ""
}
|
|
q45292
|
train
|
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
|
{
"resource": ""
}
|
|
q45293
|
train
|
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
|
{
"resource": ""
}
|
|
q45294
|
train
|
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
|
{
"resource": ""
}
|
|
q45295
|
train
|
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
|
{
"resource": ""
}
|
|
q45296
|
train
|
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
|
{
"resource": ""
}
|
|
q45297
|
train
|
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
|
{
"resource": ""
}
|
|
q45298
|
train
|
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
|
{
"resource": ""
}
|
|
q45299
|
train
|
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
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.