_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q6600
|
format
|
train
|
function format(value) {
if (typeof value == 'number')
return value;
var str = String(value);
var ary = str.split('\n').map((e) => JSON.stringify(e));
if (ary.length > 1) {
// If the string has newlines, start it off on its own line so that
// it's easier to compare against another string with newlines.
return '\n' + ary.join('\n');
} else {
return ary.join('\n');
}
}
|
javascript
|
{
"resource": ""
}
|
q6601
|
ak
|
train
|
function ak(a, b) {
return function(e, k) {
var action = (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey ||
!self.keyboard.applicationKeypad) ? a : b;
return resolve(action, e, k);
};
}
|
javascript
|
{
"resource": ""
}
|
q6602
|
bs
|
train
|
function bs(a, b) {
return function(e, k) {
var action = !self.keyboard.backspaceSendsBackspace ? a : b;
return resolve(action, e, k);
};
}
|
javascript
|
{
"resource": ""
}
|
q6603
|
alt
|
train
|
function alt(a, b) {
return function(e, k) {
var action = !e.altKey ? a : b;
return resolve(action, e, k);
};
}
|
javascript
|
{
"resource": ""
}
|
q6604
|
mod
|
train
|
function mod(a, b) {
return function(e, k) {
var action = !(e.shiftKey || e.ctrlKey || e.altKey || e.metaKey) ? a : b;
return resolve(action, e, k);
};
}
|
javascript
|
{
"resource": ""
}
|
q6605
|
med
|
train
|
function med(fn) {
return function(e, k) {
if (!self.keyboard.mediaKeysAreFKeys) {
// Block Back, Forward, and Reload keys to avoid navigating away from
// the current page.
return (e.keyCode == 166 || e.keyCode == 167 || e.keyCode == 168) ?
hterm.Keyboard.KeyActions.CANCEL :
hterm.Keyboard.KeyActions.PASS;
}
return resolve(fn, e, k);
};
}
|
javascript
|
{
"resource": ""
}
|
q6606
|
anchorFirst
|
train
|
function anchorFirst() {
self.startRow = anchorRow;
self.startNode = selection.anchorNode;
self.startOffset = selection.anchorOffset;
self.endRow = focusRow;
self.endNode = selection.focusNode;
self.endOffset = selection.focusOffset;
}
|
javascript
|
{
"resource": ""
}
|
q6607
|
removeUntilNode
|
train
|
function removeUntilNode(currentNode, targetNode) {
while (currentNode != targetNode) {
if (!currentNode)
throw 'Did not encounter target node';
if (currentNode == self.bottomFold_)
throw 'Encountered bottom fold before target node';
var deadNode = currentNode;
currentNode = currentNode.nextSibling;
deadNode.parentNode.removeChild(deadNode);
}
}
|
javascript
|
{
"resource": ""
}
|
q6608
|
train
|
function (shouldReloadClientProgram) {
// Step 1: load the current client program on the server and update the
// hash values in __meteor_runtime_config__.
if (shouldReloadClientProgram) {
WebAppInternals.reloadClientPrograms();
}
// If we just re-read the client program, or if we don't have an autoupdate
// version, calculate it.
if (shouldReloadClientProgram || Autoupdate.autoupdateVersion === null) {
Autoupdate.autoupdateVersion =
process.env.AUTOUPDATE_VERSION ||
WebApp.calculateClientHashNonRefreshable();
}
// If we just recalculated it OR if it was set by (eg) test-in-browser,
// ensure it ends up in __meteor_runtime_config__.
__meteor_runtime_config__.autoupdateVersion =
Autoupdate.autoupdateVersion;
Autoupdate.autoupdateVersionRefreshable =
__meteor_runtime_config__.autoupdateVersionRefreshable =
process.env.AUTOUPDATE_VERSION ||
WebApp.calculateClientHashRefreshable();
Autoupdate.autoupdateVersionCordova =
__meteor_runtime_config__.autoupdateVersionCordova =
process.env.AUTOUPDATE_VERSION ||
WebApp.calculateClientHashCordova();
// Step 2: form the new client boilerplate which contains the updated
// assets and __meteor_runtime_config__.
if (shouldReloadClientProgram) {
WebAppInternals.generateBoilerplate();
}
// XXX COMPAT WITH 0.8.3
if (! ClientVersions.findOne({current: true})) {
// To ensure apps with version of Meteor prior to 0.9.0 (in
// which the structure of documents in `ClientVersions` was
// different) also reload.
ClientVersions.insert({current: true});
}
if (! ClientVersions.findOne({_id: "version"})) {
ClientVersions.insert({
_id: "version",
version: Autoupdate.autoupdateVersion
});
} else {
ClientVersions.update("version", { $set: {
version: Autoupdate.autoupdateVersion
}});
}
if (! ClientVersions.findOne({_id: "version-cordova"})) {
ClientVersions.insert({
_id: "version-cordova",
version: Autoupdate.autoupdateVersionCordova,
refreshable: false
});
} else {
ClientVersions.update("version-cordova", { $set: {
version: Autoupdate.autoupdateVersionCordova
}});
}
// Use `onListening` here because we need to use
// `WebAppInternals.refreshableAssets`, which is only set after
// `WebApp.generateBoilerplate` is called by `main` in webapp.
WebApp.onListening(function () {
if (! ClientVersions.findOne({_id: "version-refreshable"})) {
ClientVersions.insert({
_id: "version-refreshable",
version: Autoupdate.autoupdateVersionRefreshable,
assets: WebAppInternals.refreshableAssets
});
} else {
ClientVersions.update("version-refreshable", { $set: {
version: Autoupdate.autoupdateVersionRefreshable,
assets: WebAppInternals.refreshableAssets
}});
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6609
|
train
|
function (collectionName, sessionCallbacks) {
var self = this;
self.collectionName = collectionName;
self.documents = {};
self.callbacks = sessionCallbacks;
}
|
javascript
|
{
"resource": ""
}
|
|
q6610
|
train
|
function (reason, offendingMessage) {
var self = this;
var msg = {msg: 'error', reason: reason};
if (offendingMessage)
msg.offendingMessage = offendingMessage;
self.send(msg);
}
|
javascript
|
{
"resource": ""
}
|
|
q6611
|
train
|
function(userId) {
var self = this;
if (userId !== null && typeof userId !== "string")
throw new Error("setUserId must be called on string or null, not " +
typeof userId);
// Prevent newly-created universal subscriptions from being added to our
// session; they will be found below when we call startUniversalSubs.
//
// (We don't have to worry about named subscriptions, because we only add
// them when we process a 'sub' message. We are currently processing a
// 'method' message, and the method did not unblock, because it is illegal
// to call setUserId after unblock. Thus we cannot be concurrently adding a
// new named subscription.)
self._dontStartNewUniversalSubs = true;
// Prevent current subs from updating our collectionViews and call their
// stop callbacks. This may yield.
self._eachSub(function (sub) {
sub._deactivate();
});
// All subs should now be deactivated. Stop sending messages to the client,
// save the state of the published collections, reset to an empty view, and
// update the userId.
self._isSending = false;
var beforeCVs = self.collectionViews;
self.collectionViews = {};
self.userId = userId;
// Save the old named subs, and reset to having no subscriptions.
var oldNamedSubs = self._namedSubs;
self._namedSubs = {};
self._universalSubs = [];
_.each(oldNamedSubs, function (sub, subscriptionId) {
self._namedSubs[subscriptionId] = sub._recreate();
// nb: if the handler throws or calls this.error(), it will in fact
// immediately send its 'nosub'. This is OK, though.
self._namedSubs[subscriptionId]._runHandler();
});
// Allow newly-created universal subs to be started on our connection in
// parallel with the ones we're spinning up here, and spin up universal
// subs.
self._dontStartNewUniversalSubs = false;
self.startUniversalSubs();
// Start sending messages again, beginning with the diff from the previous
// state of the world to the current state. No yields are allowed during
// this diff, so that other changes cannot interleave.
Meteor._noYieldsAllowed(function () {
self._isSending = true;
self._diffCollectionViews(beforeCVs);
if (!_.isEmpty(self._pendingReady)) {
self.sendReady(self._pendingReady);
self._pendingReady = [];
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6612
|
train
|
function () {
var self = this;
_.each(self._namedSubs, function (sub, id) {
sub._deactivate();
});
self._namedSubs = {};
_.each(self._universalSubs, function (sub) {
sub._deactivate();
});
self._universalSubs = [];
}
|
javascript
|
{
"resource": ""
}
|
|
q6613
|
train
|
function () {
var self = this;
Meteor._noYieldsAllowed(function () {
_.each(self._documents, function(collectionDocs, collectionName) {
// Iterate over _.keys instead of the dictionary itself, since we'll be
// mutating it.
_.each(_.keys(collectionDocs), function (strId) {
self.removed(collectionName, self._idFilter.idParse(strId));
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6614
|
train
|
function(value) {
var model;
if (this.options.isCollection) {
// find value in collection, error if no model found
if (this.options.indexOf(value) === -1) model = this.getModelForId(value);
else model = value;
if (!model) throw new Error('model or model idAttribute not found in options collection');
return this.yieldModel ? model : model[this.idAttribute];
} else if (Array.isArray(this.options)) {
// find value value in options array
// find option, formatted [['val', 'text'], ...]
if (this.options.length && Array.isArray(this.options[0])) {
for (var i = this.options.length - 1; i >= 0; i--) {
if (this.options[i][0] == value) return this.options[i];
}
}
// find option, formatted ['valAndText', ...] format
if (this.options.length && this.options.indexOf(value) !== -1) return value;
throw new Error('value not in set of provided options');
}
throw new Error('select option set invalid');
}
|
javascript
|
{
"resource": ""
}
|
|
q6615
|
fixCurves
|
train
|
function fixCurves() {
if (point[0] == 0) start = point[1];
if (point[0] == 1) end = point[1];
var points = filter[curves.name];
var foundStart = false;
var foundEnd = false;
for (var i = 0; i < points.length; i++) {
var p = points[i];
if (p[0] == 0) {
foundStart = true;
if (point[0] == 0 && p != point) points.splice(i--, 1);
} else if (p[0] == 1) {
foundEnd = true;
if (point[0] == 1 && p != point) points.splice(i--, 1);
}
}
if (!foundStart) points.push([0, start]);
if (!foundEnd) points.push([1, end]);
}
|
javascript
|
{
"resource": ""
}
|
q6616
|
loadSimpleResourceMap
|
train
|
function loadSimpleResourceMap(config) {
return new Promise((resolve, reject) => {
// Convert Jest config into glob pattern.
let testPathDirs;
let testFileExtensions;
let generatedGlob;
if (config.testPathDirs.length === 1) {
testPathDirs = config.testPathDirs[0];
} else {
testPathDirs = '{' + config.testPathDirs.join(',') + '}';
}
if (config.testFileExtensions.length === 1) {
testFileExtensions = config.testFileExtensions[0];
} else {
testFileExtensions = '{' + config.testFileExtensions.join(',') + '}';
}
generatedGlob = testPathDirs + '/' +
'**/' + config.testDirectoryName + '/**/*.' + testFileExtensions;
glob(generatedGlob, (err, files) => {
if (err) {
reject(err);
} else {
let resourceMap;
resourceMap = {
resourcePathMap: {}
};
files.forEach(file => {
let fullPath = path.resolve(file);
resourceMap.resourcePathMap[fullPath] = {
path: fullPath
};
});
resolve(resourceMap);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q6617
|
getWebpackStats
|
train
|
function getWebpackStats(config) {
let statsPaths = config.testPathDirs.map(testPathDir => {
return path.join(testPathDir, 'stats.json');
});
statsPaths.some(statsPath => {
try {
webpackStats = require(statsPath);
} catch (oh) {
// not found
}
return !!webpackStats;
});
if (!webpackStats) {
throw new Error('Cannot find Webpack stats in: \n' + statsPaths.join('\n'));
}
return webpackStats;
}
|
javascript
|
{
"resource": ""
}
|
q6618
|
train
|
function(attrs) {
for (var key in attrs) {
//convert cls to class
var mappedKey = key == 'cls' ? 'class' : key;
this.attributes[mappedKey] = attrs[key];
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q6619
|
train
|
function(lpad) {
lpad = lpad || 0;
var node = [],
attrs = [],
textnode = (this instanceof Jaml.TextNode),
multiline = this.multiLineTag();
//add any left padding
if (!textnode) node.push(this.getPadding(lpad));
//open the tag
node.push("<" + this.tagName);
for (var key in this.attributes) {
attrs.push(key + "=\"" + this.attributes[key] + "\"");
}
attrs.sort()
//add any tag attributes
for (var i=0; i<attrs.length; i++) {
node.push(" " + attrs[i]);
}
if (this.isSelfClosing() && this.children.length==0) {
node.push("/>\n");
} else {
node.push(">");
if (multiline) node.push("\n");
this.renderChildren(node, this.children, lpad);
if (multiline) node.push(this.getPadding(lpad));
node.push("</", this.tagName, ">\n");
}
return node.join("");
}
|
javascript
|
{
"resource": ""
}
|
|
q6620
|
train
|
function(node, children, lpad) {
var childLpad = lpad + 2;
for (var i=0; i < children.length; i++) {
var child = children[i];
if (child instanceof Array) {
var nestedChildren = child;
this.renderChildren(node, nestedChildren, lpad)
} else {
node.push(child.render(childLpad));
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6621
|
train
|
function(thisObj, data) {
data = data || (thisObj = thisObj || {});
//the 'data' argument can come in two flavours - array or non-array. Normalise it
//here so that it always looks like an array.
if (data.constructor.toString().indexOf("Array") == -1) {
data = [data];
}
with(this) {
for (var i=0; i < data.length; i++) {
eval("(" + this.tpl.toString() + ").call(thisObj, data[i], i)");
};
}
var roots = this.getRoots(),
output = "";
for (var i=0; i < roots.length; i++) {
output += roots[i].render();
};
return output;
}
|
javascript
|
{
"resource": ""
}
|
|
q6622
|
train
|
function(tagName) {
return function(attrs) {
var node = new Jaml.Node(tagName);
var firstArgIsAttributes = (typeof attrs == 'object')
&& !(attrs instanceof Jaml.Node)
&& !(attrs instanceof Jaml.TextNode);
if (firstArgIsAttributes) node.setAttributes(attrs);
var startIndex = firstArgIsAttributes ? 1 : 0;
for (var i=startIndex; i < arguments.length; i++) {
var arg = arguments[i];
if (typeof arg == "string" || arg == undefined) {
arg = new Jaml.TextNode(arg || "");
}
if (arg instanceof Jaml.Node || arg instanceof Jaml.TextNode) {
arg.parent = node;
}
node.addChild(arg);
};
this.nodes.push(node);
return node;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q6623
|
valueIsNullForValidator
|
train
|
function valueIsNullForValidator(value, validatorName) {
if (value === null || value === CONSTANT.NULL || typeof value === 'undefined') {
return true;
}
if (value === '' && VALIDATOR_CONSIDERS_EMPTY_STRING_NULL[validatorName]) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q6624
|
train
|
function (msg) {
var self = this;
if (! _.has(msg, 'collection')) {
return '';
} else if (typeof(msg.collection) === 'string') {
if (msg.collection === '')
throw Error("Message has empty collection!");
return msg.collection;
} else {
throw Error("Message has non-string collection!");
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6625
|
train
|
function(ownerId, callback) {
if (!ownerId) return callback(new Error(utils.i18n.blocklist.ownerId));
utils.debug('Blocklist get: ' + ownerId);
request.get({
path: '/users/' + querystring.escape(ownerId) + '/blocks'
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q6626
|
train
|
function(ownerId, userId, callback) {
if (!ownerId) return callback(new Error(utils.i18n.blocklist.ownerId));
if (!userId) return callback(new Error(utils.i18n.blocklist.userId));
utils.debug('Blocklist block: ' + ownerId + ' userId: ' + userId);
request.post({
path: '/users/' + querystring.escape(ownerId) + '/blocks',
body: {
user_id: userId
}
}, callback || utils.nop);
}
|
javascript
|
{
"resource": ""
}
|
|
q6627
|
argNames
|
train
|
function argNames(str) {
// Matching
var matches = str.match(regexes.argMatch);
if (!matches)
throw Error('sandcrawler.phantom_script.arguments: not enough arguments to compile a correct phantom scraper.');
return [matches[1], matches[2]];
}
|
javascript
|
{
"resource": ""
}
|
q6628
|
argName
|
train
|
function argName(str) {
// Matching
var matches = str.match(regexes.singleArgMatch);
if (!matches)
throw Error('sandcrawler.phantom_script.arguments: not enough arguments to compile a correct phantom scraper.');
return [matches[1]];
}
|
javascript
|
{
"resource": ""
}
|
q6629
|
wrap
|
train
|
function wrap(str, dollarName, doneName) {
return doneName ?
'(function(' + dollarName + ', ' + doneName + ', undefined){' + str + '})(artoo.$, artoo.done);' :
'(function(' + dollarName + ', undefined){' + str + '})(artoo.$);';
}
|
javascript
|
{
"resource": ""
}
|
q6630
|
nodeText
|
train
|
function nodeText (node) {
return squashWhitespace(node.textContent)
function squashWhitespace (string) {
return string.replace(/\s{2,}/g, ' ').trim()
}
}
|
javascript
|
{
"resource": ""
}
|
q6631
|
sendModifiedResponse
|
train
|
function sendModifiedResponse(clientRes, response, transform) {
var dataPipe = response,
decompressor = decompressorFor(response),
chunks = [];
if(decompressor) {
dataPipe = dataPipe.pipe(decompressor);
}
dataPipe.on('data', function(chunk) {
chunks.push(chunk);
});
dataPipe.on('end', function () {
var origContent = Buffer.concat(chunks);
transform(origContent, function (modifiedContent) {
response.headers['content-length'] = modifiedContent.length;
// The response has been de-chunked and uncompressed, so delete
// these headers from the response.
delete response.headers['content-encoding'];
delete response.headers['content-transfer-encoding'];
clientRes.writeHead(response.statusCode, response.headers);
clientRes.end(modifiedContent);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q6632
|
sendOriginalResponse
|
train
|
function sendOriginalResponse(clientRes, response) {
clientRes.writeHead(response.statusCode, response.headers);
response.pipe(clientRes);
}
|
javascript
|
{
"resource": ""
}
|
q6633
|
makeSNICallback
|
train
|
function makeSNICallback() {
var caKey = fs.readFileSync(__dirname + '/../cert/dummy.key', 'utf8'),
caCert = fs.readFileSync(__dirname + '/../cert/dummy.crt', 'utf8'),
serial = Math.floor(Date.now() / 1000),
cache = {};
var ver = process.version.match(/^v(\d+)\.(\d+)/);
var canUseSNI = ver[1] > 1 || ver[2] >= 12; // >= 0.12.0
console.log('Per-site certificate generation is: ' + (canUseSNI ? 'ENABLED' : 'DISABLED'));
console.log('Feature requires SNI support (node >= v0.12), running version is: ' + ver[0]);
if(!canUseSNI) {
return undefined;
}
var createCertificateAsync = Promise.promisify(pem.createCertificate);
return function SNICallback(servername, cb) {
if(!cache.hasOwnProperty(servername)) {
// Slow path, put a promise for the cert into cache. Need to increment
// the serial or browsers will complain.
console.log('Generating new TLS certificate for: ' + servername);
var certOptions = {
commonName: servername,
serviceKey: caKey,
serviceCertificate: caCert,
serial: serial++,
days: 3650
};
cache[servername] = createCertificateAsync(certOptions).then(function (keys) {
return tls.createSecureContext({
key: keys.clientKey,
cert: keys.certificate,
ca: caCert
}).context;
});
}
cache[servername].then(function (ctx) {
cb(null, ctx);
}).catch(function (err) {
console.log('Error generating TLS certificate: ', err);
cb(err, null);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q6634
|
Statement
|
train
|
function Statement (attributes) {
for (var key in attributes) {
if (attributes.hasOwnProperty(key)) this[key] = result(attributes[key])
}
// Convert table rows to array of transactions
var transactions = Table.prototype.rowsToArray(this.rows, {
processRow: function (row) {
return this.createTransaction(weld(this.columns, row))
}.bind(this)
})
this.transactions = new Transactions(transactions, this)
}
|
javascript
|
{
"resource": ""
}
|
q6635
|
select
|
train
|
function select( state, json, path, isSeekAll ) {
var steps = getSteps( state, path );
if ( !steps.length ) { return { json: null }; }
var paths = getCachedPaths( state, json );
var walker = !!paths ? cachedWalk : walk;
var found = walker( paths || json,
isSeekAll ? [] : null,
selectStep( steps, isSeekAll ) );
var lastStep = steps[ 0 ].path;
return {
json: found,
isFinal: ( isSeekAll ? found.length === 0 : found === null ) ||
!!~[ "@id", "@index", "@value", "@type" ].indexOf( lastStep )
};
}
|
javascript
|
{
"resource": ""
}
|
q6636
|
train
|
function(options, callback) {
if (!options) options = {};
if (!(this.client_id || this.client_secret) && !(options.client_id || options.client_secret)) {
return _handleErr('Please provide client_id and client_secret in options', callback);
}
var options = {
api: '/oauth',
endpoint: '/token',
method: 'POST',
payload: {
client_id: options.client_id || this.client_id,
client_secret: options.client_secret || this.client_secret,
grant_type: options.grant_type || 'client_credentials'
}
}
var self = this;
if (callback) {
return this._request(options, function(err, res) {
if (!err) {
self._setToken(res);
callback(null, res);
} else callback(err);
})
} else {
return this._request(options)
.then(function(res) {
self._setToken(res);
Promise.resolve(res);
})
.catch(function(err) {
Promise.reject(err);
})
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6637
|
getTrending
|
train
|
function getTrending(options, callback) {
if (!options) options = {};
return this._request({
api: '/gfycats',
endpoint: '/trending',
method: 'GET',
query: {
count: options.count || 100,
cursor: options.cursor || null,
tagName: options.tagName || null
}
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
q6638
|
train
|
function(options, callback) {
return this._request({
api: '/gfycats',
endpoint: '/' + options.id + '/related',
method: 'GET',
query: {
cursor: options.cursor,
count: options.count,
from: options.from
}
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q6639
|
getRedisOptions
|
train
|
function getRedisOptions() {
var defaults = {
debug: false,
certExpiry: 100 * 60 * 60 * 24, // all cert data expires after 100 days
redisOptions: {
db: 3,
retry_strategy: function(options) {
// reconnect after 60 seconds, keep trying forever
return 60 * 1000;
}
}
};
var mergedOptions = _.merge(defaults, options);
_debug('le-store-redis.getRedisOptions', mergedOptions);
return mergedOptions;
}
|
javascript
|
{
"resource": ""
}
|
q6640
|
redisSetAccountKeypair
|
train
|
function redisSetAccountKeypair(options, keypair, callback) {
_debug('le-store-redis.redisSetAccountKeypair', '\nkeypair:', keypair);
var keypairId = 'keypair-' +
crypto.createHash('sha256').update(keypair.publicKeyPem).digest('hex');
var jsonKeypair = JSON.stringify(keypair);
async.parallel([
function(callback) {
// write the keypair data
client.set(keypairId, jsonKeypair, callback);
},
function(callback) {
// create an index for email if one was given
if(options.email) {
return _createIndex('idx-e2k', options.email, keypairId, callback);
}
callback(null, 'NOP');
}], function(err, results) {
if(err) {
return callback(err);
}
if(results[0] !== null && results[1] !== null) {
callback(null, keypair);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q6641
|
redisCheckAccountKeypair
|
train
|
function redisCheckAccountKeypair(options, callback) {
_debug('le-store-redis.redisCheckAccountKeypair:',
options.email, options.accountId);
if(options.email) {
return _getByIndex('idx-e2k', options.email, callback);
} else if(options.accountId) {
return _getByIndex('idx-a2k', options.accountId, callback);
}
callback(new Error('le-store-redis.redisCheckAccountKeypair ' +
'lookup requires options.email or options.accountId.'));
}
|
javascript
|
{
"resource": ""
}
|
q6642
|
redisCheckAccount
|
train
|
function redisCheckAccount(options, callback) {
_debug('le-store-redis.redisCheckAccount:',
options.email, options.accountId, options.domains);
if(options.email) {
return _getByIndex('idx-e2a', options.email, callback);
} else if(options.accountId) {
return client.get(options.accountId, _deserializeJson(callback));
} else if(options.domains) {
// FIXME: implement domain indexing
return client.get(options.domains, _deserializeJson(callback));
}
callback(new Error('le-store-redis.redisCheckAccount requires ' +
'options.email, options.accountId, or options.domains'));
}
|
javascript
|
{
"resource": ""
}
|
q6643
|
redisSetAccount
|
train
|
function redisSetAccount(options, reg, callback) {
_debug('le-store-redis.redisSetAccount', '\nregistration:', reg);
var accountId = 'account-' + crypto.createHash('sha256')
.update(reg.keypair.publicKeyPem).digest('hex');
var account = _.cloneDeep(reg);
account.id = accountId;
account.accountId = accountId;
account.email = options.email;
account.agreeTos = options.agreeTos || reg.agreeTos;
var jsonAccount = JSON.stringify(account);
async.parallel([
function(callback) {
return client.set(accountId, jsonAccount, callback);
},
function(callback) {
if(account.email) {
return _createIndex('idx-e2a', account.email, account.id, callback);
}
callback(null, 'NOP');
}], function(err, results) {
if(err) {
return callback(err);
}
if(results[0] !== null && results[1] !== null) {
callback(null, account);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q6644
|
redisSetCertificateKeypair
|
train
|
function redisSetCertificateKeypair(options, keypair, callback) {
_debug('le-store-redis.redisSetCertificateKeypair', '\nkeypair:', keypair);
var keypairId = 'keypair-' + crypto.createHash('sha256')
.update(keypair.publicKeyPem).digest('hex');
var jsonKeypair = JSON.stringify(keypair);
async.parallel([
function(callback) {
// write the cert to the database
client.set(keypairId, jsonKeypair, callback);
return client.expire(keypairId, moduleOptions.certExpiry);
},
function(callback) {
if(options.domains) {
// create a domain to keypair index
return async.each(options.domains, function(domain, callback) {
_createIndex('idx-d2k', domain, keypairId,
moduleOptions.certExpiry, callback);
}, function(err) {
callback(err);
});
}
callback();
}], function(err) {
if(err) {
return callback(err);
}
callback(null, keypair);
});
}
|
javascript
|
{
"resource": ""
}
|
q6645
|
redisCheckCertificateKeypair
|
train
|
function redisCheckCertificateKeypair(options, callback) {
_debug('le-store-redis.redisCheckCertificateKeypair:', options.domains);
if(options.domains && options.domains[0]) {
return _getByIndex('idx-d2k', options.domains[0], callback);
}
callback(new Error('le-store-redis.redisCheckCertificateKeypair requires ' +
'options.domains'));
}
|
javascript
|
{
"resource": ""
}
|
q6646
|
redisCheckCertificate
|
train
|
function redisCheckCertificate(options, callback) {
_debug('le-store-redis.redisCheckCertificate:',
options.domains, options.email, options.accountId);
if(options.domains && options.domains.length > 0) {
return _getByIndex('idx-d2c', options.domains[0], callback);
} else if(options.email) {
return _getByIndex('idx-e2c', options.email, callback);
} else if(options.accountId) {
return _getByIndex('idx-a2c', options.accoundId, callback);
}
callback(new Error('le-store-redis.redisCheckCertificate requires ' +
'options.domains, options.email, or options.accoundId'));
}
|
javascript
|
{
"resource": ""
}
|
q6647
|
redisSetCertificate
|
train
|
function redisSetCertificate(options, callback) {
_debug('le-store-redis.redisSetCertificate',
'\npems:', options.pems);
var certId = 'cert-' + crypto.createHash('sha256')
.update(options.pems.cert).digest('hex');
var cert = _.cloneDeep(options.pems);
var jsonCert = JSON.stringify(cert);
async.parallel([
function(callback) {
// write the cert to the database
client.set(certId, jsonCert, callback);
return client.expire(certId, moduleOptions.certExpiry);
},
function(callback) {
if(options.accountId) {
// create an accountId to cert index
return _createIndex('idx-a2c', options.accountId, certId,
moduleOptions.certExpiry, callback);
}
callback();
},
function(callback) {
if(options.email) {
// create an email to cert index
return _createIndex('idx-e2c', options.email, certId,
moduleOptions.certExpiry, callback);
}
callback();
},
function(callback) {
if(options.domains) {
// create a domain to cert index
return async.each(options.domains, function(domain, callback) {
_createIndex('idx-d2c', domain, certId,
moduleOptions.certExpiry, callback);
}, function(err) {
callback(err);
});
}
callback();
}], function(err) {
if(err) {
return callback(err);
}
callback(null, cert);
});
}
|
javascript
|
{
"resource": ""
}
|
q6648
|
_createIndex
|
train
|
function _createIndex(indexName, indexData, value, ex, cb) {
var callback = cb;
var expiry = ex;
if(!callback) {
expiry = null;
callback = ex;
}
// generate the index value
var index = indexName + '-' +
crypto.createHash('sha256').update(indexData).digest('hex');
client.set(index, value, function(err, reply) {
if(err) {
return callback(err);
}
if(expiry) {
return client.expire(index, expiry, function(err) {
callback(err, reply);
});
}
callback(err, reply);
});
}
|
javascript
|
{
"resource": ""
}
|
q6649
|
_getByIndex
|
train
|
function _getByIndex(indexName, indexData, callback) {
// generate the index
var index = indexName + '-' +
crypto.createHash('sha256').update(indexData).digest('hex');
// fetch the value of the index
client.get(index, function(err, reply) {
if(err) {
return callback(err);
}
if(!reply) {
// index does not exist
return callback(null, null);
}
// fetch the actual data
client.get(reply, _deserializeJson(callback));
});
}
|
javascript
|
{
"resource": ""
}
|
q6650
|
executeApiCall
|
train
|
function executeApiCall(callback, needConnection) {
needConnection = typeof needConnection !== 'undefined' ? needConnection : true;
authenticate(function (error, result) {
if (error || !result) {
callback(error, result);
return;
}
if (needConnection) {
isConnected(function (error, result) {
if (error || !result) {
console.error("[Deluge] WebUI not connected to a daemon");
return;
}
callback(error, result);
});
} else {
callback(error, result);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q6651
|
downloadTorrentFile
|
train
|
function downloadTorrentFile(url, cookie, callback) {
post({
method: 'web.download_torrent_from_url',
params: [url,cookie]
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
q6652
|
searchCookieJar
|
train
|
function searchCookieJar(url){
var cookie = '';
for (var key in COOKIE_JAR) {
// Check if url starts with key, see: http://stackoverflow.com/q/646628/2402914
if (COOKIE_JAR.hasOwnProperty(key) && url.lastIndexOf(key, 0) === 0) {
cookie = COOKIE_JAR[key];
console.log("Using cookies for "+key);
break;
}
}
return cookie;
}
|
javascript
|
{
"resource": ""
}
|
q6653
|
getComponents
|
train
|
function getComponents(file) {
var relativePath = file.relative;
var pathParts = Path.dirname(relativePath).split(Path.sep);
return {
ext: Path.extname(relativePath).substr(1), // strip dot
filename: Path.basename(relativePath),
packageName: pathParts[0]
};
}
|
javascript
|
{
"resource": ""
}
|
q6654
|
train
|
function(n, a, b) { // Check if an angle n is between a and b
var c = this['SCALE'];
n = mod(n, c);
a = mod(a, c);
b = mod(b, c);
if (a < b)
return a <= n && n <= b;
// return 0 <= n && n <= b || a <= n && n < 360;
return a <= n || n <= b;
}
|
javascript
|
{
"resource": ""
}
|
|
q6655
|
train
|
function(a, b) {
var m = this['SCALE'];
var h = m / 2;
// One-Liner:
//return Math.min(mod(a - b, m), mod(b - a, m));
var diff = this['normalizeHalf'](a - b);
if (diff > h)
diff = diff - m;
return Math.abs(diff);
}
|
javascript
|
{
"resource": ""
}
|
|
q6656
|
train
|
function(sin, cos) {
var s = this['SCALE'];
var angle = (1 + Math.acos(cos) / TAU) * s;
if (sin < 0) {
angle = s - angle;
}
return mod(angle, s);
}
|
javascript
|
{
"resource": ""
}
|
|
q6657
|
train
|
function(p1, p2) {
var s = this['SCALE'];
var angle = (TAU + Math.atan2(p2[1] - p1[1], p2[0] - p1[0])) % TAU;
return angle / TAU * s;
}
|
javascript
|
{
"resource": ""
}
|
|
q6658
|
train
|
function(x, y, k, shift) {
var s = this['SCALE'];
if (k === undefined)
k = 4; // How many regions? 4 = quadrant, 8 = octant, ...
if (shift === undefined)
shift = 0; // Rotate the coordinate system by shift° (positiv = counter-clockwise)
/* shift = PI / k, k = 4:
* I) 45-135
* II) 135-225
* III) 225-315
* IV) 315-360
*/
/* shift = 0, k = 4:
* I) 0-90
* II) 90-180
* III) 180-270
* IV) 270-360
*/
var phi = (Math.atan2(y, x) + TAU) / TAU;
if (Math.abs(phi * s % (s / k)) < EPS) {
return 0;
}
return 1 + mod(Math.floor(k * shift / s + k * phi), k);
}
|
javascript
|
{
"resource": ""
}
|
|
q6659
|
train
|
function(course) {
// 0° = N
// 90° = E
// 180° = S
// 270° = W
var s = this['SCALE'];
var k = DIRECTIONS.length;
// floor((2ck + s) / (2s)) = round((c / s) * k)
var dir = Math.round(course / s * k);
return DIRECTIONS[mod(dir, k)];
}
|
javascript
|
{
"resource": ""
}
|
|
q6660
|
train
|
function(a, b, p, dir) {
var s = this['SCALE'];
a = mod(a, s);
b = mod(b, s);
if (a === b)
return a;
// dir becomes an offset if we have to add a full revolution (=scale)
if (!dir)
dir =-s;
else if ((dir === 1) === (a < b))
dir*= s;
else
dir = 0;
return mod(a + p * (b - a - dir), s);
}
|
javascript
|
{
"resource": ""
}
|
|
q6661
|
describeKey
|
train
|
function describeKey(e) {
var via = '';
var desc = [];
if (e.getModifierState("Shift")) desc.push("Shift");
if (e.getModifierState("Control")) desc.push("Control");
if (e.getModifierState("Alt")) desc.push("Alt");
if (e.getModifierState("Meta")) desc.push("Meta");
if (e.key !== 'Unidentified') {
desc.push(e.key);
via = 'e.key' + (e.nativeEvent.key ? '' : ' polyfill');
} else if (e.nativeEvent.keyIdentifier) {
var keyId = e.nativeEvent.keyIdentifier;
if (keyId.substring(0, 2) === 'U+') {
var code = parseInt(keyId.substring(2), 16);
desc.push(String.fromCharCode(code));
} else {
desc.push(keyId);
}
via = 'e.keyIdentifier';
} else if (specials[e.which]) {
desc.push(specials[e.which]);
via = 'e.which + lookup';
} else {
desc.push(String.fromCharCode(e.which));
via = 'e.which';
}
e.persist();
console.log(e);
return '{' + desc.join('+') + '} (' + via + ')';
}
|
javascript
|
{
"resource": ""
}
|
q6662
|
train
|
function (cb) {
var devAttrs = {
transId: null,
lifetime: qn.lifetime,
ip: qn.ip,
version: qn.version
};
qn._update(devAttrs, function (err, rsp) {});
cb(null);
}
|
javascript
|
{
"resource": ""
}
|
|
q6663
|
train
|
function (cb) {
network.get_active_interface(function(err, info) {
if (err)
cb(err);
else
cb(null, info.ip_address);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6664
|
train
|
function (cb) {
network.get_active_interface(function(err, info) {
if (err)
cb(err);
else
cb(null, info.gateway_ip);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q6665
|
compare
|
train
|
function compare(color1, color2, method) {
var methodName = method || 'CIE76Difference';
if (undefined === methods[methodName]) {
throw new Error('Method "' + methodName + '" is unknown. See implemented methods in ./lib/method directory.');
}
/** @type Abstract */
var methodObj = new methods[methodName];
return methodObj.compare(new HexRgb(color1), new HexRgb(color2));
}
|
javascript
|
{
"resource": ""
}
|
q6666
|
inUniqs
|
train
|
function inUniqs (d) {
return uniqs.some(function (u) {
return u.year === d.year && u.month === d.month && u.date === d.date
})
}
|
javascript
|
{
"resource": ""
}
|
q6667
|
clone
|
train
|
function clone(a) {
var out = new Float32Array(9)
out[0] = a[0]
out[1] = a[1]
out[2] = a[2]
out[3] = a[3]
out[4] = a[4]
out[5] = a[5]
out[6] = a[6]
out[7] = a[7]
out[8] = a[8]
return out
}
|
javascript
|
{
"resource": ""
}
|
q6668
|
overrideConfig
|
train
|
function overrideConfig(config) {
if (fs.existsSync(config.config)) {
var content = fs.readFileSync(config.config, {
encoding: "utf8"
});
var configFile = JSON.parse(content);
for (var key in configFile) {
if (configFile.hasOwnProperty(key)) {
config[key] = configFile[key];
}
}
}
return config;
}
|
javascript
|
{
"resource": ""
}
|
q6669
|
check_header
|
train
|
function check_header() {
// PhantomJS doesn't arrow functions.
page.evaluate(function() {
return document.getElementsByClassName("comment-section-header-renderer").length;
}).then((res) => {
if (res != 0) {
resolve();
} else {
setTimeout(check_header, 1000);
}
}).catch(reject);
}
|
javascript
|
{
"resource": ""
}
|
q6670
|
get_or_create
|
train
|
function get_or_create() {
if (locked) {
setTimeout(wait, 100);
} else {
locked = true;
if (phantom_instance != null) {
locked = false;
resolve(phantom_instance);
} else {
phantom.create().then((instance) => {
phantom_instance = instance;
locked = false;
resolve(instance);
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6671
|
TransactionDate
|
train
|
function TransactionDate (dateString, format, options) {
options = options || {}
var parsed = parseDate(dateString, format)
this.year = parsed.year
this.month = parsed.month
this.date = parsed.date
if (!this.year && options.succeedingDate) {
this.year = this.calculateYear(options.succeedingDate)
}
}
|
javascript
|
{
"resource": ""
}
|
q6672
|
searchAndCompare
|
train
|
function searchAndCompare(specObject, comparisonObject, currentDescription) {
if (comparisonObject === undefined) {
comparisonObject = {};
}
for (var key in specObject) {
if (specObject.hasOwnProperty(key)) {
currentDescription.push(key);
if (typeof(specObject[key]) === "string") {
compare(specObject[key], comparisonObject[key], currentDescription);
} else {
searchAndCompare(specObject[key].specs, comparisonObject[key], currentDescription);
}
currentDescription.pop();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6673
|
compare
|
train
|
function compare(specValue, comparisonValue, currentDescription) {
var lengthIndex = currentDescription.length - 1,
suite = currentDescription.slice(0, (lengthIndex)).join(" "),
spec = currentDescription[lengthIndex],
object = {};
if (suite === "") {
object[spec] = specValue;
} else {
object[suite] = {};
object[suite][spec] = specValue;
}
if (typeof(specValue) !== 'undefined' && typeof(comparisonValue) !== 'undefined') {
if (comparisonValue === "PASSED") {
response.passed.push(object);
} else {
response.failed.push(object);
}
} else {
if (config.hint) {
console.log(("ShouldIt? is running in " + config.hint + " hint mode.\n").green);
console.log("One of your features has not been implelented.");
console.log((object[suite][spec] + '\n').grey);
console.log("The recommended test for you to implement is below:\n");
console.log(templates(config.hint, suite, spec).yellow);
console.log("\n");
throw "end";
}
response.pending.push(object);
}
}
|
javascript
|
{
"resource": ""
}
|
q6674
|
compileMesher
|
train
|
function compileMesher(options) {
options = options || {}
if(!options.order) {
throw new Error("greedy-mesher: Missing order field")
}
if(!options.append) {
throw new Error("greedy-mesher: Missing append field")
}
return generateMesher(
options.order,
options.skip,
options.merge,
options.append,
options.extraArgs|0,
options,
!!options.useGetter
)
}
|
javascript
|
{
"resource": ""
}
|
q6675
|
collectResults
|
train
|
function collectResults(resultsGlob) {
var glob = require("glob"),
fs = require("fs"),
Q = require('q'),
JunitConverter = require("./formats/junitConverter"),
response = {},
count = 0,
specs,
files = [],
converter,
result;
for (var i = 0; i < resultsGlob.length; i++) {
files = files.concat(glob.sync(resultsGlob[i]));
}
var converterCallback = function(output) {
result = output;
};
for (i = 0; i < files.length; i++) {
if (files[i].indexOf(".xml") !== -1) {
converter = new JunitConverter(files[i]);
converter.exec(converterCallback);
} else {
try {
result = JSON.parse(fs.readFileSync(files[i]));
} catch (err) {
console.log('Error parsing JSON of ' + files[i]);
result = {};
}
}
response = mergeResults(result, response);
count++;
}
return Q.fcall(function () {
return response;
});
}
|
javascript
|
{
"resource": ""
}
|
q6676
|
mergeResults
|
train
|
function mergeResults(spec, response) {
for (var key in spec) {
if (spec.hasOwnProperty(key)) {
if (!response[key]) {
response[key] = {};
}
for (var test in spec[key]) {
if (spec[key].hasOwnProperty(test)) {
response[key][test] = spec[key][test];
}
}
}
}
return response;
}
|
javascript
|
{
"resource": ""
}
|
q6677
|
fromMat4
|
train
|
function fromMat4(out, a) {
out[0] = a[0]
out[1] = a[1]
out[2] = a[2]
out[3] = a[4]
out[4] = a[5]
out[5] = a[6]
out[6] = a[8]
out[7] = a[9]
out[8] = a[10]
return out
}
|
javascript
|
{
"resource": ""
}
|
q6678
|
frob
|
train
|
function frob(a) {
return Math.sqrt(
a[0]*a[0]
+ a[1]*a[1]
+ a[2]*a[2]
+ a[3]*a[3]
+ a[4]*a[4]
+ a[5]*a[5]
+ a[6]*a[6]
+ a[7]*a[7]
+ a[8]*a[8]
)
}
|
javascript
|
{
"resource": ""
}
|
q6679
|
copy
|
train
|
function copy(target, obj) {
if (isObject(obj)) {
forIn(obj, function(value, key) {
target[key] = value;
});
}
}
|
javascript
|
{
"resource": ""
}
|
q6680
|
sh_mergeTags
|
train
|
function sh_mergeTags(originalTags, highlightTags) {
var numOriginalTags = originalTags.length;
if (numOriginalTags === 0) {
return highlightTags;
}
var numHighlightTags = highlightTags.length;
if (numHighlightTags === 0) {
return originalTags;
}
var result = [];
var originalIndex = 0;
var highlightIndex = 0;
while (originalIndex < numOriginalTags && highlightIndex < numHighlightTags) {
var originalTag = originalTags[originalIndex];
var highlightTag = highlightTags[highlightIndex];
if (originalTag.pos <= highlightTag.pos) {
result.push(originalTag);
originalIndex++;
}
else {
result.push(highlightTag);
if (highlightTags[highlightIndex + 1].pos <= originalTag.pos) {
highlightIndex++;
result.push(highlightTags[highlightIndex]);
highlightIndex++;
}
else {
// new end tag
result.push({pos: originalTag.pos});
// new start tag
highlightTags[highlightIndex] = {node: highlightTag.node.cloneNode(false), pos: originalTag.pos};
}
}
}
while (originalIndex < numOriginalTags) {
result.push(originalTags[originalIndex]);
originalIndex++;
}
while (highlightIndex < numHighlightTags) {
result.push(highlightTags[highlightIndex]);
highlightIndex++;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q6681
|
sh_insertTags
|
train
|
function sh_insertTags(tags, text) {
var doc = document;
var result = document.createDocumentFragment();
var tagIndex = 0;
var numTags = tags.length;
var textPos = 0;
var textLength = text.length;
var currentNode = result;
// output one tag or text node every iteration
while (textPos < textLength || tagIndex < numTags) {
var tag;
var tagPos;
if (tagIndex < numTags) {
tag = tags[tagIndex];
tagPos = tag.pos;
}
else {
tagPos = textLength;
}
if (tagPos <= textPos) {
// output the tag
if (tag.node) {
// start tag
var newNode = tag.node;
currentNode.appendChild(newNode);
currentNode = newNode;
}
else {
// end tag
currentNode = currentNode.parentNode;
}
tagIndex++;
}
else {
// output text
currentNode.appendChild(doc.createTextNode(text.substring(textPos, tagPos)));
textPos = tagPos;
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q6682
|
weld
|
train
|
function weld (keys, values) {
var object = {}
for (var i = keys.length - 1; i >= 0; i--) object[keys[i]] = values[i]
return object
}
|
javascript
|
{
"resource": ""
}
|
q6683
|
Transactions
|
train
|
function Transactions (transactions, statement) {
Transactions._injectPrototypeMethods(transactions)
/**
* Some financial institutions omit the year part in their date cells.
* This workaround calculates the year for each transaction affected.
*/
if (!/Y{2,}/.test(statement.dateFormat)) {
if (!transactions.chronological()) transactions = transactions.reverse()
var succeedingDate = statement.date
for (var i = transactions.length - 1; i >= 0; i--) {
var transaction = transactions[i]
transaction.setDate({ succeedingDate: succeedingDate })
succeedingDate = transaction.get('date')
}
}
return transactions
}
|
javascript
|
{
"resource": ""
}
|
q6684
|
create
|
train
|
function create() {
var out = new Float32Array(9)
out[0] = 1
out[1] = 0
out[2] = 0
out[3] = 0
out[4] = 1
out[5] = 0
out[6] = 0
out[7] = 0
out[8] = 1
return out
}
|
javascript
|
{
"resource": ""
}
|
q6685
|
Log
|
train
|
function Log(properties) {
this.contents = [];
if (properties) {
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) {
if (properties[keys[i]] != null) { this[keys[i]] = properties[keys[i]]; }
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6686
|
LogGroup
|
train
|
function LogGroup(properties) {
this.logs = [];
if (properties) {
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) {
if (properties[keys[i]] != null) { this[keys[i]] = properties[keys[i]]; }
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6687
|
LogGroupList
|
train
|
function LogGroupList(properties) {
this.logGroupList = [];
if (properties) {
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) {
if (properties[keys[i]] != null) { this[keys[i]] = properties[keys[i]]; }
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6688
|
Transaction
|
train
|
function Transaction (attributes) {
this.attributes = {}
for (var key in attributes) {
if (attributes.hasOwnProperty(key)) this.set(key, attributes[key])
}
if (!this.get('date')) this.setDate()
if (!this.get('amount')) this.setAmount()
}
|
javascript
|
{
"resource": ""
}
|
q6689
|
done
|
train
|
function done(err, template) {
// cache
if (options && options.cache && template) {
cache.set(filename, template);
}
if (isAsync) {
callback(err, template);
}
return template;
}
|
javascript
|
{
"resource": ""
}
|
q6690
|
buildTemplate
|
train
|
function buildTemplate(filename, options, callback) {
var isAsync = callback && typeof callback === 'function',
getTemplateContentFn = options.getTemplate && typeof options.getTemplate === 'function' ? options.getTemplate : getTemplateContentFromFile;
// sync
if (!isAsync) {
return builtTemplateFromString(
getTemplateContentFn(filename, options),
filename,
options
);
}
// function to call when retrieved template content
function done(err, templateText) {
callback(err, builtTemplateFromString(templateText, filename, options));
}
getTemplateContentFn(filename, options, done);
}
|
javascript
|
{
"resource": ""
}
|
q6691
|
getTemplateContentFromFile
|
train
|
function getTemplateContentFromFile(filename, options, callback) {
var isAsync = callback && typeof callback === 'function';
// sync
if (!isAsync) {
return fs.readFileSync(filename, 'utf8');
}
// async
fs.readFile(filename, 'utf8', function(err, str) {
if (err) {
callback(new Error('Failed to open view file (' + filename + ')'));
return;
}
try {
callback(null, str);
}
catch (err) {
callback(err);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q6692
|
builtTemplateFromString
|
train
|
function builtTemplateFromString(str, filename, options) {
try {
var config = {};
// config at the beginning of the file
str.replace(settings.config, function(m, conf) {
config = yaml.safeLoad(conf);
});
// strip comments
if (settings.stripComment) {
str = str.replace(settings.comment, function(m, code, assign, value) {
return '';
});
}
// strip whitespace
if (settings.stripWhitespace) {
settings.dot.strip = settings.stripWhitespace;
}
// layout sections
var sections = {};
if (!config.layout) {
sections.body = str;
}
else {
str.replace(settings.dot.define, function(m, code, assign, value) {
sections[code] = value;
});
}
var templateSettings = _.pick(options, ['settings']);
options.getTemplate && (templateSettings.getTemplate = options.getTemplate);
return new Template({
express: templateSettings,
config: config,
sections: sections,
dirname: path.dirname(filename),
filename: filename
});
}
catch (err) {
throw new Error(
'Failed to build template' +
' (' + filename + ')' +
' - ' + err.toString()
);
}
}
|
javascript
|
{
"resource": ""
}
|
q6693
|
renderSync
|
train
|
function renderSync(filename, options) {
var template = getTemplate(filename, options);
return template.render({ model: options, });
}
|
javascript
|
{
"resource": ""
}
|
q6694
|
renderString
|
train
|
function renderString(templateString, options, callback) {
var template = builtTemplateFromString(templateString, '', options);
return template.render({ model: options, }, callback);
}
|
javascript
|
{
"resource": ""
}
|
q6695
|
run
|
train
|
function run(config) {
var specCollector = require('./specCollector'),
resultCollector = require('./resultCollector'),
inspector = require('./inspector'),
spitterOuter = require('./spitterOuter'),
summariser = require('./summariser'),
XmlWriter = require('./junitXmlWriter'),
fs = require('fs'),
prepareNodeData = require('./visualiser/prepareNodeData'),
allSpecs;
function outputFileComparison(specs, results) {
/**
* Use the collector to get the content of each file
*/
var files = [specs, results];
try {
results = inspector(files, config);
var writer = new XmlWriter(config);
writer.writeResults(results);
var output = spitterOuter(results, config);
output.forEach(function(line) {
console.log(line);
});
if (config.outputSummary) {
var summary = summariser(results);
summary.forEach(function(summaryItem) {
console.log(summaryItem);
});
}
prepareNodeData(config, files);
} catch (e) {
if (config.watch) {
console.log("Still watching... carry on BDD'ing!");
}
}
}
function collectResults(specs) {
allSpecs = specs;
return resultCollector(config.results);
}
function compareOutputFiles(results) {
outputFileComparison(allSpecs, results);
}
/**
* Get the specs from the spec collector
*/
specCollector(config.specs, config.tags)
.then(collectResults)
.then(compareOutputFiles);
}
|
javascript
|
{
"resource": ""
}
|
q6696
|
getIn
|
train
|
function getIn(record, accessor, ctx) {
var v = record;
var keys = getPathKeys(accessor, ctx);
if (utils_1.isFn(record.getIn)) {
return record.getIn(keys);
}
var len = keys.length;
for (var i = 0; i < len; i++) {
var key = keys[i];
v = utils_1.isObj(v)
? utils_1.isFn(v.get)
? v.get(key)
: v[key]
: undefined;
}
return v;
}
|
javascript
|
{
"resource": ""
}
|
q6697
|
setIn
|
train
|
function setIn(record, accessor, value, ctx) {
return mutate(record, accessor, MutateType.setIn, value, ctx);
}
|
javascript
|
{
"resource": ""
}
|
q6698
|
unsetIn
|
train
|
function unsetIn(record, accessor, ctx) {
return mutate(record, accessor, MutateType.setIn, void 0, ctx);
}
|
javascript
|
{
"resource": ""
}
|
q6699
|
updateIn
|
train
|
function updateIn(record, accessor, updator, ctx) {
if (!updator) {
return record;
}
return mutate(record, accessor, MutateType.updateIn, updator, ctx);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.