_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q31500 | train | function (data) {
var validData = _.deepMapValues(this.config, function (value, propertyPath) {
return _.deepGet(data, propertyPath.join('.'));
});
_.merge(this.config, validData);
} | javascript | {
"resource": ""
} | |
q31501 | train | function () {
var self = this;
$http.get(settingsApi)
.success(function (data) {
self.set(data);
$timeout(function () {
self.loaded = true;
});
})
.error(function () {
self.reset();
$timeout(function () {
self.loaded = true;
});
});
} | javascript | {
"resource": ""
} | |
q31502 | train | function () {
var searchField = this.config.searchField;
return searchField &&
Object.keys(searchField).every(function (key) {
return searchField[key] === false;
});
} | javascript | {
"resource": ""
} | |
q31503 | train | function (module) {
if (module === SDK_PACKAGE_NAME) {
var packageFile = path.join(__dirname, '..', 'package.json')
if (fs.existsSync(packageFile)) {
var packageInfo = JSON.parse(fs.readFileSync(packageFile))
if (packageInfo.name === SDK_PACKAGE_NAME) {
// Use local library sources if the example is being run from source.
module = '..'
}
}
} else if (fs.existsSync(path.join(__dirname, '..',
'node_modules', SDK_PACKAGE_NAME, 'node_modules', module))) {
// Prior to NPM version 3, an 'npm install' would nest a package's
// dependencies under a 'node_modules' subdirectory. Adjust the module
// name to reflect the nested location if found there.
module = '../node_modules/' + SDK_PACKAGE_NAME + '/node_modules/' + module
}
return require(module)
} | javascript | {
"resource": ""
} | |
q31504 | train | function (params) {
var self = this;
this.parseParams(params);
if (!this.loaded) {
this.fetchApi(api).success(function (data) {
packages = data;
self.loaded = true;
self.search();
});
}
else {
this.search();
}
} | javascript | {
"resource": ""
} | |
q31505 | train | function (params) {
this.query = params.q !== undefined ? String(params.q) : defaultParams.query;
this.page = params.p !== undefined ? parseInt(params.p, 10) : defaultParams.page;
switch (params.s) {
case 'name':
case 'owner':
case 'stars':
case 'updated':
this.sorting = params.s;
break;
default:
this.sorting = defaultParams.sorting;
}
switch (params.o) {
case 'asc':
case 'desc':
this.order = params.o;
break;
default:
this.order = defaultParams.order;
}
} | javascript | {
"resource": ""
} | |
q31506 | train | function (url) {
var self = this;
this.searching = true;
this.loadingError = false;
return $http.get(url)
.success(function (res) {
self.searching = false;
return res.data;
})
.error(function () {
self.searching = false;
self.loadingError = true;
return false;
});
} | javascript | {
"resource": ""
} | |
q31507 | train | function (items) {
if (!config.ignoreDeprecatedPackages) {
return items;
}
var list = _.filter(items, function (item) {
// Ignore packages
if (ignore.indexOf(item.name) !== -1) {
return false;
}
// Limit to whitelisted packages
if (whitelist[item.website] && item.name !== whitelist[item.website]) {
return false;
}
return true;
});
return list;
} | javascript | {
"resource": ""
} | |
q31508 | train | function (items, query, fields, exact) {
var self = this;
var isTarget = function (fieldName) {
return fields.indexOf(fieldName) !== -1;
};
if (query === '') {
return items;
}
fields = fields || ['name', 'owner', 'description', 'keyword'];
return _.filter(items, function (item) {
if ((isTarget('name') && self.matchedInString(query, item.name, exact)) ||
(isTarget('owner') && self.matchedInString(query, item.owner, exact)) ||
(isTarget('description') && self.matchedInString(query, item.description, exact)) ||
(isTarget('keyword') && self.matchedInArray(query, item.keywords, exact))) {
return true;
}
return false;
});
} | javascript | {
"resource": ""
} | |
q31509 | train | function (query, string, exact) {
if (typeof string !== 'string' || string === '') {
return false;
}
if (exact) {
return string.toLowerCase() === query.toLowerCase();
}
return string.toLowerCase().indexOf(query.toLowerCase()) !== -1;
} | javascript | {
"resource": ""
} | |
q31510 | train | function (query, array, exact) {
if (!_.isArray(array) || array.length === 0) {
return false;
}
return array.some(function (string) {
if (exact) {
return query.toLowerCase() === string.toLowerCase();
}
return string.toLowerCase().indexOf(query.toLowerCase()) !== -1;
});
} | javascript | {
"resource": ""
} | |
q31511 | train | function (items, query) {
if (!config.exactMatch || !config.searchField.name) {
return items;
}
var list = items;
var match = _.findIndex(list, function (item) {
return query.toLowerCase() === item.name.toLowerCase();
});
if (match !== -1) {
list.splice(0, 0, list.splice(match, 1)[0]);
}
return list;
} | javascript | {
"resource": ""
} | |
q31512 | processMessage | train | function processMessage(message) {
var recipients = Object.keys(message.recipient_status).filter(function(userId) {
return hook.receipts.reportForStatus.indexOf(message.recipient_status[userId]) !== -1;
});
if (recipients.length) {
var identities = [message.sender.user_id].concat(recipients);
var identityHash = {};
if (!hook.receipts.identities) {
createJob(message, recipients, {});
} else {
if (!(hook.receipts.identities instanceof Function)) {
hook.receipts.identities = getUserFromIdentities;
}
var getUser = hook.receipts.identities;
var count = 0;
identities.forEach(function(userId) {
getUser(userId, function(err, data) {
identityHash[userId] = data;
count++;
if (count === identities.length) createJob(message, recipients, identityHash);
})
});
}
}
} | javascript | {
"resource": ""
} |
q31513 | train | function() {
var args = Array.prototype.slice.call(arguments, 0),
org = args.shift();
return kwargs.apply(org, args);
} | javascript | {
"resource": ""
} | |
q31514 | DocsRouter | train | function DocsRouter(docs, options) {
debug('create docs router');
options = options || {};
this.docs = docs;
this.prefix = options.prefix || '/';
} | javascript | {
"resource": ""
} |
q31515 | train | function(path, handler) {
var node = trie.define(path)[0];
if (typeof handler !== 'function') {
throw new Error('invalid handler');
}
node.handler = handler;
} | javascript | {
"resource": ""
} | |
q31516 | verifyWebhook | train | function verifyWebhook(hookDef, webhook) {
logger(hookDef.name + ': Webhook already registered: ' + webhook.id + ': ' + webhook.status);
if (webhook.status !== 'active') {
logger(hookDef.name + ': Enabling webhook');
webhooksClient.enable(webhook.id);
}
} | javascript | {
"resource": ""
} |
q31517 | createRequest | train | function createRequest(url, req, { method, query } = {}) {
const request = {
url,
method: method || 'GET',
query: query || {},
};
return new Proxy(req, {
set: (target, name, value, receiver) => {
request[name] = value;
return true;
},
get: (target, name) => {
if (name in request) return request[name];
switch (name) {
// TODO:
case 'next':
case 'params':
case 'baseUrl':
case 'originalUrl':
case '_parsedUrl':
return undefined;
default:
return target[name];
}
},
});
} | javascript | {
"resource": ""
} |
q31518 | addSubscription | train | function addSubscription (client, topic, messageType,
callback, subscribeToTopic) {
if (typeof (subscribeToTopic) === 'undefined') { subscribeToTopic = true }
if (callback !== explicitSubscriptionCallback) {
client._callbackManager.addCallback(messageType, topic, callback)
}
if (subscribeToTopic && topic) {
var topicMessageTypes = client._subscriptionsByMessageType[topic]
// Only subscribe for the topic with the broker if no prior
// subscription has been established
if (!topicMessageTypes) {
if (client._mqttClient) {
client._mqttClient.subscribe(topic)
}
topicMessageTypes = {}
client._subscriptionsByMessageType[topic] = topicMessageTypes
}
var messageTypeCallbacks = topicMessageTypes[messageType]
if (messageTypeCallbacks) {
if (messageTypeCallbacks.indexOf(callback) < 0) {
messageTypeCallbacks.push(callback)
}
} else {
topicMessageTypes[messageType] = [callback]
}
}
} | javascript | {
"resource": ""
} |
q31519 | removeSubscription | train | function removeSubscription (client, topic, messageType, callback) {
if (callback !== explicitSubscriptionCallback) {
client._callbackManager.removeCallback(messageType, topic, callback)
}
if (topic) {
var subscriptionsByMessageType = client._subscriptionsByMessageType
var topicMessageTypes = subscriptionsByMessageType[topic]
if (topicMessageTypes) {
// If a call to the client's unsubscribe() function for the topic
// was made, unsubscribe regardless of any other active
// callback-based subscriptions
if (callback === explicitSubscriptionCallback) {
delete subscriptionsByMessageType[topic]
} else {
var messageTypeCallbacks = topicMessageTypes[messageType]
if (messageTypeCallbacks) {
var callbackPosition = messageTypeCallbacks.indexOf(callback)
if (callbackPosition > -1) {
if (messageTypeCallbacks.length > 1) {
// Remove the callback from the list of subscribers
// for the topic and associated message type
messageTypeCallbacks.splice(callbackPosition, 1)
} else {
if (Object.keys(topicMessageTypes).length > 1) {
// Remove the message type entry since no more callbacks
// are registered for the topic
delete topicMessageTypes[messageType]
} else {
// Remove the topic entry since no more message types are
// registered for it
delete subscriptionsByMessageType[topic]
}
}
}
}
}
if (client._mqttClient && !subscriptionsByMessageType[topic]) {
client._mqttClient.unsubscribe(topic)
}
}
}
} | javascript | {
"resource": ""
} |
q31520 | publish | train | function publish (client, topic, message) {
if (client._mqttClient) {
client._mqttClient.publish(topic, message)
} else {
throw new DxlError(
'Client not connected, unable to publish data to: ' + topic)
}
} | javascript | {
"resource": ""
} |
q31521 | compile | train | function compile(str, scope) {
if (!/[\(\){}]/.exec(str)) return literal(str);
var nodes = compile2(compile1(str), scope || {});
if (nodes.length === 0) return literal('');
return foldLiterals(nodes)
.reduce(function(c, e) {return binaryExpression('+', c, e)});
} | javascript | {
"resource": ""
} |
q31522 | foldLiterals | train | function foldLiterals(nodes) {
return nodes.reduce(function(c, e) {
if (e.type === 'Literal') {
var last = c[c.length - 1];
if (last && last.type === 'Literal') {
c.pop();
return c.concat(literal(last.value + e.value));
}
}
return c.concat(e);
}, [])
} | javascript | {
"resource": ""
} |
q31523 | compile1 | train | function compile1(str) {
if (!/[{}]/.exec(str)) return [literal(str)];
var depth = 0;
var nodes = [];
var m;
var buffer = '';
while ((m = /[{}]/.exec(str)) && str.length > 0) {
var chunk = str.substring(0, m.index);
switch (m[0]) {
case '{':
depth += 1;
if (depth === 1) {
buffer += chunk;
if (buffer.length > 0) nodes.push(literal(buffer));
buffer = '';
} else {
buffer += chunk + '{';
}
break;
case '}':
depth -= 1;
if (depth === 0) {
buffer += chunk;
if (buffer.length > 0) nodes.push(utils.parseExpression(buffer));
buffer = '';
} else {
buffer += chunk + '}';
}
break;
}
str = str.substring(m.index + 1);
}
if (str.length > 0)
nodes.push(literal(str));
return nodes;
} | javascript | {
"resource": ""
} |
q31524 | compile2 | train | function compile2(nodes, scope) {
var toks = flatMap(nodes, function(expr) {
return expr.type === 'Literal' ? tokenize2(expr.value) : expr;
});
return parse2(toks, scope);
} | javascript | {
"resource": ""
} |
q31525 | Framework | train | function Framework(spec, options) {
if (!(this instanceof Framework)) {
return new Framework(spec, options);
}
debug('create framework', spec, options);
spec = lodash.cloneDeep(spec || {});
options = lodash.cloneDeep(options || {});
spec = lodash.defaults(spec, {
swaggerVersion: '1.2',
apis: [],
});
options = lodash.defaults(options,
lodash.pick(spec, 'basePath')
);
delete spec.basePath;
schema.validateThrow('ResourceListing', spec);
schema.validateThrow(frameworkOptions, options);
if (spec.swaggerVersion !== '1.2') {
throw new Error('swaggerVersion not supported: ' + spec.swaggerVersion);
}
this.spec = spec;
this.options = options;
this.docs = new Docs(this);
this.router = new Router(this);
this.apis = {};
this.middleware = {};
} | javascript | {
"resource": ""
} |
q31526 | fieldAsOption | train | function fieldAsOption (field) {
var option = ''
for (var i = 0; i < field.length; i++) {
var c = field.charAt(i)
if (c < 'a') {
option = option + '-' + c.toLowerCase()
} else {
option += c
}
}
return option
} | javascript | {
"resource": ""
} |
q31527 | train | function (command) {
command.option('--opensslbin <file>',
'Location of the OpenSSL executable that the command uses. If not ' +
'specified, the command attempts to find an OpenSSL executable in ' +
'the current environment path.')
command.option('-s, --san [value]',
'add Subject Alternative Name(s) to the CSR', sanOption, [])
command.option('-P, --passphrase [pass]',
'Password for the private key. If specified with no value, prompts ' +
'for the value.')
Object.keys(pki.SUBJECT_ATTRIBUTES).forEach(function (key) {
var attributeInfo = pki.SUBJECT_ATTRIBUTES[key]
var optionName = fieldAsOption(key)
var optionValue = attributeInfo.optionValue || optionName.toLowerCase()
command.option('--' + fieldAsOption(key) + ' <' + optionValue + '>',
attributeInfo.description)
})
return command
} | javascript | {
"resource": ""
} | |
q31528 | train | function (command, responseCallback) {
if (command.passphrase === true) {
cliUtil.getValueFromPrompt('private key passphrase', true,
function (error, passphrase) {
if (error) {
provisionUtil.invokeCallback(error, responseCallback,
command.verbosity)
} else {
command.passphrase = passphrase
provisionUtil.invokeCallback(null, responseCallback)
}
}
)
} else {
provisionUtil.invokeCallback(null, responseCallback)
}
} | javascript | {
"resource": ""
} | |
q31529 | CFW_transitionCssDuration | train | function CFW_transitionCssDuration($node) {
var durationArray = [0]; // Set a min value -- otherwise get `Infinity`
$node.each(function() {
var durations = $node.css('transition-duration') || $node.css('-webkit-transition-duration') || $node.css('-moz-transition-duration') || $node.css('-ms-transition-duration') || $node.css('-o-transition-duration');
if (durations) {
var times = durations.split(',');
for (var i = times.length; i--;) { // Reverse loop should be faster
durationArray = durationArray.concat(parseFloat(times[i]));
}
}
});
var duration = Math.max.apply(Math, durationArray); // http://stackoverflow.com/a/1379560
duration = duration * 1000; // convert to milliseconds
return duration;
} | javascript | {
"resource": ""
} |
q31530 | nameTasks | train | function nameTasks(tasks) { //name tasks that are not already named, validation done elsewhere, ret map
var namesMap = tasks.reduce(function (map, t) {
if (t.name) { map[t.name] = t; }
return map;
}, {});
tasks.forEach(function (t, idx) {
if (!t.name) { //not already named
var name = fName(t.f);
if (!name) name = sprintf(DEFAULT_TASK_NAME, idx);
if (!name || namesMap[name]) {
name = sprintf('%s_%s', name, idx); //if empty or already used, postfix with _idx
}
t.name = name;
namesMap[name] = t;
}
});
return namesMap;
} | javascript | {
"resource": ""
} |
q31531 | validate | train | function validate(ast) {
if (!ast || !ast.inParams || !ast.tasks || !ast.outTask) return [AST_IS_OBJECT];
var errors = [];
errors = errors.concat(validateInParams(ast.inParams));
errors = errors.concat(validateTasks(ast.tasks));
errors = errors.concat(validateTaskNamesUnique(ast.tasks));
errors = errors.concat(taskUtil.validateOutTask(ast.outTask));
errors = errors.concat(validateLocals(ast.locals));
if (errors.length === 0) { // if no errors do additional validation
if (ast.outTask.type !== 'finalcbFirst') errors = errors.concat(validateOuputsUnique(ast.tasks));
errors = errors.concat(taskUtil.validateLocalFunctions(ast.inParams, ast.tasks, ast.locals));
errors = errors.concat(validateNoMissingNames(ast));
}
return errors;
} | javascript | {
"resource": ""
} |
q31532 | validateNoMissingNames | train | function validateNoMissingNames(ast) {
var errors = [];
var names = {};
if (ast.locals) {
names = Object.keys(ast.locals).reduce(function (accum, k) { // start with locals
accum[k] = true;
return accum;
}, names);
}
ast.inParams.reduce(function (accum, p) { // add input params
accum[p] = true;
return accum;
}, names);
ast.tasks.reduce(function (accum, t) { // add task outputs
return t.out.reduce(function (innerAccum, p) {
innerAccum[p] = true;
return innerAccum;
}, accum);
}, names);
// now we have all possible provided vars, check task inputs are accounted for
ast.tasks.reduce(function (accum, t) { // for all tasks
return t.a.reduce(function (innerAccum, p) { // for all in params, except property
if (!isLiteralOrProp(p) && !names[p]) innerAccum.push(sprintf(MISSING_INPUTS, p)); // add error if missing
return innerAccum;
}, accum);
}, errors);
// now check the final task outputs
ast.outTask.a.reduce(function (accum, p) { // for final task out params
if (!isLiteralOrProp(p) && !names[p]) accum.push(sprintf(MISSING_INPUTS, p)); // add error if missing
return accum;
}, errors);
return errors;
} | javascript | {
"resource": ""
} |
q31533 | filterOutTrailingCbParam | train | function filterOutTrailingCbParam(args) { // if has trailing cb | callback param, filter it out
if (args.length && args[args.length - 1].match(CB_NAMES_RE)) args.pop();
return args;
} | javascript | {
"resource": ""
} |
q31534 | CommonJsProject | train | function CommonJsProject(opts) {
this.roots = opts.roots;
this.textPluginPattern = opts.textPluginPattern || /^text!/;
opts.roots = this.roots.map(function(root) {
if (!copy.isDirectory(root)) {
throw new Error('Each commonjs root should be a directory: ' + root);
}
return ensureTrailingSlash(root);
}, this);
// A module is a Location that also has dep
this.currentModules = {};
this.ignoredModules = {};
} | javascript | {
"resource": ""
} |
q31535 | model | train | function model(obj) {
if (!obj) return;
if (obj.$ref) {
obj = obj.$ref;
} else if (obj.type === 'array' && obj.items && obj.items.$ref) {
obj = obj.items.$ref;
} else if (obj.type) {
obj = obj.type;
}
// ensure valid type
if (typeof obj !== 'string') return;
// ensure non-builtin type
if (constants.notModel.indexOf(obj) >= 0) return;
return obj;
} | javascript | {
"resource": ""
} |
q31536 | models | train | function models(spec) {
var ids = {};
if (!spec) return ids;
var add = function(obj) {
var type = model(obj);
if (type) ids[type] = true;
};
add(spec);
if (spec.properties) {
lodash.forOwn(spec.properties, function(p) { add(p); });
} else if (spec.parameters) {
spec.parameters.forEach(function(p) { add(p); });
}
return Object.keys(ids);
} | javascript | {
"resource": ""
} |
q31537 | getDescription | train | function getDescription(conversation) {
if (conversation.metadata.conversationersationName) {
return 'The Conversation ' + conversation.metadata.conversationersationName + ' has been deleted';
} else {
return 'The Conversation with ' +
conversation.participants.join(', ').replace(/(.*),(.*)/, '$1 and$2') +
' has been deleted';
}
} | javascript | {
"resource": ""
} |
q31538 | cliGenerateCsr | train | function cliGenerateCsr (configDir, commonOrCsrFileName, command) {
cliPki.processPrivateKeyPassphrase(command,
function (error) {
if (error) {
provisionUtil.invokeCallback(error, command.doneCallback,
command.verbosity)
} else {
pki.generatePrivateKeyAndCsr(configDir, commonOrCsrFileName, command)
}
}
)
} | javascript | {
"resource": ""
} |
q31539 | train | function(win) {
win = win || window;
this.lastFocus = new Date().getTime();
this._isFocused = true;
var _self = this;
// IE < 9 supports focusin and focusout events
if ("onfocusin" in win.document) {
event.addListener(win.document, "focusin", function(e) {
_self._setFocused(true);
});
event.addListener(win.document, "focusout", function(e) {
_self._setFocused(!!e.toElement);
});
}
else {
event.addListener(win, "blur", function(e) {
_self._setFocused(false);
});
event.addListener(win, "focus", function(e) {
_self._setFocused(true);
});
}
} | javascript | {
"resource": ""
} | |
q31540 | train | function(session) {
this.session = session;
this.doc = session.getDocument();
this.clearSelection();
this.selectionLead = this.doc.createAnchor(0, 0);
this.selectionAnchor = this.doc.createAnchor(0, 0);
var _self = this;
this.selectionLead.on("change", function(e) {
_self._emit("changeCursor");
if (!_self.$isEmpty)
_self._emit("changeSelection");
if (!_self.$preventUpdateDesiredColumnOnChange && e.old.column != e.value.column)
_self.$updateDesiredColumn();
});
this.selectionAnchor.on("change", function() {
if (!_self.$isEmpty)
_self._emit("changeSelection");
});
} | javascript | {
"resource": ""
} | |
q31541 | train | function(data, hashId, key, keyCode, e) {
// If we pressed any command key but no other key, then ignore the input.
// Otherwise "shift-" is added to the buffer, and later on "shift-g"
// which results in "shift-shift-g" which doesn't make sense.
if (hashId != 0 && (key == "" || key == String.fromCharCode(0))) {
return null;
}
// Compute the current value of the keyboard input buffer.
var r = this.$composeBuffer(data, hashId, key, e);
var buffer = r.bufferToUse;
var symbolicName = r.symbolicName;
var keyId = r.keyIdentifier;
r = this.$find(data, buffer, symbolicName, hashId, key, keyId);
if (DEBUG) {
console.log("KeyboardStateMapper#match", buffer, symbolicName, r);
}
return r;
} | javascript | {
"resource": ""
} | |
q31542 | findInsertLocation | train | function findInsertLocation(matches, score) {
const idx = binarySearch(matches, 0, matches.length, score);
if(idx < 0) {
// If the score was not found
return - idx - 1;
}
/*
* Something with the same score was found, make sure this item is
* added after all previous items with the same score.
*/
for(let i=idx+1; i<matches.length; i++) {
if(matches[i].score < score) return i;
}
return matches.length;
} | javascript | {
"resource": ""
} |
q31543 | handleValidation | train | function handleValidation(req, res, next) {
var payload = JSON.stringify(req.body);
var nodeVersion = Number(process.version.replace(/^v/, '').split(/\./)[0]);
var utf8safe = nodeVersion >= 6 ? payload : unescape(encodeURIComponent(payload));
var hash = crypto.createHmac('sha1', secret).update(utf8safe).digest('hex');
var signature = req.get('layer-webhook-signature');
if (hash === signature) next();
else {
loggerError('Computed HMAC Signature ' + hash + ' did not match signed header ' + signature + '. Returning Error. Config:', JSON.stringify(payload.config || {}));
res.sendStatus(403);
}
} | javascript | {
"resource": ""
} |
q31544 | train | function(node) {
var $activeTab = $(node);
var data = $($activeTab).data('cfw.tab');
if (data) {
var $activePane = data.$target;
var $paneContainer = $activePane.closest('.tab-content');
$paneContainer.find('[data-cfw="collapse"]').each(function() {
$(this).one('afterHide.cfw.collapse', function(e) {
e.stopPropagation();
e.preventDefault();
})
.CFW_Collapse('hide');
});
var $collapseItem = $activePane.find('[data-cfw="collapse"]');
$collapseItem.one('afterShow.cfw.collapse', function(e) {
e.stopPropagation();
e.preventDefault();
})
.CFW_Collapse('show');
}
} | javascript | {
"resource": ""
} | |
q31545 | train | function(node) {
var $activeCollapse = $(node);
var $paneParent = $activeCollapse.closest('.tab-pane');
var $paneID = $paneParent.attr('id');
var $paneContainer = $activeCollapse.closest('.tab-content');
$paneContainer.find('[data-cfw="collapse"]').each(function() {
var $this = $(this);
if ($this[0] === $activeCollapse[0]) {
return;
}
$this.CFW_Collapse('hide');
});
var $tabList = this.$element.find('[data-cfw="tab"]');
$tabList.each(function() {
var $this = $(this);
var selector = $this.attr('data-cfw-tab-target');
if (!selector) {
selector = $this.attr('href');
}
selector = selector.replace(/^#/, '');
if (selector == $paneID) {
$this.one('beforeShow.cfw.tab', function(e) {
e.stopPropagation();
})
.CFW_Tab('show');
}
});
} | javascript | {
"resource": ""
} | |
q31546 | resolveInitialData | train | function resolveInitialData(branches, extra) {
const errors = {};
const { promises, keys } = branches.reduce(
({ promises, keys }, b) => {
const getInitialData = (b.route ? b.route.component : b.component || b)
.getInitialData;
if (getInitialData) {
const { promise, key } = getInitialData(b, extra);
promises.push(promise.catch(e => (errors[key] = e)));
keys.push(key);
}
return {
promises,
keys,
};
},
{ promises: [], keys: [] }
);
return Promise.all(promises).then(data => ({
errors,
store: keys.reduce((s, k, i) => {
if (!(k in errors)) s[k] = data[i];
return s;
}, {}),
}));
} | javascript | {
"resource": ""
} |
q31547 | cliUpdateConfig | train | function cliUpdateConfig (configDir, hostname, command) {
cliUtil.fillEmptyServerCredentialsFromPrompt(command,
function (error) {
if (error) {
provisionUtil.invokeCallback(error, command.doneCallback,
command.verbosity)
} else {
updateConfig(configDir,
cliUtil.pullHostInfoFromCommand(hostname, command),
command)
}
}
)
} | javascript | {
"resource": ""
} |
q31548 | FrameworkRouter | train | function FrameworkRouter(framework) {
debug('create framework router');
this.framework = framework;
this.encoder = lodash.clone(http.encoder);
this.decoder = lodash.clone(http.decoder);
} | javascript | {
"resource": ""
} |
q31549 | train | function (message, component, header) {
if (typeof header === 'undefined') {
header = ''
}
if (component) {
if (header) {
header += ' '
}
header += '('
header += component
header += ')'
}
if (header) {
message = header + ': ' + message
}
return message
} | javascript | {
"resource": ""
} | |
q31550 | train | function (error, options) {
options = options || {}
var verbosity = options.verbosity || 0
var message = module.exports.getErrorMessage(
typeof error === 'object' ? error.message : error, options.component,
options.header)
if (typeof header === 'undefined') {
message = 'ERROR: ' + message
}
console.error(message)
if ((verbosity > 1) && (typeof error === 'object') && error.stack) {
console.log(error.stack)
}
} | javascript | {
"resource": ""
} | |
q31551 | train | function (file, data) {
module.exports.mkdirRecursive(path.dirname(file))
fs.writeFileSync(file, data, {mode: _0644})
} | javascript | {
"resource": ""
} | |
q31552 | train | function (error, callback, verbosity) {
if (callback) {
callback(error)
} else {
module.exports.logError(error, {verbosity: verbosity})
}
} | javascript | {
"resource": ""
} | |
q31553 | Firewall | train | function Firewall(name, path, authenticationHandler, successHandler, failureHandler) {
this.name = name;
this.path = utils.ensureRegexp(path);
this.rules = [];
// configure handlers
this.authenticationHandler = authenticationHandler || function (req, res, next) {
res.status(401);
return res.redirect('/login');
};
this.successHandler = successHandler;
this.failureHandler = failureHandler || function (req, res, next) {
return res.send(403, 'forbidden');
};
this.logger = debug;
this.strategies = {
role: strategy.role
};
} | javascript | {
"resource": ""
} |
q31554 | exists | train | function exists (path, callback) {
Fs.stat(path, function (err) {
callback(checkErr(err));
});
} | javascript | {
"resource": ""
} |
q31555 | existsSync | train | function existsSync(path) {
if ( path === null || path === undefined )
return false;
try {
Fs.statSync(path);
return true;
} catch (err) {
return checkErr(err);
}
} | javascript | {
"resource": ""
} |
q31556 | cleanup | train | function cleanup(err, compacted, activeCtx, options) {
if(err) {
return callback(err);
}
if(options.compactArrays && !options.graph && _isArray(compacted)) {
// simplify to a single item
if(compacted.length === 1) {
compacted = compacted[0];
}
// simplify to an empty object
else if(compacted.length === 0) {
compacted = {};
}
}
// always use array if graph option is on
else if(options.graph && _isObject(compacted)) {
compacted = [compacted];
}
// follow @context key
if(_isObject(ctx) && '@context' in ctx) {
ctx = ctx['@context'];
}
// build output context
ctx = _clone(ctx);
if(!_isArray(ctx)) {
ctx = [ctx];
}
// remove empty contexts
var tmp = ctx;
ctx = [];
for(var i = 0; i < tmp.length; ++i) {
if(!_isObject(tmp[i]) || Object.keys(tmp[i]).length > 0) {
ctx.push(tmp[i]);
}
}
// remove array if only one context
var hasContext = (ctx.length > 0);
if(ctx.length === 1) {
ctx = ctx[0];
}
// add context and/or @graph
if(_isArray(compacted)) {
// use '@graph' keyword
var kwgraph = _compactIri(activeCtx, '@graph');
var graph = compacted;
compacted = {};
if(hasContext) {
compacted['@context'] = ctx;
}
compacted[kwgraph] = graph;
}
else if(_isObject(compacted) && hasContext) {
// reorder keys so @context is first
var graph = compacted;
compacted = {'@context': ctx};
for(var key in graph) {
compacted[key] = graph[key];
}
}
callback(null, compacted, activeCtx);
} | javascript | {
"resource": ""
} |
q31557 | createDocumentLoader | train | function createDocumentLoader(promise) {
return function(url, callback) {
promise(url).then(
// success
function(remoteDocument) {
callback(null, remoteDocument);
},
// failure
callback
);
};
} | javascript | {
"resource": ""
} |
q31558 | train | function(msg, type, details) {
if(_nodejs) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
}
this.name = type || 'jsonld.Error';
this.message = msg || 'An unspecified JSON-LD error occurred.';
this.details = details || {};
} | javascript | {
"resource": ""
} | |
q31559 | hashBlankNodes | train | function hashBlankNodes(unnamed) {
var nextUnnamed = [];
var duplicates = {};
var unique = {};
// hash quads for each unnamed bnode
jsonld.setImmediate(function() {hashUnnamed(0);});
function hashUnnamed(i) {
if(i === unnamed.length) {
// done, name blank nodes
return nameBlankNodes(unique, duplicates, nextUnnamed);
}
// hash unnamed bnode
var bnode = unnamed[i];
var hash = _hashQuads(bnode, bnodes, namer);
// store hash as unique or a duplicate
if(hash in duplicates) {
duplicates[hash].push(bnode);
nextUnnamed.push(bnode);
}
else if(hash in unique) {
duplicates[hash] = [unique[hash], bnode];
nextUnnamed.push(unique[hash]);
nextUnnamed.push(bnode);
delete unique[hash];
}
else {
unique[hash] = bnode;
}
// hash next unnamed bnode
jsonld.setImmediate(function() {hashUnnamed(i + 1);});
}
} | javascript | {
"resource": ""
} |
q31560 | nameBlankNodes | train | function nameBlankNodes(unique, duplicates, unnamed) {
// name unique bnodes in sorted hash order
var named = false;
var hashes = Object.keys(unique).sort();
for(var i = 0; i < hashes.length; ++i) {
var bnode = unique[hashes[i]];
namer.getName(bnode);
named = true;
}
// continue to hash bnodes if a bnode was assigned a name
if(named) {
hashBlankNodes(unnamed);
}
// name the duplicate hash bnodes
else {
nameDuplicates(duplicates);
}
} | javascript | {
"resource": ""
} |
q31561 | nameDuplicates | train | function nameDuplicates(duplicates) {
// enumerate duplicate hash groups in sorted order
var hashes = Object.keys(duplicates).sort();
// process each group
processGroup(0);
function processGroup(i) {
if(i === hashes.length) {
// done, create JSON-LD array
return createArray();
}
// name each group member
var group = duplicates[hashes[i]];
var results = [];
nameGroupMember(group, 0);
function nameGroupMember(group, n) {
if(n === group.length) {
// name bnodes in hash order
results.sort(function(a, b) {
a = a.hash;
b = b.hash;
return (a < b) ? -1 : ((a > b) ? 1 : 0);
});
for(var r in results) {
// name all bnodes in path namer in key-entry order
// Note: key-order is preserved in javascript
for(var key in results[r].pathNamer.existing) {
namer.getName(key);
}
}
return processGroup(i + 1);
}
// skip already-named bnodes
var bnode = group[n];
if(namer.isNamed(bnode)) {
return nameGroupMember(group, n + 1);
}
// hash bnode paths
var pathNamer = new UniqueNamer('_:b');
pathNamer.getName(bnode);
_hashPaths(bnode, bnodes, namer, pathNamer,
function(err, result) {
if(err) {
return callback(err);
}
results.push(result);
nameGroupMember(group, n + 1);
});
}
}
} | javascript | {
"resource": ""
} |
q31562 | createArray | train | function createArray() {
var normalized = [];
/* Note: At this point all bnodes in the set of RDF quads have been
assigned canonical names, which have been stored in the 'namer' object.
Here each quad is updated by assigning each of its bnodes its new name
via the 'namer' object. */
// update bnode names in each quad and serialize
for(var i = 0; i < quads.length; ++i) {
var quad = quads[i];
var attrs = ['subject', 'object', 'name'];
for(var ai = 0; ai < attrs.length; ++ai) {
var attr = attrs[ai];
if(quad[attr] && quad[attr].type === 'blank node' &&
quad[attr].value.indexOf('_:c14n') !== 0) {
quad[attr].value = namer.getName(quad[attr].value);
}
}
normalized.push(_toNQuad(quad, quad.name ? quad.name.value : null));
}
// sort normalized output
normalized.sort();
// handle output format
if(options.format) {
if(options.format === 'application/nquads') {
return callback(null, normalized.join(''));
}
return callback(new JsonLdError(
'Unknown output format.',
'jsonld.UnknownFormat', {format: options.format}));
}
// output RDF dataset
callback(null, _parseNQuads(normalized.join('')));
} | javascript | {
"resource": ""
} |
q31563 | _expandLanguageMap | train | function _expandLanguageMap(languageMap) {
var rval = [];
var keys = Object.keys(languageMap).sort();
for(var ki = 0; ki < keys.length; ++ki) {
var key = keys[ki];
var val = languageMap[key];
if(!_isArray(val)) {
val = [val];
}
for(var vi = 0; vi < val.length; ++vi) {
var item = val[vi];
if(!_isString(item)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; language map values must be strings.',
'jsonld.SyntaxError', {languageMap: languageMap});
}
rval.push({
'@value': item,
'@language': key.toLowerCase()
});
}
}
return rval;
} | javascript | {
"resource": ""
} |
q31564 | _labelBlankNodes | train | function _labelBlankNodes(namer, element) {
if(_isArray(element)) {
for(var i = 0; i < element.length; ++i) {
element[i] = _labelBlankNodes(namer, element[i]);
}
}
else if(_isList(element)) {
element['@list'] = _labelBlankNodes(namer, element['@list']);
}
else if(_isObject(element)) {
// rename blank node
if(_isBlankNode(element)) {
element['@id'] = namer.getName(element['@id']);
}
// recursively apply to all keys
var keys = Object.keys(element).sort();
for(var ki = 0; ki < keys.length; ++ki) {
var key = keys[ki];
if(key !== '@id') {
element[key] = _labelBlankNodes(namer, element[key]);
}
}
}
return element;
} | javascript | {
"resource": ""
} |
q31565 | _expandValue | train | function _expandValue(activeCtx, activeProperty, value) {
// nothing to expand
if(value === null) {
return null;
}
// special-case expand @id and @type (skips '@id' expansion)
var expandedProperty = _expandIri(activeCtx, activeProperty, {vocab: true});
if(expandedProperty === '@id') {
return _expandIri(activeCtx, value, {base: true});
}
else if(expandedProperty === '@type') {
return _expandIri(activeCtx, value, {vocab: true, base: true});
}
// get type definition from context
var type = jsonld.getContextValue(activeCtx, activeProperty, '@type');
// do @id expansion (automatic for @graph)
if(type === '@id' || (expandedProperty === '@graph' && _isString(value))) {
return {'@id': _expandIri(activeCtx, value, {base: true})};
}
// do @id expansion w/vocab
if(type === '@vocab') {
return {'@id': _expandIri(activeCtx, value, {vocab: true, base: true})};
}
// do not expand keyword values
if(_isKeyword(expandedProperty)) {
return value;
}
rval = {};
// other type
if(type !== null) {
rval['@type'] = type;
}
// check for language tagging for strings
else if(_isString(value)) {
var language = jsonld.getContextValue(
activeCtx, activeProperty, '@language');
if(language !== null) {
rval['@language'] = language;
}
}
rval['@value'] = value;
return rval;
} | javascript | {
"resource": ""
} |
q31566 | _graphToRDF | train | function _graphToRDF(graph, namer) {
var rval = [];
var ids = Object.keys(graph).sort();
for(var i = 0; i < ids.length; ++i) {
var id = ids[i];
var node = graph[id];
var properties = Object.keys(node).sort();
for(var pi = 0; pi < properties.length; ++pi) {
var property = properties[pi];
var items = node[property];
if(property === '@type') {
property = RDF_TYPE;
}
else if(_isKeyword(property)) {
continue;
}
for(var ii = 0; ii < items.length; ++ii) {
var item = items[ii];
// RDF subject
var subject = {};
subject.type = (id.indexOf('_:') === 0) ? 'blank node' : 'IRI';
subject.value = id;
// RDF predicate
var predicate = {};
predicate.type = (property.indexOf('_:') === 0) ? 'blank node' : 'IRI';
predicate.value = property;
// convert @list to triples
if(_isList(item)) {
_listToRDF(item['@list'], namer, subject, predicate, rval);
}
// convert value or node object to triple
else {
var object = _objectToRDF(item);
rval.push({subject: subject, predicate: predicate, object: object});
}
}
}
}
return rval;
} | javascript | {
"resource": ""
} |
q31567 | _objectToRDF | train | function _objectToRDF(item) {
var object = {};
// convert value object to RDF
if(_isValue(item)) {
object.type = 'literal';
var value = item['@value'];
var datatype = item['@type'] || null;
// convert to XSD datatypes as appropriate
if(_isBoolean(value)) {
object.value = value.toString();
object.datatype = datatype || XSD_BOOLEAN;
}
else if(_isDouble(value) || datatype === XSD_DOUBLE) {
// canonical double representation
object.value = value.toExponential(15).replace(/(\d)0*e\+?/, '$1E');
object.datatype = datatype || XSD_DOUBLE;
}
else if(_isNumber(value)) {
object.value = value.toFixed(0);
object.datatype = datatype || XSD_INTEGER;
}
else if('@language' in item) {
object.value = value;
object.datatype = datatype || RDF_LANGSTRING;
object.language = item['@language'];
}
else {
object.value = value;
object.datatype = datatype || XSD_STRING;
}
}
// convert string/node object to RDF
else {
var id = _isObject(item) ? item['@id'] : item;
object.type = (id.indexOf('_:') === 0) ? 'blank node' : 'IRI';
object.value = id;
}
return object;
} | javascript | {
"resource": ""
} |
q31568 | _RDFToObject | train | function _RDFToObject(o, useNativeTypes) {
// convert IRI/blank node object to JSON-LD
if(o.type === 'IRI' || o.type === 'blank node') {
return {'@id': o.value};
}
// convert literal to JSON-LD
var rval = {'@value': o.value};
// add language
if('language' in o) {
rval['@language'] = o.language;
}
// add datatype
else {
var type = o.datatype;
// use native types for certain xsd types
if(useNativeTypes) {
if(type === XSD_BOOLEAN) {
if(rval['@value'] === 'true') {
rval['@value'] = true;
}
else if(rval['@value'] === 'false') {
rval['@value'] = false;
}
}
else if(_isNumeric(rval['@value'])) {
if(type === XSD_INTEGER) {
var i = parseInt(rval['@value']);
if(i.toFixed(0) === rval['@value']) {
rval['@value'] = i;
}
}
else if(type === XSD_DOUBLE) {
rval['@value'] = parseFloat(rval['@value']);
}
}
// do not add native type
if([XSD_BOOLEAN, XSD_INTEGER, XSD_DOUBLE, XSD_STRING]
.indexOf(type) === -1) {
rval['@type'] = type;
}
}
else if(type !== XSD_STRING) {
rval['@type'] = type;
}
}
return rval;
} | javascript | {
"resource": ""
} |
q31569 | _compareRDFTriples | train | function _compareRDFTriples(t1, t2) {
var attrs = ['subject', 'predicate', 'object'];
for(var i = 0; i < attrs.length; ++i) {
var attr = attrs[i];
if(t1[attr].type !== t2[attr].type || t1[attr].value !== t2[attr].value) {
return false;
}
}
if(t1.object.language !== t2.object.language) {
return false;
}
if(t1.object.datatype !== t2.object.datatype) {
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q31570 | _hashQuads | train | function _hashQuads(id, bnodes, namer) {
// return cached hash
if('hash' in bnodes[id]) {
return bnodes[id].hash;
}
// serialize all of bnode's quads
var quads = bnodes[id].quads;
var nquads = [];
for(var i = 0; i < quads.length; ++i) {
nquads.push(_toNQuad(
quads[i], quads[i].name ? quads[i].name.value : null, id));
}
// sort serialized quads
nquads.sort();
// return hashed quads
var hash = bnodes[id].hash = sha1.hash(nquads);
return hash;
} | javascript | {
"resource": ""
} |
q31571 | nextPermutation | train | function nextPermutation(skipped) {
if(!skipped && (chosenPath === null || path < chosenPath)) {
chosenPath = path;
chosenNamer = pathNamerCopy;
}
// do next permutation
if(permutator.hasNext()) {
jsonld.setImmediate(function() {permutate();});
}
else {
// digest chosen path and update namer
md.update(chosenPath);
pathNamer = chosenNamer;
// hash the next group
hashGroup(i + 1);
}
} | javascript | {
"resource": ""
} |
q31572 | _getFrameFlag | train | function _getFrameFlag(frame, options, name) {
var flag = '@' + name;
return (flag in frame) ? frame[flag][0] : options[name];
} | javascript | {
"resource": ""
} |
q31573 | _validateFrame | train | function _validateFrame(state, frame) {
if(!_isArray(frame) || frame.length !== 1 || !_isObject(frame[0])) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a JSON-LD frame must be a single object.',
'jsonld.SyntaxError', {frame: frame});
}
} | javascript | {
"resource": ""
} |
q31574 | _filterSubjects | train | function _filterSubjects(state, subjects, frame) {
// filter subjects in @id order
var rval = {};
for(var i = 0; i < subjects.length; ++i) {
var id = subjects[i];
var subject = state.subjects[id];
if(_filterSubject(subject, frame)) {
rval[id] = subject;
}
}
return rval;
} | javascript | {
"resource": ""
} |
q31575 | _filterSubject | train | function _filterSubject(subject, frame) {
// check @type (object value means 'any' type, fall through to ducktyping)
if('@type' in frame &&
!(frame['@type'].length === 1 && _isObject(frame['@type'][0]))) {
var types = frame['@type'];
for(var i = 0; i < types.length; ++i) {
// any matching @type is a match
if(jsonld.hasValue(subject, '@type', types[i])) {
return true;
}
}
return false;
}
// check ducktype
for(var key in frame) {
// only not a duck if @id or non-keyword isn't in subject
if((key === '@id' || !_isKeyword(key)) && !(key in subject)) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
q31576 | _embedValues | train | function _embedValues(state, subject, property, output) {
// embed subject properties in output
var objects = subject[property];
for(var i = 0; i < objects.length; ++i) {
var o = objects[i];
// recurse into @list
if(_isList(o)) {
var list = {'@list': []};
_addFrameOutput(state, output, property, list);
return _embedValues(state, o, '@list', list['@list']);
}
// handle subject reference
if(_isSubjectReference(o)) {
var id = o['@id'];
// embed full subject if isn't already embedded
if(!(id in state.embeds)) {
// add embed
var embed = {parent: output, property: property};
state.embeds[id] = embed;
// recurse into subject
o = {};
var s = state.subjects[id];
for(var prop in s) {
// copy keywords
if(_isKeyword(prop)) {
o[prop] = _clone(s[prop]);
continue;
}
_embedValues(state, s, prop, o);
}
}
_addFrameOutput(state, output, property, o);
}
// copy non-subject value
else {
_addFrameOutput(state, output, property, _clone(o));
}
}
} | javascript | {
"resource": ""
} |
q31577 | _removeEmbed | train | function _removeEmbed(state, id) {
// get existing embed
var embeds = state.embeds;
var embed = embeds[id];
var parent = embed.parent;
var property = embed.property;
// create reference to replace embed
var subject = {'@id': id};
// remove existing embed
if(_isArray(parent)) {
// replace subject with reference
for(var i = 0; i < parent.length; ++i) {
if(jsonld.compareValues(parent[i], subject)) {
parent[i] = subject;
break;
}
}
}
else {
// replace subject with reference
var useArray = _isArray(parent[property]);
jsonld.removeValue(parent, property, subject, {propertyIsArray: useArray});
jsonld.addValue(parent, property, subject, {propertyIsArray: useArray});
}
// recursively remove dependent dangling embeds
var removeDependents = function(id) {
// get embed keys as a separate array to enable deleting keys in map
var ids = Object.keys(embeds);
for(var i = 0; i < ids.length; ++i) {
var next = ids[i];
if(next in embeds && _isObject(embeds[next].parent) &&
embeds[next].parent['@id'] === id) {
delete embeds[next];
removeDependents(next);
}
}
};
removeDependents(id);
} | javascript | {
"resource": ""
} |
q31578 | train | function(id) {
// get embed keys as a separate array to enable deleting keys in map
var ids = Object.keys(embeds);
for(var i = 0; i < ids.length; ++i) {
var next = ids[i];
if(next in embeds && _isObject(embeds[next].parent) &&
embeds[next].parent['@id'] === id) {
delete embeds[next];
removeDependents(next);
}
}
} | javascript | {
"resource": ""
} | |
q31579 | _addFrameOutput | train | function _addFrameOutput(state, parent, property, output) {
if(_isObject(parent)) {
jsonld.addValue(parent, property, output, {propertyIsArray: true});
}
else {
parent.push(output);
}
} | javascript | {
"resource": ""
} |
q31580 | _selectTerm | train | function _selectTerm(
activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue) {
if(typeOrLanguageValue === null) {
typeOrLanguageValue = '@null';
}
// preferences for the value of @type or @language
var prefs = [];
// determine prefs for @id based on whether or not value compacts to a term
if((typeOrLanguageValue === '@id' || typeOrLanguageValue === '@reverse') &&
_isSubjectReference(value)) {
// prefer @reverse first
if(typeOrLanguageValue === '@reverse') {
prefs.push('@reverse');
}
// try to compact value to a term
var term = _compactIri(activeCtx, value['@id'], null, {vocab: true});
if(term in activeCtx.mappings &&
activeCtx.mappings[term] &&
activeCtx.mappings[term]['@id'] === value['@id']) {
// prefer @vocab
prefs.push.apply(prefs, ['@vocab', '@id']);
}
else {
// prefer @id
prefs.push.apply(prefs, ['@id', '@vocab']);
}
}
else {
prefs.push(typeOrLanguageValue);
}
prefs.push('@none');
var containerMap = activeCtx.inverse[iri];
for(var ci = 0; ci < containers.length; ++ci) {
// if container not available in the map, continue
var container = containers[ci];
if(!(container in containerMap)) {
continue;
}
var typeOrLanguageValueMap = containerMap[container][typeOrLanguage];
for(var pi = 0; pi < prefs.length; ++pi) {
// if type/language option not available in the map, continue
var pref = prefs[pi];
if(!(pref in typeOrLanguageValueMap)) {
continue;
}
// select term
return typeOrLanguageValueMap[pref];
}
}
return null;
} | javascript | {
"resource": ""
} |
q31581 | _expandIri | train | function _expandIri(activeCtx, value, relativeTo, localCtx, defined) {
// already expanded
if(value === null || _isKeyword(value)) {
return value;
}
// define term dependency if not defined
if(localCtx && value in localCtx && defined[value] !== true) {
_createTermDefinition(activeCtx, localCtx, value, defined);
}
relativeTo = relativeTo || {};
if(relativeTo.vocab) {
var mapping = activeCtx.mappings[value];
// value is explicitly ignored with a null mapping
if(mapping === null) {
return null;
}
if(mapping) {
// value is a term
return mapping['@id'];
}
}
// split value into prefix:suffix
var colon = value.indexOf(':');
if(colon !== -1) {
var prefix = value.substr(0, colon);
var suffix = value.substr(colon + 1);
// do not expand blank nodes (prefix of '_') or already-absolute
// IRIs (suffix of '//')
if(prefix === '_' || suffix.indexOf('//') === 0) {
return value;
}
// prefix dependency not defined, define it
if(localCtx && prefix in localCtx) {
_createTermDefinition(activeCtx, localCtx, prefix, defined);
}
// use mapping if prefix is defined
var mapping = activeCtx.mappings[prefix];
if(mapping) {
return mapping['@id'] + suffix;
}
// already absolute IRI
return value;
}
// prepend vocab
if(relativeTo.vocab && '@vocab' in activeCtx) {
return activeCtx['@vocab'] + value;
}
// prepend base
var rval = value;
if(relativeTo.base) {
rval = _prependBase(activeCtx['@base'], rval);
}
if(localCtx) {
// value must now be an absolute IRI
if(!_isAbsoluteIri(rval)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a @context value does not expand to ' +
'an absolute IRI.',
'jsonld.SyntaxError', {context: localCtx, value: value});
}
}
return rval;
} | javascript | {
"resource": ""
} |
q31582 | _prependBase | train | function _prependBase(base, iri) {
// already an absolute IRI
if(iri.indexOf(':') !== -1) {
return iri;
}
// parse base if it is a string
if(_isString(base)) {
base = jsonld.url.parse(base || '');
}
// parse given IRI
var rel = jsonld.url.parse(iri);
// start hierarchical part
var hierPart = (base.protocol || '');
if(rel.authority) {
hierPart += '//' + rel.authority;
}
else if(base.href !== '') {
hierPart += '//' + base.authority;
}
// per RFC3986 normalize
var path;
// IRI represents an absolute path
if(rel.pathname.indexOf('/') === 0) {
path = rel.pathname;
}
else {
path = base.pathname;
// append relative path to the end of the last directory from base
if(rel.pathname !== '') {
path = path.substr(0, path.lastIndexOf('/') + 1);
if(path.length > 0 && path.substr(-1) !== '/') {
path += '/';
}
path += rel.pathname;
}
}
// remove slashes and dots in path
path = _removeDotSegments(path, hierPart !== '');
// add query and hash
if(rel.query) {
path += '?' + rel.query;
}
if(rel.hash) {
path += rel.hash;
}
var rval = hierPart + path;
if(rval === '') {
rval = './';
}
return rval;
} | javascript | {
"resource": ""
} |
q31583 | _removeBase | train | function _removeBase(base, iri) {
if(_isString(base)) {
base = jsonld.url.parse(base || '');
}
// establish base root
var root = '';
if(base.href !== '') {
root += (base.protocol || '') + '//' + base.authority;
}
// support network-path reference with empty base
else if(iri.indexOf('//')) {
root += '//';
}
// IRI not relative to base
if(iri.indexOf(root) !== 0) {
return iri;
}
// remove root from IRI and parse remainder
var rel = jsonld.url.parse(iri.substr(root.length));
// remove path segments that match
var baseSegments = base.normalizedPath.split('/');
var iriSegments = rel.normalizedPath.split('/');
while(baseSegments.length > 0 && iriSegments.length > 0) {
if(baseSegments[0] !== iriSegments[0]) {
break;
}
baseSegments.shift();
iriSegments.shift();
}
// use '../' for each non-matching base segment
var rval = '';
if(baseSegments.length > 0) {
// don't count the last segment if it isn't a path (doesn't end in '/')
// don't count empty first segment, it means base began with '/'
if(base.normalizedPath.substr(-1) !== '/' || baseSegments[0] === '') {
baseSegments.pop();
}
for(var i = 0; i < baseSegments.length; ++i) {
rval += '../';
}
}
// prepend remaining segments
rval += iriSegments.join('/');
// add query and hash
if(rel.query) {
rval += '?' + rel.query;
}
if(rel.hash) {
rval += rel.hash;
}
if(rval === '') {
rval = './';
}
return rval;
} | javascript | {
"resource": ""
} |
q31584 | _createInverseContext | train | function _createInverseContext() {
var activeCtx = this;
// lazily create inverse
if(activeCtx.inverse) {
return activeCtx.inverse;
}
var inverse = activeCtx.inverse = {};
// handle default language
var defaultLanguage = activeCtx['@language'] || '@none';
// create term selections for each mapping in the context, ordered by
// shortest and then lexicographically least
var mappings = activeCtx.mappings;
var terms = Object.keys(mappings).sort(_compareShortestLeast);
for(var i = 0; i < terms.length; ++i) {
var term = terms[i];
var mapping = mappings[term];
if(mapping === null) {
continue;
}
var container = mapping['@container'] || '@none';
// iterate over every IRI in the mapping
var ids = mapping['@id'];
if(!_isArray(ids)) {
ids = [ids];
}
for(var ii = 0; ii < ids.length; ++ii) {
var iri = ids[ii];
var entry = inverse[iri];
// initialize entry
if(!entry) {
inverse[iri] = entry = {};
}
// add new entry
if(!entry[container]) {
entry[container] = {
'@language': {},
'@type': {}
};
}
entry = entry[container];
// term is preferred for values using @reverse
if(mapping.reverse) {
_addPreferredTerm(mapping, term, entry['@type'], '@reverse');
}
// term is preferred for values using specific type
else if('@type' in mapping) {
_addPreferredTerm(mapping, term, entry['@type'], mapping['@type']);
}
// term is preferred for values using specific language
else if('@language' in mapping) {
var language = mapping['@language'] || '@null';
_addPreferredTerm(mapping, term, entry['@language'], language);
}
// term is preferred for values w/default language or no type and
// no language
else {
// add an entry for the default language
_addPreferredTerm(mapping, term, entry['@language'], defaultLanguage);
// add entries for no type and no language
_addPreferredTerm(mapping, term, entry['@type'], '@none');
_addPreferredTerm(mapping, term, entry['@language'], '@none');
}
}
}
return inverse;
} | javascript | {
"resource": ""
} |
q31585 | _addPreferredTerm | train | function _addPreferredTerm(mapping, term, entry, typeOrLanguageValue) {
if(!(typeOrLanguageValue in entry)) {
entry[typeOrLanguageValue] = term;
}
} | javascript | {
"resource": ""
} |
q31586 | _cloneActiveContext | train | function _cloneActiveContext() {
var child = {};
child['@base'] = this['@base'];
child.mappings = _clone(this.mappings);
child.clone = this.clone;
child.inverse = null;
child.getInverse = this.getInverse;
if('@language' in this) {
child['@language'] = this['@language'];
}
if('@vocab' in this) {
child['@vocab'] = this['@vocab'];
}
return child;
} | javascript | {
"resource": ""
} |
q31587 | _isSubject | train | function _isSubject(v) {
// Note: A value is a subject if all of these hold true:
// 1. It is an Object.
// 2. It is not a @value, @set, or @list.
// 3. It has more than 1 key OR any existing key is not @id.
var rval = false;
if(_isObject(v) &&
!(('@value' in v) || ('@set' in v) || ('@list' in v))) {
var keyCount = Object.keys(v).length;
rval = (keyCount > 1 || !('@id' in v));
}
return rval;
} | javascript | {
"resource": ""
} |
q31588 | _isBlankNode | train | function _isBlankNode(v) {
// Note: A value is a blank node if all of these hold true:
// 1. It is an Object.
// 2. If it has an @id key its value begins with '_:'.
// 3. It has no keys OR is not a @value, @set, or @list.
var rval = false;
if(_isObject(v)) {
if('@id' in v) {
rval = (v['@id'].indexOf('_:') === 0);
}
else {
rval = (Object.keys(v).length === 0 ||
!(('@value' in v) || ('@set' in v) || ('@list' in v)));
}
}
return rval;
} | javascript | {
"resource": ""
} |
q31589 | _parseNQuads | train | function _parseNQuads(input) {
// define partial regexes
var iri = '(?:<([^:]+:[^>]*)>)';
var bnode = '(_:(?:[A-Za-z][A-Za-z0-9]*))';
var plain = '"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"';
var datatype = '(?:\\^\\^' + iri + ')';
var language = '(?:@([a-z]+(?:-[a-z0-9]+)*))';
var literal = '(?:' + plain + '(?:' + datatype + '|' + language + ')?)';
var ws = '[ \\t]+';
var wso = '[ \\t]*';
var eoln = /(?:\r\n)|(?:\n)|(?:\r)/g;
var empty = new RegExp('^' + wso + '$');
// define quad part regexes
var subject = '(?:' + iri + '|' + bnode + ')' + ws;
var property = iri + ws;
var object = '(?:' + iri + '|' + bnode + '|' + literal + ')' + wso;
var graphName = '(?:\\.|(?:(?:' + iri + '|' + bnode + ')' + wso + '\\.))';
// full quad regex
var quad = new RegExp(
'^' + wso + subject + property + object + graphName + wso + '$');
// build RDF dataset
var dataset = {};
// split N-Quad input into lines
var lines = input.split(eoln);
var lineNumber = 0;
for(var li = 0; li < lines.length; ++li) {
var line = lines[li];
lineNumber++;
// skip empty lines
if(empty.test(line)) {
continue;
}
// parse quad
var match = line.match(quad);
if(match === null) {
throw new JsonLdError(
'Error while parsing N-Quads; invalid quad.',
'jsonld.ParseError', {line: lineNumber});
}
// create RDF triple
var triple = {};
// get subject
if(!_isUndefined(match[1])) {
triple.subject = {type: 'IRI', value: match[1]};
}
else {
triple.subject = {type: 'blank node', value: match[2]};
}
// get predicate
triple.predicate = {type: 'IRI', value: match[3]};
// get object
if(!_isUndefined(match[4])) {
triple.object = {type: 'IRI', value: match[4]};
}
else if(!_isUndefined(match[5])) {
triple.object = {type: 'blank node', value: match[5]};
}
else {
triple.object = {type: 'literal'};
if(!_isUndefined(match[7])) {
triple.object.datatype = match[7];
}
else if(!_isUndefined(match[8])) {
triple.object.datatype = RDF_LANGSTRING;
triple.object.language = match[8];
}
else {
triple.object.datatype = XSD_STRING;
}
var unescaped = match[6]
.replace(/\\"/g, '"')
.replace(/\\t/g, '\t')
.replace(/\\n/g, '\n')
.replace(/\\r/g, '\r')
.replace(/\\\\/g, '\\');
triple.object.value = unescaped;
}
// get graph name ('@default' is used for the default graph)
var name = '@default';
if(!_isUndefined(match[9])) {
name = match[9];
}
else if(!_isUndefined(match[10])) {
name = match[10];
}
// initialize graph in dataset
if(!(name in dataset)) {
dataset[name] = [triple];
}
// add triple if unique to its graph
else {
var unique = true;
var triples = dataset[name];
for(var ti = 0; unique && ti < triples.length; ++ti) {
if(_compareRDFTriples(triples[ti], triple)) {
unique = false;
}
}
if(unique) {
triples.push(triple);
}
}
}
return dataset;
} | javascript | {
"resource": ""
} |
q31590 | _toNQuads | train | function _toNQuads(dataset) {
var quads = [];
for(var graphName in dataset) {
var triples = dataset[graphName];
for(var ti = 0; ti < triples.length; ++ti) {
var triple = triples[ti];
if(graphName === '@default') {
graphName = null;
}
quads.push(_toNQuad(triple, graphName));
}
}
quads.sort();
return quads.join('');
} | javascript | {
"resource": ""
} |
q31591 | _parseRdfaApiData | train | function _parseRdfaApiData(data) {
var dataset = {};
dataset['@default'] = [];
var subjects = data.getSubjects();
for(var si = 0; si < subjects.length; ++si) {
var subject = subjects[si];
if(subject === null) {
continue;
}
// get all related triples
var triples = data.getSubjectTriples(subject);
if(triples === null) {
continue;
}
var predicates = triples.predicates;
for(var predicate in predicates) {
// iterate over objects
var objects = predicates[predicate].objects;
for(var oi = 0; oi < objects.length; ++oi) {
var object = objects[oi];
// create RDF triple
var triple = {};
// add subject
if(subject.indexOf('_:') === 0) {
triple.subject = {type: 'blank node', value: subject};
}
else {
triple.subject = {type: 'IRI', value: subject};
}
// add predicate
if(predicate.indexOf('_:') === 0) {
triple.predicate = {type: 'blank node', value: predicate};
}
else {
triple.predicate = {type: 'IRI', value: predicate};
}
// serialize XML literal
var value = object.value;
if(object.type === RDF_XML_LITERAL) {
// initialize XMLSerializer
if(!XMLSerializer) {
_defineXMLSerializer();
}
var serializer = new XMLSerializer();
value = '';
for(var x = 0; x < object.value.length; x++) {
if(object.value[x].nodeType === Node.ELEMENT_NODE) {
value += serializer.serializeToString(object.value[x]);
}
else if(object.value[x].nodeType === Node.TEXT_NODE) {
value += object.value[x].nodeValue;
}
}
}
// add object
triple.object = {};
// object is an IRI
if(object.type === RDF_OBJECT) {
if(object.value.indexOf('_:') === 0) {
triple.object.type = 'blank node';
}
else {
triple.object.type = 'IRI';
}
}
// literal
else {
triple.object.type = 'literal';
if(object.type === RDF_PLAIN_LITERAL) {
if(object.language) {
triple.object.datatype = RDF_LANGSTRING;
triple.object.language = object.language;
}
else {
triple.object.datatype = XSD_STRING;
}
}
else {
triple.object.datatype = object.type;
}
}
triple.object.value = value;
// add triple to dataset in default graph
dataset['@default'].push(triple);
}
}
}
return dataset;
} | javascript | {
"resource": ""
} |
q31592 | _parseAuthority | train | function _parseAuthority(parsed) {
// parse authority for unparsed relative network-path reference
if(parsed.href.indexOf(':') === -1 && parsed.href.indexOf('//') === 0 &&
!parsed.host) {
// must parse authority from pathname
parsed.pathname = parsed.pathname.substr(2);
var idx = parsed.pathname.indexOf('/');
if(idx === -1) {
parsed.authority = parsed.pathname;
parsed.pathname = '';
}
else {
parsed.authority = parsed.pathname.substr(0, idx);
parsed.pathname = parsed.pathname.substr(idx);
}
}
else {
// construct authority
parsed.authority = parsed.host || '';
if(parsed.auth) {
parsed.authority = parsed.auth + '@' + parsed.authority;
}
}
} | javascript | {
"resource": ""
} |
q31593 | _removeDotSegments | train | function _removeDotSegments(path, hasAuthority) {
var rval = '';
if(path.indexOf('/') === 0) {
rval = '/';
}
// RFC 3986 5.2.4 (reworked)
var input = path.split('/');
var output = [];
while(input.length > 0) {
if(input[0] === '.' || (input[0] === '' && input.length > 1)) {
input.shift();
continue;
}
if(input[0] === '..') {
input.shift();
if(hasAuthority ||
(output.length > 0 && output[output.length - 1] !== '..')) {
output.pop();
}
// leading relative URL '..'
else {
output.push('..');
}
continue;
}
output.push(input.shift());
}
return rval + output.join('/');
} | javascript | {
"resource": ""
} |
q31594 | scrollTo | train | function scrollTo({ container, element, key, options }) {
// if duration is ero then set it to very small so that we do not divide by zero
if (options.duration <= 0) options.duration = 0.1;
// width or height
const sizeKey = SIZE_KEYS[key];
// destination measurement
let to = Math.min(
element[`offset${key}`] + options[`offset${key}`],
(container[`scroll${sizeKey}`] - container[`offset${sizeKey}`])
);
// if destination is greater than avaialable space then limit to avaialable space
if (to > container[`scroll${sizeKey}`]) to = container[`scroll${sizeKey}`];
// if destination is less than zero then make it zero
if (to < 0) to = 0;
// amount that needs to be scrolled
const difference = to - container[`scroll${key}`];
// amount thats needs to be scrolled every tick
const perTick = difference / options.duration * options.tick;
// if we are already scrolled to that point then exit
if (perTick === 0) return;
// scroll the amount for one tick
const doScroll = () => {
setTimeout(() => {
// scroll container
container[`scroll${key}`] = container[`scroll${key}`] + perTick;
// if we have reached desired position then exit
if (
(container[`scroll${key}`] >= to && perTick > 0) ||
(container[`scroll${key}`] <= to && perTick < 0)
) return;
// else repeat after `TICK` interval
doScroll();
}, options.tick);
};
doScroll();
} | javascript | {
"resource": ""
} |
q31595 | train | function (request) {
// Extract information from request. The toString() call converts the
// payload from a binary Buffer into a string, decoded using UTF-8
// character encoding.
console.log('Service received request payload: ' +
request.payload.toString())
// Create the response message
var response = new dxl.Response(request)
// Populate the response payload
response.payload = 'pong'
// Send the response
client.sendResponse(response)
} | javascript | {
"resource": ""
} | |
q31596 | train | function (error, response) {
// Destroy the client - frees up resources so that the application
// stops running
client.destroy()
// Display the contents of an error, if one occurred
if (error) {
console.log('Request error: ' + error.message)
// The 'code' property, if set, typically has a string
// representation of the error code.
if (error.code) {
console.log('Request error code: ' + error.code)
// If no string representation is available for the error code
// but the error is a DXL 'RequestError', a numeric error
// code should be available in the
// 'dxlErrorResponse.errorCode' property.
} else if (error.dxlErrorResponse) {
console.log('Request error code: ' +
error.dxlErrorResponse.errorCode)
}
// No error occurred, so extract information from the response. The
// toString() call converts the payload from a binary Buffer into a
// string, decoded using UTF-8 character encoding.
} else {
console.log('Client received response payload: ' +
response.payload.toString())
}
} | javascript | {
"resource": ""
} | |
q31597 | train | function (prototype, properties) {
var object = Object.create(prototype);
Object.keys(properties).forEach(function (key) {
object[key] = properties[key];
});
return object;
} | javascript | {
"resource": ""
} | |
q31598 | train | function (descriptor) {
var result = {};
for (var key in descriptor) {
if (Object.prototype.hasOwnProperty.call(descriptor, key)) {
var keys = key.split(',');
for (var i = 0, len = keys.length; i < len; i += 1) {
var method = keys[i];
if (!ACCEPTABLE_METHOD_SET[method]) {
throw new Error("Unknown descriptor method " + method);
}
if (Object.prototype.hasOwnProperty.call(result, method)) {
throw new Error("Already specified descriptor method " + method);
}
result[method] = descriptor[key];
}
}
}
if (!result.options) {
result.options = createOptionsHandler(result);
}
return freeze(result);
} | javascript | {
"resource": ""
} | |
q31599 | train | function (route) {
if (route === "/") {
return "root";
}
if (route.indexOf("{") >= 0) {
throw new Error("Unable to guess route name for route " + route);
}
var result = route
.replace(SLASH_PREFIX_REGEX, "")
.replace(GUESS_ROUTE_NAME_UNEXPECTED_CHARACTER_REGEX, "")
.replace(PUNCTUATION_LETTER_REGEX, function (full, character) {
return character.toUpperCase();
});
if (!result) {
throw new Error("Unable to guess route name for route " + route);
}
return result;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.