_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q14100
|
train
|
function (str) {
// here:xx:xxx??inline
var matches = /^<!--\s*here\:(.*?)\s*-->$/.exec(str.trim())
if (!matches || !matches[1]) return null
var expr = matches[1]
var parts = expr.split('??')
var query = querystring.parse(parts[1] || '')
var isInline = ('inline' in query) && query.inline != 'false'
var isWrapping = query.wrap !== 'false'
var namespace = ''
var reg
expr = parts[0]
parts = expr.split(':')
if (parts.length > 1) {
namespace = parts.shift()
}
reg = new RegExp(parts.pop())
return {
regexp: reg, // resource match validate regexp
namespace: namespace, // resource namespace match
inline: isInline, // whether inline resource or not
wrap: isWrapping
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14101
|
prettyLines
|
train
|
function prettyLines(lines, theme) {
if (!lines || !Array.isArray(lines)) throw new Error('Please supply an array of lines');
if (!theme) throw new Error('Please supply a theme');
function prettify(line) {
if (!line) return null;
return exports.line(line, theme);
}
return lines.map(prettify);
}
|
javascript
|
{
"resource": ""
}
|
q14102
|
train
|
function(fs, ourGlob, negatives, opt) {
// remove path relativity to make globs make sense
ourGlob = resolveGlob(fs, ourGlob, opt);
var ourOpt = extend({}, opt);
delete ourOpt.root;
// create globbing stuff
var globber = new glob.Glob(fs, ourGlob, ourOpt);
// extract base path from glob
var basePath = opt.base || glob2base(globber);
// create stream and map events from globber to it
var stream = through2.obj(negatives.length ? filterNegatives : undefined);
var found = false;
globber.on('error', stream.emit.bind(stream, 'error'));
globber.once('end', function(){
if (opt.allowEmpty !== true && !found && globIsSingular(globber)) {
stream.emit('error', new Error('File not found with singular glob'));
}
stream.end();
});
globber.on('match', function(filename) {
found = true;
stream.write({
cwd: opt.cwd,
base: basePath,
path: fs.resolve(opt.cwd, filename)
});
});
return stream;
function filterNegatives(filename, enc, cb) {
var matcha = isMatch.bind(null, filename);
if (negatives.every(matcha)) {
cb(null, filename); // pass
} else {
cb(); // ignore
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14103
|
train
|
function(fs, globs, opt) {
if (!opt) opt = {};
if (typeof opt.cwd !== 'string') opt.cwd = fs.resolve('.');
if (typeof opt.dot !== 'boolean') opt.dot = false;
if (typeof opt.silent !== 'boolean') opt.silent = true;
if (typeof opt.nonull !== 'boolean') opt.nonull = false;
if (typeof opt.cwdbase !== 'boolean') opt.cwdbase = false;
if (opt.cwdbase) opt.base = opt.cwd;
// only one glob no need to aggregate
if (!Array.isArray(globs)) globs = [globs];
var positives = [];
var negatives = [];
var ourOpt = extend({}, opt);
delete ourOpt.root;
globs.forEach(function(glob, index) {
if (typeof glob !== 'string' && !(glob instanceof RegExp)) {
throw new Error('Invalid glob at index ' + index);
}
var globArray = isNegative(glob) ? negatives : positives;
// create Minimatch instances for negative glob patterns
if (globArray === negatives && typeof glob === 'string') {
var ourGlob = resolveGlob(glob, opt);
glob = new Minimatch(ourGlob, ourOpt);
}
globArray.push({
index: index,
glob: glob
});
});
if (positives.length === 0) throw new Error('Missing positive glob');
// only one positive glob no need to aggregate
if (positives.length === 1) return streamFromPositive(positives[0]);
// create all individual streams
var streams = positives.map(streamFromPositive);
// then just pipe them to a single unique stream and return it
var aggregate = new Combine(streams);
var uniqueStream = unique('path');
var returnStream = aggregate.pipe(uniqueStream);
aggregate.on('error', function (err) {
returnStream.emit('error', err);
});
return returnStream;
function streamFromPositive(positive) {
var negativeGlobs = negatives.filter(indexGreaterThan(positive.index)).map(toGlob);
return gs.createStream(fs, positive.glob, negativeGlobs, opt);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14104
|
extensionsParser
|
train
|
function extensionsParser(str) {
// Convert the file extensions string to a list.
var list = str.split(',');
for (var i = 0; i < list.length; i++) {
// Make sure the file extension has the correct format: '.ext'
var ext = '.' + list[i].replace(/(^\s?\.?)|(\s?$)/g, '');
list[i] = ext.toLowerCase();
}
return list;
}
|
javascript
|
{
"resource": ""
}
|
q14105
|
listParser
|
train
|
function listParser(str) {
var list = str.split(',');
for (var i = 0; i < list.length; i++)
list[i] = list[i].replace(/(^\s?)|(\s?$)/g, '');
return list;
}
|
javascript
|
{
"resource": ""
}
|
q14106
|
kill
|
train
|
function kill(noMsg, signal) {
if (!instance)
return false;
try {
if (signal)
instance.kill(signal);
else
process.kill(instance.pid);
if ((noMsg || false) !== true)
logger.log('Killed', clc.green(script));
} catch (ex) {
// Process was already dead.
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q14107
|
restart
|
train
|
function restart() {
logger.log('Restarting', clc.green(script));
notifyWebSocket('restart');
if (!kill(true)) {
// The process wasn't running, start it now.
start(true);
} /*else {
// The process will restart when its 'exit' event is emitted.
}*/
}
|
javascript
|
{
"resource": ""
}
|
q14108
|
notifyWebSocket
|
train
|
function notifyWebSocket(message) {
if (!webSocketServer || !message)
return;
// Send the message to all connection in the WebSocket server.
for (var value in webSocketServer.conn) {
var connection = webSocketServer.conn[value];
if (connection)
connection.send(message)
}
}
|
javascript
|
{
"resource": ""
}
|
q14109
|
start
|
train
|
function start(noMsg) {
if ((noMsg || false) !== true)
logger.log('Starting', clc.green(script), 'with', clc.magenta(parser));
if (instance)
return;
// Spawn an instance of the parser that will run the script.
instance = spawn(parser, parserParams);
// Redirect the parser/script's output to the console.
instance.stdout.on('data', function (data) {
logger.scriptLog(scriptName, data.toString());
});
instance.stderr.on('data', function (data) {
logger.scriptLog(scriptName, data.toString(), true);
});
instance.stderr.on('data', function (data) {
if (/^execvp\(\)/.test(data.toString())) {
logger.error('Failed to restart child process.');
process.exit(0);
}
});
instance.on('exit', function (code, signal) {
instance = null;
if (signal == 'SIGUSR2') {
logger.error('Signal interuption');
start();
return;
}
logger.log(clc.green(script), 'exited with code', clc.yellow(code));
notifyWebSocket('exit');
if (keepAlive || (restartOnCleanExit && code == 0)) {
start();
return;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q14110
|
getLaunchIndex
|
train
|
function getLaunchIndex(PromiseArray){
return PromiseArray.map(r => {return (r.isRunning === false && r.isRejected === false && r.isResolved === false)}).indexOf(true)
}
|
javascript
|
{
"resource": ""
}
|
q14111
|
parseAnnotation
|
train
|
function parseAnnotation(entity) {
return {
annotations: entity.annotations ? {
bundleURL: entity.annotations['bundle-url'],
guiX: entity.annotations['gui-x'],
guiY: entity.annotations['gui-y']
} : undefined,
modelUUID: entity['model-uuid'],
tag: entity.tag
};
}
|
javascript
|
{
"resource": ""
}
|
q14112
|
parseAnnotations
|
train
|
function parseAnnotations(response) {
let entities = {};
Object.keys(response).forEach(key => {
entities[key] = parseAnnotation(response[key]);
});
return entities;
}
|
javascript
|
{
"resource": ""
}
|
q14113
|
parseApplication
|
train
|
function parseApplication(entity) {
return {
charmURL: entity['charm-url'],
// Config is arbitrary so leave the keys as defined.
config: entity.config,
// Constraints are arbitrary so leave the keys as defined.
constraints: entity.constraints,
exposed: entity.exposed,
life: entity.life,
minUnits: entity['min-units'],
modelUUID: entity['model-uuid'],
name: entity.name,
ownerTag: entity['owner-tag'],
status: entity.status ? {
current: entity.status.current,
message: entity.status.message,
since: entity.status.since,
version: entity.status.version
} : undefined,
subordinate: entity.subordinate,
workloadVersion: entity['workload-version']
};
}
|
javascript
|
{
"resource": ""
}
|
q14114
|
parseApplications
|
train
|
function parseApplications(response) {
let entities = {};
Object.keys(response).forEach(key => {
entities[key] = parseApplication(response[key]);
});
return entities;
}
|
javascript
|
{
"resource": ""
}
|
q14115
|
parseMachine
|
train
|
function parseMachine(entity) {
return {
addresses: entity.addresses ? entity.addresses.map(address => ({
value: address.value,
type: address.type,
scope: address.scope
})) : undefined,
agentStatus: entity['agent-status'] ? {
current: entity['agent-status'].current,
message: entity['agent-status'].message,
since: entity['agent-status'].since,
version: entity['agent-status'].version
} : undefined,
// Hardware characteristics are arbitrary so leave the keys as defined.
hardwareCharacteristics: entity['hardware-characteristics'],
hasVote: entity['has-vote'],
id: entity.id,
instanceID: entity['instance-id'],
instanceStatus: entity['instance-status'] ? {
current: entity['instance-status'].current,
message: entity['instance-status'].message,
since: entity['instance-status'].since,
version: entity['instance-status'].version
} : undefined,
jobs: entity.jobs,
life: entity.life,
modelUUID: entity['model-uuid'],
series: entity.series,
supportedContainers: entity['supported-containers'],
supportedContainersKnown: entity['supported-containers-known'],
wantsVote: entity['wants-vote']
};
}
|
javascript
|
{
"resource": ""
}
|
q14116
|
parseMachines
|
train
|
function parseMachines(response) {
let entities = {};
Object.keys(response).forEach(key => {
entities[key] = parseMachine(response[key]);
});
return entities;
}
|
javascript
|
{
"resource": ""
}
|
q14117
|
parseRelation
|
train
|
function parseRelation(entity) {
return {
endpoints: entity.endpoints ? entity.endpoints.map(endpoint => ({
applicationName: endpoint['application-name'],
relation: {
name: endpoint.relation.name,
role: endpoint.relation.role,
'interface': endpoint.relation.interface,
optional: endpoint.relation.optional,
limit: endpoint.relation.limit,
scope: endpoint.relation.scope
}
})) : undefined,
id: entity.id,
key: entity.key,
modelUUID: entity['model-uuid']
};
}
|
javascript
|
{
"resource": ""
}
|
q14118
|
parseRelations
|
train
|
function parseRelations(response) {
let entities = {};
Object.keys(response).forEach(key => {
entities[key] = parseRelation(response[key]);
});
return entities;
}
|
javascript
|
{
"resource": ""
}
|
q14119
|
parseRemoteApplication
|
train
|
function parseRemoteApplication(entity) {
return {
life: entity.life,
modelUUID: entity['model-uuid'],
name: entity.name,
offerURL: entity['offer-url'],
offerUUID: entity['offer-uuid'],
status: entity.status ? {
current: entity.status.current,
message: entity.status.message,
since: entity.status.since,
version: entity.status.version
} : undefined
};
}
|
javascript
|
{
"resource": ""
}
|
q14120
|
parseRemoteApplications
|
train
|
function parseRemoteApplications(response) {
let entities = {};
Object.keys(response).forEach(key => {
entities[key] = parseRemoteApplication(response[key]);
});
return entities;
}
|
javascript
|
{
"resource": ""
}
|
q14121
|
parseUnit
|
train
|
function parseUnit(entity) {
return {
agentStatus: entity['agent-status'] ? {
current: entity['agent-status'].current,
message: entity['agent-status'].message,
since: entity['agent-status'].since,
version: entity['agent-status'].version
} : undefined,
application: entity.application,
charmURL: entity['charm-url'],
machineID: entity['machine-id'],
modelUUID: entity['model-uuid'],
name: entity.name,
portRanges: entity['port-ranges'] ? entity['port-ranges'].map(range => ({
fromPort: range['from-port'],
toPort: range['to-port'],
protocol: range.protocol
})) : undefined,
ports: entity.ports ? entity.ports.map(port => ({
protocol: port.protocol,
number: port.number
})) : undefined,
privateAddress: entity['private-address'],
publicAddress: entity['public-address'],
series: entity.series,
subordinate: entity.subordinate,
workloadStatus: entity['workload-status'] ? {
current: entity['workload-status'].current,
message: entity['workload-status'].message,
since: entity['workload-status'].since,
version: entity['workload-status'].version
} : undefined
};
}
|
javascript
|
{
"resource": ""
}
|
q14122
|
parseUnits
|
train
|
function parseUnits(response) {
let entities = {};
Object.keys(response).forEach(key => {
entities[key] = parseUnit(response[key]);
});
return entities;
}
|
javascript
|
{
"resource": ""
}
|
q14123
|
parseMegaWatcher
|
train
|
function parseMegaWatcher(response) {
return {
annotations: parseAnnotations(response.annotations),
applications: parseApplications(response.applications),
machines: parseMachines(response.machines),
relations: parseRelations(response.relations),
remoteApplications: parseRemoteApplications(response['remote-applications']),
units: parseUnits(response.units)
};
}
|
javascript
|
{
"resource": ""
}
|
q14124
|
init
|
train
|
function init() {
var _user = arguments.length <= 0 || arguments[0] === undefined ? 'try' : arguments[0];
var _pw = arguments.length <= 1 || arguments[1] === undefined ? 'try' : arguments[1];
var _clientId = arguments.length <= 2 || arguments[2] === undefined ? 'mqttControlsClient' : arguments[2];
var _broker = arguments.length <= 3 || arguments[3] === undefined ? 'broker.shiftr.io' : arguments[3];
var _topics = arguments.length <= 4 || arguments[4] === undefined ? {
'subscribe': '/output/#',
'publish': '/input/' } : arguments[4];
user = _user;
pw = _pw;
clientId = _clientId;
broker = _broker;
topics = _topics;
url = '' + protocol + user + ':' + pw + '@' + broker;
console.log('mqtt controller is initialised');
}
|
javascript
|
{
"resource": ""
}
|
q14125
|
connect
|
train
|
function connect() {
console.log('Connecting client: ' + clientId + ' to url:"' + url + '"');
client = mqtt.connect(url, { 'clientId': clientId });
}
|
javascript
|
{
"resource": ""
}
|
q14126
|
disconnect
|
train
|
function disconnect() {
var force = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0];
var cb = arguments.length <= 1 || arguments[1] === undefined ? undefined : arguments[1];
console.log('Disconnecting client: ' + clientId);
stopPub = true;
client.end(force, cb);
}
|
javascript
|
{
"resource": ""
}
|
q14127
|
reconnect
|
train
|
function reconnect() {
client.end(false, function () {
console.log('Reconnecting client: ' + clientId);
client.connect(url, { 'clientId': clientId });
});
}
|
javascript
|
{
"resource": ""
}
|
q14128
|
subscribe
|
train
|
function subscribe() {
console.log('Subscribing client ' + clientId + ' to topic: ' + topics.subscribe);
client.subscribe(topics.subscribe);
isSubscribed = true;
}
|
javascript
|
{
"resource": ""
}
|
q14129
|
publish
|
train
|
function publish() {
console.log('Client ' + clientId + ' is publishing to topic ' + topics.publish);
// client.on('message',()=>{});
// this is just for testing purpouse
// maybe we dont need to stop and start publishing
var timer = setInterval(function () {
client.publish(topics.publish, 'ping');
if (stopPub === true) {
clearInterval(timer);
stopPub = false;
}
}, 1000);
}
|
javascript
|
{
"resource": ""
}
|
q14130
|
send
|
train
|
function send() {
var message = arguments.length <= 0 || arguments[0] === undefined ? 'hello mqtt-controls' : arguments[0];
var topic = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var t = undefined;
if (topic === null) {
t = topics.publish;
} else {
t = topic;
}
client.publish(t, message);
}
|
javascript
|
{
"resource": ""
}
|
q14131
|
consoleLogger
|
train
|
function consoleLogger(prefix, name, args, value) {
var result = value;
if (typeof value === 'string') {
result = '"' + result + '"';
}
name = prefix + name;
switch (args) {
case 'getter':
console.log(name, '=', result);
break;
case 'setter':
console.log(name, YIELDS, result);
break;
default: // method call
name += '(' + Array.prototype.slice.call(args).join(', ') + ')';
if (result === undefined) {
console.log(name);
} else {
console.log(name, YIELDS, result);
}
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q14132
|
train
|
function() {
var self = this;
if (self._refreshingCache) {
return;
}
self._refreshingCache = true;
Parse._objectEach(this.attributes, function(value, key) {
if (value instanceof Parse.Object) {
value._refreshCache();
} else if (_.isObject(value)) {
if (self._resetCacheForKey(key)) {
self.set(key, new Parse.Op.Set(value), { silent: true });
}
}
});
delete self._refreshingCache;
}
|
javascript
|
{
"resource": ""
}
|
|
q14133
|
train
|
function(attrs) {
// Check for changes of magic fields.
var model = this;
var specialFields = ["id", "objectId", "createdAt", "updatedAt"];
Parse._arrayEach(specialFields, function(attr) {
if (attrs[attr]) {
if (attr === "objectId") {
model.id = attrs[attr];
} else if ((attr === "createdAt" || attr === "updatedAt") &&
!_.isDate(attrs[attr])) {
model[attr] = Parse._parseDate(attrs[attr]);
} else {
model[attr] = attrs[attr];
}
delete attrs[attr];
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14134
|
train
|
function(serverData) {
// Copy server data
var tempServerData = {};
Parse._objectEach(serverData, function(value, key) {
tempServerData[key] = Parse._decode(key, value);
});
this._serverData = tempServerData;
// Refresh the attributes.
this._rebuildAllEstimatedData();
// Clear out any changes the user might have made previously.
this._refreshCache();
this._opSetQueue = [{}];
// Refresh the attributes again.
this._rebuildAllEstimatedData();
}
|
javascript
|
{
"resource": ""
}
|
|
q14135
|
train
|
function(other) {
if (!other) {
return;
}
// This does the inverse of _mergeMagicFields.
this.id = other.id;
this.createdAt = other.createdAt;
this.updatedAt = other.updatedAt;
this._copyServerData(other._serverData);
this._hasData = true;
}
|
javascript
|
{
"resource": ""
}
|
|
q14136
|
train
|
function(opSet, target) {
var self = this;
Parse._objectEach(opSet, function(change, key) {
target[key] = change._estimate(target[key], self, key);
if (target[key] === Parse.Op._UNSET) {
delete target[key];
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14137
|
train
|
function() {
var self = this;
var previousAttributes = _.clone(this.attributes);
this.attributes = _.clone(this._serverData);
Parse._arrayEach(this._opSetQueue, function(opSet) {
self._applyOpSet(opSet, self.attributes);
Parse._objectEach(opSet, function(op, key) {
self._resetCacheForKey(key);
});
});
// Trigger change events for anything that changed because of the fetch.
Parse._objectEach(previousAttributes, function(oldValue, key) {
if (self.attributes[key] !== oldValue) {
self.trigger('change:' + key, self, self.attributes[key], {});
}
});
Parse._objectEach(this.attributes, function(newValue, key) {
if (!_.has(previousAttributes, key)) {
self.trigger('change:' + key, self, newValue, {});
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14138
|
train
|
function(attr, amount) {
if (_.isUndefined(amount) || _.isNull(amount)) {
amount = 1;
}
return this.set(attr, new Parse.Op.Increment(amount));
}
|
javascript
|
{
"resource": ""
}
|
|
q14139
|
train
|
function() {
var json = _.clone(_.first(this._opSetQueue));
Parse._objectEach(json, function(op, key) {
json[key] = op.toJSON();
});
return json;
}
|
javascript
|
{
"resource": ""
}
|
|
q14140
|
$item
|
train
|
function $item(corq, item){
var typeName = item.type;
if (!corq.callbacks[typeName]){
throw "Item handler not found for items of type `" + typeName + "`";
}
$debug(corq, 'Corq: Calling handler for item `' + typeName + '`');
$debug(corq, item.data);
var _next = function(){
var freq = (corq.delay) ? corq.delayLength : corq.frequency;
setTimeout(function(){
$next(corq);
}, freq);
};
var _success = function(){
$debug(corq, 'Corq: Item processing SUCCESS `' + typeName + '` ');
$debug(corq, item.data);
$success(corq,item);
_next();
};
var _fail = function(){
$debug(corq, 'Corq: Item processing FAILURE `' + typeName + '` ');
$debug(corq, item.data);
$fail(corq, item);
_next();
};
try {
corq.callbacks[typeName](item.data, _success, _fail);
}catch(e){
$debug(corq, 'Corq: Error thrown by item processing function `' + typeName + '` ');
$debug(corq, item.data);
_fail();
throw e;
}
}
|
javascript
|
{
"resource": ""
}
|
q14141
|
getOrRegister
|
train
|
function getOrRegister(name, definition) {
if(name && !definition) {
return registry.get(name);
}
if(name && definition) {
return registry.register(name, definition);
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q14142
|
extractHeaderCookies
|
train
|
function extractHeaderCookies(headerSet) {
var cookie = headerSet.cookie;
var cookies = cookie ? cookie.split(';') : [];
delete headerSet.cookie;
return cookies;
}
|
javascript
|
{
"resource": ""
}
|
q14143
|
hyperImg
|
train
|
function hyperImg(store) {
this.compile = function(input) {
var path = input.split('.');
return {
path: input,
target: path[path.length - 1]
};
};
this.state = function(config, state) {
var res = store.get(config.path, state);
if (!res.completed) return false;
return state.set(config.target, res.value);
};
this.props = function(config, state, props) {
var image = state.get(config.target);
if (!image || !image.src) return props;
if (image.title) props = props.set('title', image.title);
return props.set('src', image.src);
};
}
|
javascript
|
{
"resource": ""
}
|
q14144
|
Registry
|
train
|
function Registry(opts) {
var defaultOptions = {
resourceCapabilitiesEndPoint:
'http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/reg/resource-caps'
}
var options = opts || {}
this.axiosConfig = {
method: 'get',
withCredentials: true,
crossDomain: true
}
this.resourceCapabilitiesURL = URL.parse(
options.resourceCapabilitiesEndPoint ||
defaultOptions.resourceCapabilitiesEndPoint
)
/**
* @param {URL} URI of the resource to obtain a service URL for.
* @param {{}} callback Function to callback. Optional, and defaults to a Promise.
* @returns {Promise}
*/
this.capabilityURLs = async function(callback) {
var aConf = Object.assign(
{ url: this.resourceCapabilitiesURL.href },
this.axiosConfig
)
var p = axios(aConf)
if (callback) {
p.then(callback)
} else {
return p
}
}
/**
* Obtain a service URL endpoint for the given resource and standard IDs
*
* @param {String|URL} resourceURI The Resource URI to lookup.
* @param {String|URL} The Standard ID URI to lookup.
* @param {boolean} secureFlag Whether to look for HTTPS access URLs. Requires client certificate.
* @param {{}} callback Optional function to callback.
* @returns {Promise}
*/
this.serviceURL = async function(
resourceURI,
standardURI,
secureFlag,
callback
) {
var aConf = Object.assign({}, this.axiosConfig)
return this.capabilityURLs().then(function(results) {
var properties = new PropertiesReader().read(results.data)
var capabilitiesURL = properties.get(resourceURI)
if (capabilitiesURL) {
aConf.url = capabilitiesURL
return axios(aConf).then(function(capResults) {
var doc = new DOMParser().parseFromString(capResults.data)
var capabilityFields = doc.documentElement.getElementsByTagName(
'capability'
)
for (var i = 0, cfl = capabilityFields.length; i < cfl; i++) {
var next = capabilityFields[i]
if (next.getAttribute('standardID') === standardURI) {
var interfaces = next.getElementsByTagName('interface')
for (var j = 0, il = interfaces.length; j < il; j++) {
var nextInterface = interfaces[j]
var securityMethods = nextInterface.getElementsByTagName(
'securityMethod'
)
if (
(secureFlag === false && securityMethods.length === 0) ||
(secureFlag === true &&
securityMethods.length > 0 &&
securityMethods[0].getAttribute('standardID') ===
'ivo://ivoa.net/sso#tls-with-certificate')
) {
// Actual URL value.
var accessURLElements = nextInterface.getElementsByTagName(
'accessURL'
)
return accessURLElements.length > 0
? accessURLElements[0].childNodes[0].nodeValue
: null
}
}
}
}
throw 'No service URL found'
})
} else {
throw `No service entry found for ${resourceURI}`
}
})
}
}
|
javascript
|
{
"resource": ""
}
|
q14145
|
getSourceCode
|
train
|
function getSourceCode(filepath) {
// The current folder
var dir = filepath.substring(0, filepath.lastIndexOf("/") + 1);
// Regex for file import
var fileRegex = /(?:["'])<!=\s*(.+)\b\s*!>(?:["'])?;?/;
// Regex for file extension
var fileExtRegex = /\..+$/;
// Read the file and check if anything should be imported into it; loop through them
return grunt.file.read(filepath).replace(new RegExp(fileRegex.source, "g"), function(match) {
// Log the number of imports we did
files += 1;
// Get the filename
var file = match.match(fileRegex)[1];
// Check if it has an extension
if(file.match(fileExtRegex) === null) {
file += options.defaultExtension; // Add it
}
var source = "";
// Loop through files
glob.sync(dir + file).forEach(function(filename) {
// Read file
var src = grunt.file.read(filename);
// Check if it has imports too
source += (function() {
return fileRegex.test(src) ? getSourceCode(filename) : src;
})() + options.separator; // Add separator
});
return source;
});
}
|
javascript
|
{
"resource": ""
}
|
q14146
|
train
|
function ( value, index, array ) {
if ( visited.hasOwnProperty(value) ) { return; }
visited[value] = true;
var deps = projectData.dependency[ value ];
if ( !deps ) { return; }
for ( var i = 0; i < deps.length; ++i ) {
var depAbsPath = projectData.id2File[ deps[i] ];
if ( !depAbsPath ) {
grunt.fail.fatal("Can't find file when merging, the file might exist but it's not a Sea.js module : [ " + deps[i] + " ]" );
}
this.push( depAbsPath );
reverse_dep_map[ depAbsPath ] = true;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14147
|
writeFileSyncLong
|
train
|
function writeFileSyncLong(filepath, contents) {
const options = arguments[2] || { flag: 'w', encoding: 'utf8' };
let lastPath;
const pathNormal = path.normalize(filepath);
if (path.isAbsolute(pathNormal)) {
lastPath = pathNormal;
} else {
lastPath = path.resolve(pathNormal);
}
if (fs.existsSync(lastPath)) {
fs.writeFileSync(lastPath, contents, options);
} else {
let prefixPath = [];
let dir = path.dirname(lastPath);
let splitPath = dir.split(path.sep)
if (splitPath[0] == "") {
splitPath.splice(0, 1, "/");// 将Unix 下的产生的root[""]替换为["/"];
}
for (let i = 0; i < splitPath.length; i++) {
prefixPath.push(splitPath[i]);
let prefixPaths = prefixPath.join("/");
if (fs.existsSync(prefixPaths) == false) {
fs.mkdirSync(prefixPaths);
}
}
fs.writeFileSync(lastPath, contents, options);
}
}
|
javascript
|
{
"resource": ""
}
|
q14148
|
isValid
|
train
|
function isValid (value, predicate, self) {
if (predicate instanceof Function) {
return predicate.call(self, value)
}
if (predicate instanceof RegExp) {
return predicate.test(value)
}
return true
}
|
javascript
|
{
"resource": ""
}
|
q14149
|
to12Hour
|
train
|
function to12Hour(hour) {
var meridiem = hour < 12 ? 'am' : 'pm';
return {
hour: ((hour + 11) % 12 + 1),
meridiem: meridiem,
meridian: meridiem
};
}
|
javascript
|
{
"resource": ""
}
|
q14150
|
to24Hour
|
train
|
function to24Hour(time) {
var meridiem = time.meridiem || time.meridian;
return (meridiem === 'am' ? 0 : 12) + (time.hour % 12);
}
|
javascript
|
{
"resource": ""
}
|
q14151
|
train
|
function(args) {
var lastArgWasNumber = false;
var numArgs = args.length;
var strs = [];
for (var ii = 0; ii < numArgs; ++ii) {
var arg = args[ii];
if (arg === undefined) {
strs.push('undefined');
} else if (typeof arg === 'number') {
if (lastArgWasNumber) {
strs.push(", ");
}
if (arg === Math.floor(arg)) {
strs.push(arg.toFixed(0));
} else {
strs.push(arg.toFixed(3));
}
lastArgWasNumber = true;
} else if (window.Float32Array && arg instanceof Float32Array) {
// TODO(gman): Make this handle other types of arrays.
strs.push(tdl.string.argsToString(arg));
} else {
strs.push(arg.toString());
lastArgWasNumber = false;
}
}
return strs.join("");
}
|
javascript
|
{
"resource": ""
}
|
|
q14152
|
shouldRun
|
train
|
function shouldRun(verb) {
// Add extra middleware to check if this method matches the requested HTTP verb
return function wareShouldRun(req, res, next) {
var shouldRun = (this.running && (req.method === verb || verb.toLowerCase() === 'all'));
// Call next in stack if it matches
if (shouldRun) next();
}
}
|
javascript
|
{
"resource": ""
}
|
q14153
|
sendReadyMessage
|
train
|
function sendReadyMessage() {
var data = {
namespace: MESSAGE_NAMESPACE,
id: 'iframe-ready'
};
parent.postMessage(JSON.stringify(data), '*');
}
|
javascript
|
{
"resource": ""
}
|
q14154
|
train
|
function (asset, result) {
var checksum;
result = Microloader.parseResult(result);
Microloader.remainingCachedAssets--;
if (!result.error) {
checksum = Microloader.checksum(result.content, asset.assetConfig.hash);
if (!checksum) {
_warn("Cached Asset '" + asset.assetConfig.path + "' has failed checksum. This asset will be uncached for future loading");
// Un cache this asset so it is loaded next time
asset.uncache();
}
//<debug>
_debug("Checksum for Cached Asset: " + asset.assetConfig.path + " is " + checksum);
//</debug>
Boot.registerContent(asset.assetConfig.path, asset.type, result.content);
asset.updateContent(result.content);
asset.cache();
} else {
_warn("There was an error pre-loading the asset '" + asset.assetConfig.path + "'. This asset will be uncached for future loading");
// Un cache this asset so it is loaded next time
asset.uncache();
}
if (Microloader.remainingCachedAssets === 0) {
Microloader.onCachedAssetsReady();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14155
|
train
|
function (content, delta) {
var output = [],
chunk, i, ln;
if (delta.length === 0) {
return content;
}
for (i = 0,ln = delta.length; i < ln; i++) {
chunk = delta[i];
if (typeof chunk === 'number') {
output.push(content.substring(chunk, chunk + delta[++i]));
}
else {
output.push(chunk);
}
}
return output.join('');
}
|
javascript
|
{
"resource": ""
}
|
|
q14156
|
train
|
function(doc, callback) {
audit([doc], function(err) {
if (err) {
return callback(err);
}
docsDb.saveDoc(doc, callback);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14157
|
train
|
function(docs, options, callback) {
if (!callback) {
callback = options;
options = {};
}
audit(docs, function(err) {
if (err) {
return callback(err);
}
options.docs = docs;
docsDb.bulkDocs(options, callback);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14158
|
train
|
function(doc, callback) {
audit([doc], 'delete', function(err) {
if (err) {
return callback(err);
}
docsDb.removeDoc(doc._id, doc._rev, callback);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14159
|
train
|
function(arr, i) {
var ret = arr.slice(0);
for (var j = 0; j < i; j++) {
ret = [ret[ret.length - 1]].concat(ret.slice(0, ret.length - 1));
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q14160
|
train
|
function(first, second) {
if (_equal(first, second)) {
return true;
}
for (var i = 1; i <= first.length; i++) {
if (_equal(first, _rotated(second, i))) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q14161
|
sqlParams
|
train
|
function sqlParams(sql, params)
{
var args = [];
var keys = sql.match(/@\w+/g);
var aKeys = sql.match(/\$\d+/g);
if (keys && aKeys)
throw new Error(
'Cannot use both array-style and object-style parametric values');
// Array-style (native)
if (aKeys) {
return { text: sql, values: params };
}
// No params
if (!keys) {
return { text: sql, values: [] };
}
var n = 1;
keys.forEach(function(key) {
key = key.substr(1);
var val = params[key];
if (val === undefined)
throw new Error('No value for @' + key + ' provided');
args.push(val);
sql = sql.replace('@' + key, '$' + n++);
});
return { text: sql, values: args };
}
|
javascript
|
{
"resource": ""
}
|
q14162
|
getWordToken
|
train
|
function getWordToken(str) {
var word = str.split(/\s/g)[0];
return {text: word, type: 'WORD', length: word.length};
}
|
javascript
|
{
"resource": ""
}
|
q14163
|
contains
|
train
|
function contains (obj1, obj2) {
const keys = Object.keys(obj1)
let result = keys.length > 0
let l = keys.length
while (l--) {
const key = keys[l]
result = result && match(obj1[key], obj2[key])
}
return result
}
|
javascript
|
{
"resource": ""
}
|
q14164
|
ravenwall
|
train
|
function ravenwall(options) {
if (options instanceof statware) return options
options = options || {}
// set defaults
options.sysstats = !(options.sysstats === false)
options.procstats = !(options.procstats === false)
options.memstats = !(options.memstats === false)
options.push = !(options.push === false)
options.pushApi = options.pushApi || "https://push.ravenwall.com"
options.pushSeconds = options.pushSeconds || 10
options.logHandle = options.logHandle || console.log
options.logSeconds = options.logSeconds || 60
options.initial = options.initial || {}
options.initial.ravenwall_agent = "nodejs_" + VERSION
if (options.id) id = options.id
function startPusher(id) {
if (!options.apiToken) throw new Error("Push API Requires an API token.")
var pusherSettings = {
url: options.pushApi + "/" + id,
headers: {
"Ravenwall-API-Token": options.apiToken,
},
timeout: (options.pushSeconds * 900) | 0
}
stats.pusher(pusherSettings, options.pushSeconds)
stats.push()
}
// Create series/api client
if (!options.noUpsert) {
var client = api(options.apiToken, options.apiUrl)
.upsertSeries({id: options.id, tags: options.tags}, function (err, res, body) {
if (err) {
console.log("Unable to upsert series to Ravenwall!", err)
return
}
if (res.statusCode != 201) {
console.log("Unable to upsert series to Ravenwall: server replied %s", res.statusCode)
return
}
var results = JSON.parse(body)
if (!options.id && options.push && !options.push) {
// This is a new series, so the pusher wasn't set up yet. Set it up now.
id = results.id
startPusher(results.id)
}
})
}
var stats = statware(options.initial)
if (options.sysstats) stats.registerHelper(statware.sysstats)
if (options.procstats) stats.registerHelper(statware.procstats)
if (options.memstats) stats.registerHelper(statware.memstats)
// Don't immediately start a pusher if no id specified (instead it will start after upsert)
if (options.push && options.id) {
startPusher(options.id)
}
if (options.page) {
stats.page(options.pagePort)
}
if (options.log) {
stats.logger(options.logHandle, options.logSeconds)
stats.log()
}
return stats
}
|
javascript
|
{
"resource": ""
}
|
q14165
|
normalize
|
train
|
function normalize(from, to) {
if (from && (isNaN(from) || from <= 0) || (to && (isNaN(to) || to <= 0))) {
throw new Error('invalid port range: required > 0');
}
if ((from && from > MAX) || (to && to > MAX)) {
throw new Error(f('invalid port range: required < %d', MAX));
}
if (to && to < from) {
throw new Error('invalid port range: required max >= min');
}
if (!from) {
from = min;
to = to || max;
} else {
to = to || from;
}
return {
from: from,
to: to
};
}
|
javascript
|
{
"resource": ""
}
|
q14166
|
cleanObject
|
train
|
function cleanObject(Object){
delete Object.resolve;
delete Object.reject;
delete Object.resolveResult;
delete Object.rejectResult;
delete Object.launchPromise;
delete Object.promiseFunc;
}
|
javascript
|
{
"resource": ""
}
|
q14167
|
updateExample
|
train
|
function updateExample(app, str) {
var cwd = app.options.dest || app.cwd;
return app.src('example.txt', {cwd: cwd})
.pipe(append(str))
.pipe(app.dest(cwd));
}
|
javascript
|
{
"resource": ""
}
|
q14168
|
erase
|
train
|
function erase(num) {
var n = typeof num === 'number' ? num : 1;
return through.obj(function(file, enc, next) {
var lines = file.contents.toString().trim().split('\n');
file.contents = new Buffer(lines.slice(0, -n).join('\n') + '\n');
next(null, file);
});
}
|
javascript
|
{
"resource": ""
}
|
q14169
|
update
|
train
|
function update (state) {
assert.ifError(inRenderingTransaction, 'infinite loop detected')
// request a redraw for next frame
if (currentState === null && !redrawScheduled) {
redrawScheduled = true
raf(function redraw () {
redrawScheduled = false
if (!currentState) return
inRenderingTransaction = true
var newTree = view(currentState)
const patches = vdom.diff(tree, newTree)
inRenderingTransaction = false
target = vdom.patch(target, patches)
tree = newTree
currentState = null
})
}
// update data for redraw
currentState = state
}
|
javascript
|
{
"resource": ""
}
|
q14170
|
Split
|
train
|
function Split (options) {
if (!(this instanceof Split)) {
return new Split(options)
}
if (options instanceof RegExp || typeof options === 'string') {
options = { matcher: options }
}
this.options = Object.assign({
matcher: /(\r?\n)/, // emits also newlines
encoding: 'utf8'
}, options)
this.buffer = ''
Transform.call(this, _omit(this.options, ['matcher']))
return this
}
|
javascript
|
{
"resource": ""
}
|
q14171
|
copyObject
|
train
|
function copyObject(obj) {
var ret = {}, name;
for (name in obj) {
if (obj.hasOwnProperty(name)) {
ret[name] = obj[name];
}
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q14172
|
setHost
|
train
|
function setHost(uri) {
if (uri.auth || uri.hostname || uri.port) {
uri.host = '';
if (uri.auth) uri.host += uri.auth + '@';
if (uri.hostname) uri.host += uri.hostname;
if (uri.port) uri.host += ':' + uri.port;
}
}
|
javascript
|
{
"resource": ""
}
|
q14173
|
setHref
|
train
|
function setHref(uri) {
uri.href = '';
if (uri.protocol) uri.href += uri.protocol + '//';
if (uri.host) uri.href += uri.host;
if (uri.path) uri.href += uri.path;
if (uri.hash) uri.href += uri.hash;
}
|
javascript
|
{
"resource": ""
}
|
q14174
|
setPath
|
train
|
function setPath(uri) {
if (uri.path || (uri.pathname === undefined && uri.search === undefined)) return;
uri.path = '';
if (uri.pathname) uri.path += uri.pathname;
if (uri.search) uri.path += uri.search;
}
|
javascript
|
{
"resource": ""
}
|
q14175
|
setSearch
|
train
|
function setSearch(uri) {
if (typeof uri.search === 'string' || uri.query === undefined) return;
if (typeof uri.query === 'string') {
uri.search = '?' + uri.query;
return;
}
var name, filled = false;
uri.search = '?';
for (name in uri.query) {
filled = true;
uri.search += name + '=' + uri.query[name] + '&';
}
uri.search = uri.search.substr(0, uri.search.length - 1);
}
|
javascript
|
{
"resource": ""
}
|
q14176
|
parseFilepath
|
train
|
function parseFilepath(path) {
if (path === undefined) {
return {filename: null, list: []};
}
var list = path.split('/'),
isDir = (path[path.length - 1] === '/') || (list[list.length - 1].indexOf('.') === -1);
return {
filename: isDir ? null : list.pop(),
list: list
};
}
|
javascript
|
{
"resource": ""
}
|
q14177
|
bin
|
train
|
function bin(argv) {
rm(argv, function(err, res, uri) {
console.log('rm of : ' + uri);
});
}
|
javascript
|
{
"resource": ""
}
|
q14178
|
buildError
|
train
|
function buildError(err, hackErr) {
var stack1 = err.stack;
var stack2 = hackErr.stack;
var label = hackErr.label;
var stack = [];
stack1.split('\n').forEach(function(line, index, arr) {
if (line.match(/^ at GeneratorFunctionPrototype.next/)) {
stack = stack.concat(arr.slice(0, index));
return;
}
});
stack = stack.concat(stack2.split('\n').slice(2));
if (!stack[0].match(/^Error:/)) {
stack.unshift(err.message);
}
if (!!label) {
stack.unshift('[DEBUG: ' + label + ']');
}
stack = stack.join('\n');
var newError = new Error();
newError.message = err.message;
newError.stack = stack;
return newError;
}
|
javascript
|
{
"resource": ""
}
|
q14179
|
train
|
function(argument) {
//console.log("deep.Deferred.resolve : ", argument);
if (this.rejected || this.resolved)
throw new Error("deferred has already been ended !");
if (argument instanceof Error)
return this.reject(argument);
this._success = argument;
this.resolved = true;
var self = this;
this._promises.forEach(function(promise) {
promise.resolve(argument);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14180
|
train
|
function(argument) {
// console.log("DeepDeferred.reject");
if (this.rejected || this.resolved)
throw new Error("deferred has already been ended !");
this._error = argument;
this.rejected = true;
var self = this;
this._promises.forEach(function(promise) {
promise.reject(argument);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14181
|
train
|
function() {
var prom = new promise.Promise();
//console.log("deep2.Deffered.promise : ", prom, " r,r,c : ", this.rejected, this.resolved, this.canceled)
if (this.resolved)
return prom.resolve(this._success);
if (this.rejected)
return prom.reject(this._error);
this._promises.push(prom);
return prom;
}
|
javascript
|
{
"resource": ""
}
|
|
q14182
|
init
|
train
|
function init()
{
scope._servConn = new ConnectaSocket(scope._url,scope._reconnect,scope._encode);
scope._servConn.onConnected = function(e)
{
scope.id = e;
scope.dispatchEvent("connected");
}
scope._servConn.onError = function(e)
{
scope.dispatchEvent("error",e);
}
scope._servConn.onClose = function(e)
{
scope.dispatchEvent("close");
scope.closePeers();
}
scope._servConn.onJoinedRoom = onJoinedRoom;
scope._servConn.onClientJoinedRoom = onClientJoinedRoom;
scope._servConn.onLeftRoom = onLeftRoom;
scope._servConn.onClientLeftRoom = onClientLeftRoom;
scope._servConn.onSDPDescription = onSDPDescription;
scope._servConn.onIceCandidate = onIceCandidate;
scope._servConn.onRTCFallback = onRTCFallback;
scope._servConn.onMessage = onServerMessage;
scope._servConn.onBytesMessage = onServerByteArray;
window.addEventListener("beforeunload", function (event)
{
scope.dispose();
});
}
|
javascript
|
{
"resource": ""
}
|
q14183
|
createPeerInstance
|
train
|
function createPeerInstance(id)
{
var peer = new ConnectaPeer(id,stunUrls);
peer.onIceCandidate = gotIceCandidate;
peer.onDescription = createdDescription;
peer.onRemoteStream = gotRemoteStream;
peer.onConnected = onPeerConnected;
peer.onMessage = onPeerMessage;
peer.onBytesMessage = onBytesMessage;
peer.onConnectionFail = onPeerFailed;
peer.onClosed = onPeerClose;
peer.onError = onPeerError;
peer.onChannelState = onPeerState;
scope.peers[id] = peer;
peer.init();
return peer;
}
|
javascript
|
{
"resource": ""
}
|
q14184
|
getPeerByRTCId
|
train
|
function getPeerByRTCId(id)
{
for(var num = 0; num < scope._servConn.roomUsers.length; num++)
{
if(scope._servConn.roomUsers[num].rtcId == id)
{
return scope._servConn.roomUsers[num];
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q14185
|
getOrCreatePeer
|
train
|
function getOrCreatePeer(id)
{
if(scope.peers[id])
{
return scope.peers[id];
}
return createPeerInstance(id);
}
|
javascript
|
{
"resource": ""
}
|
q14186
|
onClientJoinedRoom
|
train
|
function onClientJoinedRoom(id)
{
if(scope._servConn.useRTC)
{
if(scope.hasWebRTCSupport())
{
var peer = getOrCreatePeer(id);
peer.createOffer();
}
else
{
scope._servConn.sendRTCState(false,id);
}
}
scope.dispatchEvent("clientJoinedRoom",id);
}
|
javascript
|
{
"resource": ""
}
|
q14187
|
onRTCFallback
|
train
|
function onRTCFallback(from,data,isArray)
{
var peer = getPeerByRTCId(from);
if(peer)
{
if(isArray == true)
{
data = sliceArray(data,0,data.length-2);// data.slice(0,data.length-2);
}
scope.dispatchEvent("peerMessage",{message:data,id:peer.id,rtc:peer.rtcId,array:isArray,fallback:true});
}
}
|
javascript
|
{
"resource": ""
}
|
q14188
|
onServerMessage
|
train
|
function onServerMessage(data)
{
if(data.ev)
{
scope.dispatchEvent("onServerMessage",data);
scope.dispatchEvent(data.ev,data);
}
}
|
javascript
|
{
"resource": ""
}
|
q14189
|
onPeerConnected
|
train
|
function onPeerConnected(peer)
{
if(scope.localStream)
{
peer.updateStream(scope.localStream,false);
}
scope._servConn.sendRTCState(true,peer.id);
scope.dispatchEvent("peerConnected",peer.id);
}
|
javascript
|
{
"resource": ""
}
|
q14190
|
onPeerFailed
|
train
|
function onPeerFailed(peer)
{
scope._servConn.sendRTCState(false,peer.id);
scope.dispatchEvent("peerFailed",peer.id);
}
|
javascript
|
{
"resource": ""
}
|
q14191
|
onPeerClose
|
train
|
function onPeerClose(peer)
{
var id = peer.id;
scope.removePeer(peer);
sendPeerClose(id);
scope.dispatchEvent("peerDisconnected",id);
}
|
javascript
|
{
"resource": ""
}
|
q14192
|
onIceCandidate
|
train
|
function onIceCandidate(id,data)
{
if(scope.hasWebRTCSupport())
{
getOrCreatePeer(id).onServerMessage(JSON.parse(data));
}
}
|
javascript
|
{
"resource": ""
}
|
q14193
|
onPeerMessage
|
train
|
function onPeerMessage(peer,msg)
{
scope.dispatchEvent("peerMessage",{message:msg,id:peer.id,rtc:peer.rtcId,array:false,fallback:false});
}
|
javascript
|
{
"resource": ""
}
|
q14194
|
onBytesMessage
|
train
|
function onBytesMessage(peer,data)
{
var arr = bufferToArray(scope._servConn.byteType,data);
if(arr)
{
if(scope._servConn.rtcFallback == true)
{
arr = arr.slice(0,arr.length-2);
}
scope.dispatchEvent("peerMessage",{message:arr,id:peer.id,rtc:peer.rtcId,array:true,fallback:false});
}
}
|
javascript
|
{
"resource": ""
}
|
q14195
|
addText
|
train
|
function addText() {
// Add title
dialogEl.querySelector( '#dialog-title' ).innerHTML = options.title
// Add optional description
var descriptionEl = dialogEl.querySelector( '#dialog-description' )
if ( options.description ) {
descriptionEl.innerHTML = options.description
} else {
descriptionEl.parentElement.removeChild( descriptionEl )
dialogEl.removeAttribute( 'aria-labelledby' )
}
}
|
javascript
|
{
"resource": ""
}
|
q14196
|
tab
|
train
|
function tab( event ) {
// Find all focusable elements in the dialog card
var focusable = dialogEl.querySelectorAll('input:not([type=hidden]), textarea, select, button'),
last = focusable[focusable.length - 1],
focused = document.activeElement
// If focused on the last focusable element, tab to the first element.
if ( focused == last ) {
if ( event ){ event.preventDefault() }
focusable[0].focus()
}
// Focus on the last element if the focused element is not a child of the dialog
if ( !focused || !toolbox.childOf( focused, dialogEl ) ) {
last.focus()
}
}
|
javascript
|
{
"resource": ""
}
|
q14197
|
train
|
function( d ) { // ISO-8601 year number. This has the same value as Y, except that if the ISO
var m = d.getMonth(), w = DATE_PROTO.getISOWeek.call( d ); // week number (W) belongs to the previous or next year, that year is used instead.
return ( d.getFullYear() + ( w == 1 && m > 0 ? 1 : ( w >= 52 && m < 11 ? -1 : 0 ) ) );
}
|
javascript
|
{
"resource": ""
}
|
|
q14198
|
train
|
function(ac) {
var data = {},
selectedmojit = ac.params.getFromRoute('mojit') || 'none';
data[selectedmojit] = true;
ac.assets.addCss('./index.css');
ac.done(data);
}
|
javascript
|
{
"resource": ""
}
|
|
q14199
|
executeCommands
|
train
|
function executeCommands(bulkOperation, options, callback) {
if (bulkOperation.s.batches.length === 0) {
return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult));
}
// Ordered execution of the command
const batch = bulkOperation.s.batches.shift();
function resultHandler(err, result) {
// Error is a driver related error not a bulk op error, terminate
if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) {
return handleCallback(callback, err);
}
// If we have and error
if (err) err.ok = 0;
if (err instanceof MongoWriteConcernError) {
return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, true, err, callback);
}
// Merge the results together
const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult);
const mergeResult = mergeBatchResults(true, batch, bulkOperation.s.bulkResult, err, result);
if (mergeResult != null) {
return handleCallback(callback, null, writeResult);
}
if (bulkOperation.handleWriteError(callback, writeResult)) return;
// Execute the next command in line
executeCommands(bulkOperation, options, callback);
}
bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.