_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q12900
|
isUnreserved
|
train
|
function isUnreserved (chr) {
return charHelper.isAlpha(chr) || charHelper.isDigit(chr) || chr === '-' || chr === '.' || chr === '_' || chr === '~';
}
|
javascript
|
{
"resource": ""
}
|
q12901
|
isReserved
|
train
|
function isReserved (chr) {
return chr === ':' || chr === '/' || chr === '?' || chr === '#' || chr === '[' || chr === ']' || chr === '@' || chr === '!' || chr === '$' || chr === '&' || chr === '(' ||
chr === ')' || chr === '*' || chr === '+' || chr === ',' || chr === ';' || chr === '=' || chr === "'";
}
|
javascript
|
{
"resource": ""
}
|
q12902
|
sort
|
train
|
function sort(array, compare, swap) {
var pos = 1;
while (pos < array.length) {
if (compare(array, pos, pos - 1) >= 0) {
pos++;
} else {
swap(array, pos, pos - 1);
if (pos > 1) {
pos--;
}
}
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
q12903
|
respond
|
train
|
function respond(res, code, data) {
return res.status(code).send(data || http.STATUS_CODES[code]);
}
|
javascript
|
{
"resource": ""
}
|
q12904
|
sort
|
train
|
function sort(array, compare) {
for (var i = 1; i < array.length; i++) {
var item = array[i];
var indexHole = i;
while (indexHole > 0 && compare(array[indexHole - 1], item) > 0) {
array[indexHole] = array[--indexHole];
}
array[indexHole] = item;
if (sortExternal.shiftObserver) {
sortExternal.shiftObserver(i, indexHole);
}
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
q12905
|
bottomUpMerge
|
train
|
function bottomUpMerge(
array, leftPosition, chunkSize, workArray, compare) {
var i;
var rightPosition = leftPosition + chunkSize;
var endPosition = Math.min(leftPosition + chunkSize * 2 - 1,
array.length - 1);
var leftIndex = leftPosition;
var rightIndex = rightPosition;
for (i = 0; i <= endPosition - leftPosition; i++) {
if (leftIndex < rightPosition &&
(rightIndex > endPosition ||
compare(array[leftIndex], array[rightIndex]) <= 0)) {
workArray[i] = array[leftIndex++];
} else {
workArray[i] = array[rightIndex++];
}
}
for (i = leftPosition; i <= endPosition; i++) {
array[i] = workArray[i - leftPosition];
}
}
|
javascript
|
{
"resource": ""
}
|
q12906
|
sort
|
train
|
function sort(array, compare) {
var workArray = new Array(array.length);
var chunkSize = 1;
while (chunkSize < array.length) {
var i = 0;
while (i < array.length - chunkSize) {
bottomUpMerge(array, i, chunkSize, workArray, compare);
i += chunkSize * 2;
}
chunkSize *= 2;
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
q12907
|
createRelationships
|
train
|
function createRelationships(rhapsodyApp) {
var relationshipModel,
relationshipName,
relationship,
relatedModel;
this.relationships = this.relationships || {};
for(relationshipName in this.relationships) {
relationship = this.relationships[relationshipName];
//If it's a valid relationship
if(this.serverModel[relationship.type]) {
relatedModel = rhapsodyApp.requireModel(relationship['with']);
//If the user sets the relationship model, pass it
//otherwise, just pass false and JugglingDB will generate it
relationshipModel = rhapsodyApp.requireModel(relationship.through);
//If the related model actually exists
if(relatedModel) {
//Creates the relationship with JugglingDB API
if(relationship.type === 'hasAndBelongsToMany') {
this.serverModel.hasAndBelongsToMany(relationshipName, {
model: relatedModel,
through: relationshipModel
});
}
else {
this.serverModel[relationship.type](relatedModel, {
as: relationshipName,
foreignKey: relationship.foreignKey
});
}
}
else {
utils.Logger.error('Relationship error', '"' + relationship['with'] + '" related with "' + this.name + '" does not exist.');
}
}
else {
utils.Logger.error('Relationship error', relationship.type + ' in "' + this.name + '" is not a valid relationship');
}
}
}
|
javascript
|
{
"resource": ""
}
|
q12908
|
ownerDocument
|
train
|
function ownerDocument(componentOrElement) {
var elem = ReactDOM.findDOMNode(componentOrElement);
return elem && elem.ownerDocument || document;
}
|
javascript
|
{
"resource": ""
}
|
q12909
|
isNodeInRoot
|
train
|
function isNodeInRoot(node, root) {
node = ReactDOM.findDOMNode(node), root = ReactDOM.findDOMNode(root);
return _isNodeInRoot(node, root);
}
|
javascript
|
{
"resource": ""
}
|
q12910
|
Class
|
train
|
function Class(name, definition, parent) {
// Argument shifting.
if (typeof name == 'function') {
parent = definition;
definition = name;
name = null;
}
this.definition = definition;
this.parent = parent;
// Create the constructor, add some methods to it, and store the association.
this.Ctor = createConstructor(name);
this.Ctor.subclass = subclass;
this.Ctor.final = final;
constructorToClassMap.set(this.Ctor, this);
this._setupInheritance();
this._storeSecrets();
this._makeAccessors();
}
|
javascript
|
{
"resource": ""
}
|
q12911
|
protectedFactory
|
train
|
function protectedFactory(instance) {
var publicPrototype = Object.getPrototypeOf(instance);
var protectedPrototype = protectToPrototypeMap.get(publicPrototype);
if (!protectedPrototype) {
throw new Error('The protected key function only accepts instances '
+ 'of objects created using Mozart constructors.'
);
}
return Object.create(protectedPrototype);
}
|
javascript
|
{
"resource": ""
}
|
q12912
|
sort
|
train
|
function sort(array, compare, swap) {
var start = -1;
var end = array.length - 2;
var swapped;
var i;
do {
swapped = false;
for (i = ++start; i <= end; i++) {
if (compare(array, i, i + 1) > 0) {
swap(array, i, i + 1);
swapped = true;
}
}
if (!swapped) {
break;
}
swapped = false;
for (i = --end; i >= start; i--) {
if (compare(array, i, i + 1) > 0) {
swap(array, i, i + 1);
swapped = true;
}
}
} while (swapped);
return array;
}
|
javascript
|
{
"resource": ""
}
|
q12913
|
hasher
|
train
|
function hasher(opts, callback) {
if (typeof opts.password !== 'string') {
passNeeded(opts, callback);
} else if (typeof opts.salt !== 'string') {
saltNeeded(opts, callback);
} else {
opts.salt = new Buffer(opts.salt, 'base64');
genHash(opts, callback);
}
}
|
javascript
|
{
"resource": ""
}
|
q12914
|
genPass
|
train
|
function genPass(opts, cb) {
// generate a 10-bytes password
crypto.randomBytes(10, function(err, buffer) {
if (buffer) {
opts.password = buffer.toString("base64");
}
cb(err, opts);
});
}
|
javascript
|
{
"resource": ""
}
|
q12915
|
genSalt
|
train
|
function genSalt(opts, cb) {
crypto.randomBytes(saltLength, function(err, buf) {
opts.salt = buf;
cb(err, opts);
});
}
|
javascript
|
{
"resource": ""
}
|
q12916
|
genHashWithDigest
|
train
|
function genHashWithDigest(opts, cb) {
crypto.pbkdf2(opts.password, opts.salt, iterations, keyLength, digest, function(err, hash) {
if (typeof hash === 'string') {
hash = new Buffer(hash, 'binary');
}
cb(err, opts.password, opts.salt.toString("base64"), hash.toString("base64"));
});
}
|
javascript
|
{
"resource": ""
}
|
q12917
|
sort
|
train
|
function sort(array, bucketSize) {
if (array.length === 0) {
return array;
}
// Determine minimum and maximum values
var i;
var minValue = array[0];
var maxValue = array[0];
for (i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
} else if (array[i] > maxValue) {
maxValue = array[i];
}
}
// Initialise buckets
var DEFAULT_BUCKET_SIZE = 5;
bucketSize = bucketSize || DEFAULT_BUCKET_SIZE;
var bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1;
var buckets = new Array(bucketCount);
for (i = 0; i < buckets.length; i++) {
buckets[i] = [];
}
// Distribute input array values into buckets
for (i = 0; i < array.length; i++) {
buckets[Math.floor((array[i] - minValue) / bucketSize)].push(array[i]);
}
// Sort buckets and place back into input array
array.length = 0;
for (i = 0; i < buckets.length; i++) {
insertionSort(buckets[i]);
for (var j = 0; j < buckets[i].length; j++) {
array.push(buckets[i][j]);
}
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
q12918
|
newSubschemaContext
|
train
|
function newSubschemaContext(defaultLoaders = [], defaultResolvers = {}, defaultPropTypes = PropTypes, defaultInjectorFactory = injectorFactory, Subschema = {
Conditional,
Field,
FieldSet,
RenderContent,
RenderTemplate,
Form,
NewChildContext,
Dom,
PropTypes,
ValueManager,
css,
eventable,
loaderFactory,
tutils,
validators,
warning,
injectorFactory,
cachedInjector,
stringInjector
}) {
const {loader, injector, ...rest} = Subschema;
const _injector = defaultInjectorFactory();
for (let key of Object.keys(defaultResolvers)) {
if (key in defaultPropTypes) {
_injector.resolver(defaultPropTypes[key], defaultResolvers[key]);
}
}
const defaultLoader = loaderFactory(defaultLoaders);
const defaultInjector = cachedInjector(stringInjector(_injector, defaultPropTypes));
//Form needs these to kick off the whole thing. Its defaults can be overriden with
// properties.
rest.Form.defaultProps.loader = defaultLoader;
rest.Form.defaultProps.injector = defaultInjector;
rest.loader = defaultLoader;
rest.injector = defaultInjector;
return rest;
}
|
javascript
|
{
"resource": ""
}
|
q12919
|
Rhapsody
|
train
|
function Rhapsody(options) {
//Expose object as global
//Should fix it latter
global.Rhapsody = this;
this.options = options;
this.root = options.root;
//Libs used internally that the programmer can access
this.libs = {
express: require('express'),
jsmin: require('jsmin').jsmin,
lodash: require('lodash'),
wolverine: require('wolverine')
};
this.config = require(path.join(this.root, '/app/config/config'));
//Get the general environment settings
this.config = this.libs.lodash.merge(this.config, require(path.join(this.root, '/app/config/envs/all')));
//Overwrite it with the defined environment settings
this.config = this.libs.lodash.merge(this.config, require(path.join(this.root, '/app/config/envs/' + this.config.environment)));
//Then extends it with the other settings
var loadConfig = require('./rhapsody/app/config');
this.config = this.libs.lodash.merge(this.config, loadConfig(options));
return this;
}
|
javascript
|
{
"resource": ""
}
|
q12920
|
requireModel
|
train
|
function requireModel(modelName, full) {
if(!modelName) {
return false;
}
var model = this.models[modelName];
if(full) {
return (model ? model : false);
}
return (model ? model.serverModel : false);
}
|
javascript
|
{
"resource": ""
}
|
q12921
|
onlineMessage
|
train
|
function onlineMessage() {
_this.showLogo();
var httpPort = _this.config.http.port;
Logger.info('Listening HTTP on port ' + httpPort);
if(_this.config.https.enabled) {
var httpsPort = _this.config.https.port;
Logger.info('Listening HTTPS on port ' + httpsPort);
}
}
|
javascript
|
{
"resource": ""
}
|
q12922
|
nextFunc
|
train
|
function nextFunc(f1, f2) {
if (f1 && !f2) return f1;
if (f2 && !f1) return f2;
return function nextFunc$wrapper(...args) {
if (f1.apply(this, args) !== false) {
return f2.apply(this, args);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q12923
|
clean
|
train
|
function clean(parts) {
var p = '';
for (var i = 0; i < parts.length; i += 3) {
p += parts[i] || '';
}
return p;
}
|
javascript
|
{
"resource": ""
}
|
q12924
|
train
|
function (x) {
var i = indexOf.call(k, x);
k.splice(i, 1);
v.splice(i, 1);
}
|
javascript
|
{
"resource": ""
}
|
|
q12925
|
drop
|
train
|
function drop(type, callback) {
if (arguments.length === 1)
delete _[type];
else {
var fn = wm.get(callback), cb, i;
if (fn) {
wm['delete'](callback);
drop(type, fn);
} else {
cb = get(type).cb;
i = indexOf.call(cb, callback);
if (~i) cb.splice(i, 1);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q12926
|
all
|
train
|
function all(type, callback) {
if (!wm.get(callback)) {
wm.set(callback, function fn() {
invoke = false;
when(type, fn);
invoke = true;
resolve(arguments).then(bind.call(broadcast, callback));
});
when(type, wm.get(callback));
}
}
|
javascript
|
{
"resource": ""
}
|
q12927
|
getModel
|
train
|
function getModel(req, res, next, model) {
var fullModel = Rhapsody.requireModel(model, true);
if(!fullModel) {
Rhapsody.log.verbose('Nonexistent model', 'Couldn\'t find collection %s.', model);
return responseUtils.respond(res, 400); //Malformed syntax or a bad query
}
//This model does not allow REST API
if(!fullModel.options.allowREST) {
return responseUtils.respond(res, 404);
}
req.fullModel = fullModel;
next();
}
|
javascript
|
{
"resource": ""
}
|
q12928
|
train
|
function(req, res, next, relationship) {
if(req.fullModel.hasRelationship(relationship)) {
return next();
}
return responseUtils.respond(res, 400); //Malformed syntax or a bad query
}
|
javascript
|
{
"resource": ""
}
|
|
q12929
|
bindMiddlewares
|
train
|
function bindMiddlewares() {
var modelName,
_this = this;
for(modelName in Rhapsody.models) {
(function(model) {
model.options.middlewares.forEach(function(middleware) {
if(typeof middleware !== 'function') {
middleware = require(path.join(Rhapsody.root, '/app/middlewares/' + middleware));
}
modelName = '/' + modelName;
_this.router.post(modelName, middleware);
_this.router.post(modelName + '/:id/:relationship', middleware);
_this.router.get(modelName + '/:id?', middleware);
_this.router.get(modelName + '/:id/:relationship', middleware);
_this.router.put(modelName + '/:id', middleware);
_this.router.patch(modelName + '/:id', middleware);
_this.router.delete(modelName + '/:id', middleware);
});
}(Rhapsody.models[modelName]));
}
}
|
javascript
|
{
"resource": ""
}
|
q12930
|
train
|
function (e, errors, value, path) {
var parts = path && path.split('.') || [], i = 0, l = parts.length, pp = null;
do {
if (this.submitListeners.some(v=> {
if (v.path === pp) {
return (v.listener.call(v.scope, e, errors, value, path) === false);
}
}, this) === true) {
return false
}
pp = tpath(pp, parts[i]);
} while (i++ < l);
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q12931
|
heapify
|
train
|
function heapify(array, heapSize, i, compare, swap) {
var left = i * 2 + 1;
var right = i * 2 + 2;
var largest = i;
if (left < heapSize && compare(array, left, largest) > 0) {
largest = left;
}
if (right < heapSize && compare(array, right, largest) > 0) {
largest = right;
}
if (largest !== i) {
swap(array, i, largest);
heapify(array, heapSize, largest, compare, swap);
}
}
|
javascript
|
{
"resource": ""
}
|
q12932
|
buildHeap
|
train
|
function buildHeap(array, heapSize, compare, swap) {
for (var i = Math.floor(array.length / 2); i >= 0; i--) {
heapify(array, heapSize, i, compare, swap);
}
}
|
javascript
|
{
"resource": ""
}
|
q12933
|
sort
|
train
|
function sort(array, compare, swap) {
var heapSize = array.length;
buildHeap(array, heapSize, compare, swap);
while (heapSize > 1) {
swap(array, 0, --heapSize);
heapify(array, heapSize, 0, compare, swap);
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
q12934
|
exposeNative
|
train
|
function exposeNative(Browser, command, exposed) {
if (_.isNumber(exposed)) {
exposed = command;
}
Browser.prototype[exposed] = function () {
ensureDriverCommand.call(this, command, 'exposeNative');
var args = wrapArguments.call(this, arguments, errorToExceptionCallback);
this._driver[command].apply(this._driver, args);
return this;
};
}
|
javascript
|
{
"resource": ""
}
|
q12935
|
sort
|
train
|
function sort(array, compare, swap) {
var gap = array.length;
var shrinkFactor = 1.3;
var swapped;
while (gap > 1 || swapped) {
if (gap > 1) {
gap = Math.floor(gap / shrinkFactor);
}
swapped = false;
for (var i = 0; gap + i < array.length; ++i) {
if (compare(array, i, i + gap) > 0) {
swap(array, i, i + gap);
swapped = true;
}
}
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
q12936
|
innerSort
|
train
|
function innerSort(array, i, compare, swap) {
var sorted = true;
for (; i < array.length - 1; i += 2) {
if (compare(array, i, i + 1) > 0) {
swap(array, i, i + 1);
sorted = false;
}
}
return sorted;
}
|
javascript
|
{
"resource": ""
}
|
q12937
|
sort
|
train
|
function sort(array, compare, swap) {
var sorted = false;
while (!sorted) {
sorted = innerSort(array, 1, compare, swap);
sorted = innerSort(array, 0, compare, swap) && sorted;
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
q12938
|
errorToExceptionCallback
|
train
|
function errorToExceptionCallback(cb) {
var browser = this;
return function errorWrapped(err) {
if (err) throw err;
if (cb) {
cb.apply(browser, _.tail(arguments));
}
};
}
|
javascript
|
{
"resource": ""
}
|
q12939
|
exposeThenNative
|
train
|
function exposeThenNative(Browser, command) {
var exposed = ['then', ucfirst(command)].join('');
Browser.prototype[exposed] = function () {
var args = arguments;
ensureDriverCommand.call(this, command, 'exposeThenNative');
this.then(function (next) {
args = wrapArguments.call(this, args, chainAndErrorCallback, next);
this._driver[command].apply(this._driver, args);
});
return this;
};
}
|
javascript
|
{
"resource": ""
}
|
q12940
|
countingSortByDigit
|
train
|
function countingSortByDigit(array, radix, exponent, minValue) {
var i;
var bucketIndex;
var buckets = new Array(radix);
var output = new Array(array.length);
// Initialize bucket
for (i = 0; i < radix; i++) {
buckets[i] = 0;
}
// Count frequencies
for (i = 0; i < array.length; i++) {
bucketIndex = Math.floor(((array[i] - minValue) / exponent) % radix);
buckets[bucketIndex]++;
}
// Compute cumulates
for (i = 1; i < radix; i++) {
buckets[i] += buckets[i - 1];
}
// Move records
for (i = array.length - 1; i >= 0; i--) {
bucketIndex = Math.floor(((array[i] - minValue) / exponent) % radix);
output[--buckets[bucketIndex]] = array[i];
}
// Copy back
for (i = 0; i < array.length; i++) {
array[i] = output[i];
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
q12941
|
sort
|
train
|
function sort(array, radix) {
if (array.length === 0) {
return array;
}
radix = radix || 10;
// Determine minimum and maximum values
var minValue = array[0];
var maxValue = array[0];
for (var i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
} else if (array[i] > maxValue) {
maxValue = array[i];
}
}
// Perform counting sort on each exponent/digit, starting at the least
// significant digit
var exponent = 1;
while ((maxValue - minValue) / exponent >= 1) {
array = countingSortByDigit(array, radix, exponent, minValue);
exponent *= radix;
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
q12942
|
partitionRandom
|
train
|
function partitionRandom(array, left, right, compare, swap) {
var pivot = left + Math.floor(Math.random() * (right - left));
if (pivot !== right) {
swap(array, right, pivot);
}
return partitionRight(array, left, right, compare, swap);
}
|
javascript
|
{
"resource": ""
}
|
q12943
|
partitionRight
|
train
|
function partitionRight(array, left, right, compare, swap) {
var mid = left;
for (var i = mid; i < right; i++) {
if (compare(array, i, right) <= 0) {
if (i !== mid) {
swap(array, i, mid);
}
mid++;
}
}
if (right !== mid) {
swap(array, right, mid);
}
return mid;
}
|
javascript
|
{
"resource": ""
}
|
q12944
|
train
|
function(word,iteration)
{
/* rotate the 32-bit word 8 bits to the left */
word = this.rotate(word);
/* apply S-Box substitution on all 4 parts of the 32-bit word */
for (var i = 0; i < 4; ++i)
word[i] = this.sbox[word[i]];
/* XOR the output of the rcon operation with i to the first part (leftmost) only */
word[0] = word[0]^this.Rcon[iteration];
return word;
}
|
javascript
|
{
"resource": ""
}
|
|
q12945
|
train
|
function(expandedKey,roundKeyPointer)
{
var roundKey = [];
for (var i = 0; i < 4; i++)
for (var j = 0; j < 4; j++)
roundKey[j*4+i] = expandedKey[roundKeyPointer + i*4 + j];
return roundKey;
}
|
javascript
|
{
"resource": ""
}
|
|
q12946
|
train
|
function(a,b)
{
var p = 0;
for(var counter = 0; counter < 8; counter++)
{
if((b & 1) == 1)
p ^= a;
if(p > 0x100) p ^= 0x100;
var hi_bit_set = (a & 0x80); //keep p 8 bit
a <<= 1;
if(a > 0x100) a ^= 0x100; //keep a 8 bit
if(hi_bit_set == 0x80)
a ^= 0x1b;
if(a > 0x100) a ^= 0x100; //keep a 8 bit
b >>= 1;
if(b > 0x100) b ^= 0x100; //keep b 8 bit
}
return p;
}
|
javascript
|
{
"resource": ""
}
|
|
q12947
|
train
|
function(state,isInv)
{
var column = [];
/* iterate over the 4 columns */
for (var i = 0; i < 4; i++)
{
/* construct one column by iterating over the 4 rows */
for (var j = 0; j < 4; j++)
column[j] = state[(j*4)+i];
/* apply the mixColumn on one column */
column = this.mixColumn(column,isInv);
/* put the values back into the state */
for (var k = 0; k < 4; k++)
state[(k*4)+i] = column[k];
}
return state;
}
|
javascript
|
{
"resource": ""
}
|
|
q12948
|
train
|
function(column,isInv)
{
var mult = [];
if(isInv)
mult = [14,9,13,11];
else
mult = [2,1,1,3];
var cpy = [];
for(var i = 0; i < 4; i++)
cpy[i] = column[i];
column[0] = this.galois_multiplication(cpy[0],mult[0]) ^
this.galois_multiplication(cpy[3],mult[1]) ^
this.galois_multiplication(cpy[2],mult[2]) ^
this.galois_multiplication(cpy[1],mult[3]);
column[1] = this.galois_multiplication(cpy[1],mult[0]) ^
this.galois_multiplication(cpy[0],mult[1]) ^
this.galois_multiplication(cpy[3],mult[2]) ^
this.galois_multiplication(cpy[2],mult[3]);
column[2] = this.galois_multiplication(cpy[2],mult[0]) ^
this.galois_multiplication(cpy[1],mult[1]) ^
this.galois_multiplication(cpy[0],mult[2]) ^
this.galois_multiplication(cpy[3],mult[3]);
column[3] = this.galois_multiplication(cpy[3],mult[0]) ^
this.galois_multiplication(cpy[2],mult[1]) ^
this.galois_multiplication(cpy[1],mult[2]) ^
this.galois_multiplication(cpy[0],mult[3]);
return column;
}
|
javascript
|
{
"resource": ""
}
|
|
q12949
|
train
|
function(state, roundKey)
{
state = this.subBytes(state,false);
state = this.shiftRows(state,false);
state = this.mixColumns(state,false);
state = this.addRoundKey(state, roundKey);
return state;
}
|
javascript
|
{
"resource": ""
}
|
|
q12950
|
train
|
function(state,roundKey)
{
state = this.shiftRows(state,true);
state = this.subBytes(state,true);
state = this.addRoundKey(state, roundKey);
state = this.mixColumns(state,true);
return state;
}
|
javascript
|
{
"resource": ""
}
|
|
q12951
|
train
|
function(input,key,size)
{
var output = [];
var block = []; /* the 128 bit block to encode */
var nbrRounds = this.numberOfRounds(size);
/* Set the block values, for the block:
* a0,0 a0,1 a0,2 a0,3
* a1,0 a1,1 a1,2 a1,3
* a2,0 a2,1 a2,2 a2,3
* a3,0 a3,1 a3,2 a3,3
* the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3
*/
for (var i = 0; i < 4; i++) /* iterate over the columns */
for (var j = 0; j < 4; j++) /* iterate over the rows */
block[(i+(j*4))] = input[(i*4)+j];
/* expand the key into an 176, 208, 240 bytes key */
var expandedKey = this.expandKey(key, size); /* the expanded key */
/* encrypt the block using the expandedKey */
block = this.main(block, expandedKey, nbrRounds);
for (var k = 0; k < 4; k++) /* unmap the block again into the output */
for (var l = 0; l < 4; l++) /* iterate over the rows */
output[(k*4)+l] = block[(k+(l*4))];
return output;
}
|
javascript
|
{
"resource": ""
}
|
|
q12952
|
train
|
function(s1, s2) {
var n = s1.length;
if (s1.length > s2.length) n = s2.length;
for (var i = 0; i < n; i++) {
if (s1.charCodeAt(i) != s2.charCodeAt(i)) return i;
}
if (s1.length != s2.length) return n;
return -1; // same
}
|
javascript
|
{
"resource": ""
}
|
|
q12953
|
_rsapem_privateKeyToPkcs1HexString
|
train
|
function _rsapem_privateKeyToPkcs1HexString(rsaKey) {
var result = _rsapem_derEncodeNumber(0);
result += _rsapem_derEncodeNumber(rsaKey.n);
result += _rsapem_derEncodeNumber(rsaKey.e);
result += _rsapem_derEncodeNumber(rsaKey.d);
result += _rsapem_derEncodeNumber(rsaKey.p);
result += _rsapem_derEncodeNumber(rsaKey.q);
result += _rsapem_derEncodeNumber(rsaKey.dmp1);
result += _rsapem_derEncodeNumber(rsaKey.dmq1);
result += _rsapem_derEncodeNumber(rsaKey.coeff);
var fullLen = _rsapem_encodeLength(result.length / 2);
return '30' + fullLen + result;
}
|
javascript
|
{
"resource": ""
}
|
q12954
|
_rsapem_publicKeyToX509HexString
|
train
|
function _rsapem_publicKeyToX509HexString(rsaKey) {
var encodedIdentifier = "06092A864886F70D010101";
var encodedNull = "0500";
var headerSequence = "300D" + encodedIdentifier + encodedNull;
var keys = _rsapem_derEncodeNumber(rsaKey.n);
keys += _rsapem_derEncodeNumber(rsaKey.e);
var keySequence = "0030" + _rsapem_encodeLength(keys.length / 2) + keys;
var bitstring = "03" + _rsapem_encodeLength(keySequence.length / 2) + keySequence;
var mainSequence = headerSequence + bitstring;
return "30" + _rsapem_encodeLength(mainSequence.length / 2) + mainSequence;
}
|
javascript
|
{
"resource": ""
}
|
q12955
|
sort
|
train
|
function sort(array, compare, swap) {
for (var i = 0; i < array.length - 1; i++) {
var minIndex = i;
for (var j = i + 1; j < array.length; j++) {
if (compare(array, j, minIndex) < 0) {
minIndex = j;
}
}
if (minIndex !== i) {
swap(array, i, minIndex);
}
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
q12956
|
train
|
function(tree, options) {
let list = [];
const stack = [];
console.log(tree);
const _tree = _.cloneDeep(tree);
const settings = {
initNode: options.initNode || (node => node),
itemsKey: options.itemsKey || 'children',
idKey: options.idKey || 'id',
uniqueIdStart: options.uniqueIdStart || 1,
generateUniqueId: options.generateUniqueId ||
(() => settings.uniqueIdStart++),
};
if (Array.isArray(_tree) && _tree.length) {
// Object Array
for (let i = 0, len = _tree.length; i < len; i++) {
stack.push(
flattenNodeGenerator(
_tree[i],
'root', // placeholder
i,
settings,
stack
)
);
}
} else {
// One object tree
stack.push(flattenNodeGenerator(_tree, 'root', 0, settings, stack));
}
while (stack.length) {
list = stack.shift()(list);
}
return list;
}
|
javascript
|
{
"resource": ""
}
|
|
q12957
|
train
|
function(options) {
options = options || {};
this.path = PATH.resolve(PATH.normalize(options.path));
this.exists = FS.existsSync(this.path);
this.umask = 'umask' in options ? options.umask : File.UMASK;
if (this.exists) {
this.stats = this.getStats();
this.type = this.getType();
this.mode = this.stats.mode & 511; // 511 == 0777
this.uid = this.stats.uid;
this.gid = this.stats.gid;
}
else {
this.owner = options.owner;
this.group = options.group;
if ('exists' in options && options.exists) {
throw new File.FileMissingException('File was expected to exist, but does not.');
}
if ('type' in options) {
if (options.type in File.Types) {
this.type = File.Types[options.type];
}
else {
throw new File.UnknownFileTypeException('Unknown file type: ' + options.type + '.');
}
}
else {
throw new File.MissingRequiredParameterException('"type" is required for nonexistent files.');
}
switch (this.type) {
case File.Types.file:
this.content = 'content' in options ? options.content : '';
break;
case File.Types.symlink:
if ('dest' in options) {
this.dest = options.dest;
}
else {
throw new File.MissingRequiredParameterException('"dest" is a required option for symlink files.');
}
break;
}
this.mode = File.interpretMode(options.mode, options.type, this.umask);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12958
|
sort
|
train
|
function sort(array, compare) {
if (array.length <= 1) {
return array;
}
var i;
var middle = Math.floor(array.length / 2);
var left = new Array(middle);
var right = new Array(array.length - middle);
for (i = 0; i < left.length; i++) {
left[i] = array[i];
}
for (i = 0; i < right.length; i++) {
right[i] = array[i + left.length];
}
return merge(sort(left, compare), sort(right, compare), compare);
}
|
javascript
|
{
"resource": ""
}
|
q12959
|
merge
|
train
|
function merge(left, right, compare) {
var result = [];
var leftIndex = 0;
var rightIndex = 0;
while (leftIndex < left.length || rightIndex < right.length) {
if (leftIndex < left.length && rightIndex < right.length) {
if (compare(left[leftIndex], right[rightIndex]) <= 0) {
result.push(left[leftIndex++]);
} else {
result.push(right[rightIndex++]);
}
} else if (leftIndex < left.length) {
result.push(left[leftIndex++]);
} else if (rightIndex < right.length) {
result.push(right[rightIndex++]);
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q12960
|
exposeThenSelector
|
train
|
function exposeThenSelector(Browser, command, exposed) {
if (_.isNumber(exposed)) {
exposed = command;
}
exposed = ['then', ucfirst(exposed)].join('');
Browser.prototype[exposed] = function () {
var args = arguments;
ensureDriverCommand.call(this, command, 'exposeThenSelector');
this.then(function (next) {
args = wrapArguments.call(this, args, chainAndErrorCallback, next);
args = wrapSelectorArguments(args);
this._driver[command].apply(this._driver, args);
});
return this;
};
}
|
javascript
|
{
"resource": ""
}
|
q12961
|
_fillInputText
|
train
|
function _fillInputText(element, value, next) {
var onFilled = chainAndErrorCallback.call(this, null, next);
var onClear = chainAndErrorCallback.call(this, function () {
element.type(value || '', onFilled);
}, onFilled);
element.clear(onClear);
}
|
javascript
|
{
"resource": ""
}
|
q12962
|
_fillInputFile
|
train
|
function _fillInputFile(element, value, next) {
var onUploadDone = function (localPath) {
element.type(localPath, next);
};
this.uploadFile(value, onUploadDone);
}
|
javascript
|
{
"resource": ""
}
|
q12963
|
_fillInputCheckbox
|
train
|
function _fillInputCheckbox(element, value, next) {
var onIsSelected = chainAndErrorCallback.call(this, function (selected, next) {
//ensure boolean
value = !!value;
if (value === selected) {
// nothing to do
return next();
}
element.click(next);
}, next);
element.isSelected(onIsSelected);
}
|
javascript
|
{
"resource": ""
}
|
q12964
|
_fillInputRadio
|
train
|
function _fillInputRadio(name, value, next) {
this.element({
value: "//input[@name='"+escapeString(name, "'")+"' and @value='"+escapeString(value, "'")+"']",
strategy: "xpath"
}, function (el) {
el.click(next);
});
}
|
javascript
|
{
"resource": ""
}
|
q12965
|
_fillSelect
|
train
|
function _fillSelect(element, value, next) {
var clickOnOption = chainAndErrorCallback.call(this, function (el, next) {
el.click(next);
}, next);
element.elementByXPath("//option[@value='"+escapeString(value, "'")+"']", clickOnOption);
}
|
javascript
|
{
"resource": ""
}
|
q12966
|
appendJSValue
|
train
|
function appendJSValue(token) {
builder.add('(')
if (options.compileDebug) {
builder.add(`${compile._getDebugMarker(token)},`)
}
builder.addToken(token)
builder.add(')')
}
|
javascript
|
{
"resource": ""
}
|
q12967
|
prepareContents
|
train
|
function prepareContents(tokens) {
let contents = new Map
for (let i = 0, len = tokens.length; i < len; i++) {
let token = tokens[i]
if (token.type === 'element' && token.name === 'eh-content') {
// Find attribute 'name'
let name = getNameAttributeValue(token),
arr = getArr(name)
for (let j = 0, len2 = token.children.length; j < len2; j++) {
arr.push(token.children[j])
}
} else {
getArr('').push(token)
}
}
/**
* @param {string} name
* @returns {Array<Token>}
*/
function getArr(name) {
if (!contents.has(name)) {
let arr = []
contents.set(name, arr)
return arr
}
return contents.get(name)
}
return contents
}
|
javascript
|
{
"resource": ""
}
|
q12968
|
getNameAttributeValue
|
train
|
function getNameAttributeValue(element) {
for (let i = 0, len = element.attributes.length; i < len; i++) {
let attribute = element.attributes[i]
if (attribute.name === 'name') {
if (attribute.type !== 'attribute-simple') {
throw new Error(`name attribute for ${element.name} tag must be a literal value`)
}
return attribute.value
}
}
return ''
}
|
javascript
|
{
"resource": ""
}
|
q12969
|
prepareInternalJSCode
|
train
|
function prepareInternalJSCode(source, options) {
// Parse
let tokens = parse(source)
// Transform
if (options.transformer) {
tokens = options.transformer(tokens) || tokens
}
let reducedTokens = reduce(tokens, options)
return createCode(reducedTokens, options, false)
}
|
javascript
|
{
"resource": ""
}
|
q12970
|
appendExpression
|
train
|
function appendExpression(prefix, token, suffix, isString) {
if (state === 'very-first') {
if (!isString) {
builder.add('""+')
}
} else if (state === 'first') {
builder.add('__o+=')
} else {
builder.add('+')
}
if (options.compileDebug && token) {
builder.add(`(${getDebugMarker(token)},`)
}
if (prefix) {
builder.add(prefix)
}
if (token) {
if (token.type === 'source-builder') {
builder.addBuilder(token.sourceBuilder)
} else {
builder.addToken(token)
}
}
if (suffix) {
builder.add(suffix)
}
if (options.compileDebug && token) {
builder.add(')')
}
state = 'rest'
}
|
javascript
|
{
"resource": ""
}
|
q12971
|
ActionProvider
|
train
|
function ActionProvider(dispatcher){
this.action1 = function(data){
console.log("Action 1");
// this way, the dispatcher establishes dynamically the action binding.
dispatcher.dispatch('action1', data);
};
this.action2 = function(data){
console.log("Action 2");
dispatcher.dispatch('action2', data);
}
}
|
javascript
|
{
"resource": ""
}
|
q12972
|
readSimpleToken
|
train
|
function readSimpleToken(type, endRegex, trimRight) {
if (trimRight) {
let matchTrim = exec(/\S/g)
if (matchTrim) {
advanceTo(matchTrim.index)
}
}
let match = exec(endRegex)
if (!match) {
throwSyntaxError(`Unterminated ${type}`)
}
let start = getSourcePoint()
advanceTo(match.index)
let token = createContentToken(type, start)
advanceTo(endRegex.lastIndex)
return token
}
|
javascript
|
{
"resource": ""
}
|
q12973
|
readCloseTag
|
train
|
function readCloseTag() {
let start = getSourcePoint(),
match = tagCloseRegex.exec(source.substr(pos))
if (!match) {
throwSyntaxError('Invalid close tag')
}
advanceTo(pos + match[0].length)
let end = getSourcePoint()
return {
type: 'tag-close',
start,
end,
name: match[1].toLowerCase()
}
}
|
javascript
|
{
"resource": ""
}
|
q12974
|
readOpenTag
|
train
|
function readOpenTag() {
// Read tag name
let start = getSourcePoint(),
match = tagNameRegex.exec(source.substr(pos))
if (!match) {
throwSyntaxError('Invalid open tag')
}
let tagName = match[0].toLowerCase(),
isVoid = voidElementsRegex.test(tagName)
advanceTo(pos + tagName.length)
// Keep reading content
let selfClose = false,
attributes = [],
// Used to detect repeated attributes
foundAttributeNames = []
while (true) {
// Match using anchored regex
let match = tagOpenContentStartRegex.exec(source.substr(pos))
if (!match) {
throwSyntaxError('Invalid open tag')
}
advanceTo(pos + match[0].length)
if (match[1] === '<%-') {
throwSyntaxError('EJS unescaped tags are not allowed inside open tags')
} else if (match[1] === '<%=') {
throwSyntaxError('EJS escaped tags are not allowed inside open tags')
} else if (match[1] === '<%') {
throwSyntaxError('EJS eval tags are not allowed inside open tags')
} else if (match[1] === '>') {
break
} else if (match[1] === '/>') {
selfClose = true
break
} else {
// Attribute start
let lowerName = match[1].toLowerCase()
if (foundAttributeNames.indexOf(lowerName) !== -1) {
throwSyntaxError(`Repeated attribute ${match[1]} in open tag ${tagName}`)
}
foundAttributeNames.push(lowerName)
attributes.push(readAttribute(lowerName))
}
}
if (!isVoid && selfClose) {
throwSyntaxError('Self-closed tags for non-void elements are not allowed')
}
return {
type: 'element',
start,
end: getSourcePoint(),
name: tagName,
isVoid,
attributes,
children: []
}
}
|
javascript
|
{
"resource": ""
}
|
q12975
|
advanceTo
|
train
|
function advanceTo(newPos) {
let n = newPos - pos
assert(n >= 0)
while (n--) {
if (source[pos] === '\n') {
column = 1
line++
} else {
column++
}
pos += 1
}
}
|
javascript
|
{
"resource": ""
}
|
q12976
|
createContentToken
|
train
|
function createContentToken(type, start) {
let end = getSourcePoint()
return {
type,
start,
end,
content: source.substring(start.pos, end.pos)
}
}
|
javascript
|
{
"resource": ""
}
|
q12977
|
throwSyntaxError
|
train
|
function throwSyntaxError(message) {
let curr = getSourcePoint(),
snippet = getSnippet(source, curr.line, curr.line),
err = new SyntaxError(`${message}\n${snippet}`)
err.pos = getSourcePoint()
throw err
}
|
javascript
|
{
"resource": ""
}
|
q12978
|
fromLatFirstString
|
train
|
function fromLatFirstString (str) {
var arr = str.split(',')
return floatize({lat: arr[0], lon: arr[1]})
}
|
javascript
|
{
"resource": ""
}
|
q12979
|
latitudeToPixel
|
train
|
function latitudeToPixel (latitude, zoom) {
const latRad = toRadians(latitude)
return (1 -
Math.log(Math.tan(latRad) + (1 / Math.cos(latRad))) /
Math.PI) / 2 * zScale(zoom)
}
|
javascript
|
{
"resource": ""
}
|
q12980
|
pixelToLatitude
|
train
|
function pixelToLatitude (y, zoom) {
var latRad = Math.atan(Math.sinh(Math.PI * (1 - 2 * y / zScale(zoom))))
return toDegrees(latRad)
}
|
javascript
|
{
"resource": ""
}
|
q12981
|
train
|
function(hexDimensions, radius) {
var positionArray = [];
var pixelCoordinates;
//For every hex, place an instance of the original mesh. The symbol fills in 3 of the 6 lines, the other 3 being shared with an adjacent hex
//Make a hexagonal grid of hexagons since it is approximately circular.
var u = 0;
var v = 0;
//For each radius
positionArray.push({ y: 0, x: 0 });
for (var i = 1; i < radius + 1; i++) {
//Hold u constant as the radius, add an instance for each v
for (v = -i; v <= 0; v++) {
pixelCoordinates = hexDimensions.getPixelCoordinates(i, v);
positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
}
//Hold u constant as negative the radius, add an instance for each v
for (v = 0; v <= i; v++) {
pixelCoordinates = hexDimensions.getPixelCoordinates(-i, v);
positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
}
//Hold v constant as the radius, add an instance for each u
for (u = -i + 1; u <= 0; u++) {
pixelCoordinates = hexDimensions.getPixelCoordinates(u, i);
positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
}
//Hold v constant as negative the radius, add an instance for each u
for (u = 0; u < i; u++) {
pixelCoordinates = hexDimensions.getPixelCoordinates(u, -i);
positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
}
//Hold w constant as the radius, add an instance for each u + v = -i
for (u = -i + 1, v = -1; v > -i; u++, v--) {
pixelCoordinates = hexDimensions.getPixelCoordinates(u, v);
positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
}
//Hold w constant as the negative radius, add an instance for each u + v = i
for (u = i - 1, v = 1; v < i; u--, v++) {
pixelCoordinates = hexDimensions.getPixelCoordinates(u, v);
positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
}
}
return positionArray;
}
|
javascript
|
{
"resource": ""
}
|
|
q12982
|
run
|
train
|
function run(cmd, args, options) {
if (process.env.SLS_DEBUG) console.log('Running', cmd, args.join(' '));
const stdio = process.env.SLS_DEBUG && options && options.showOutput
? ['pipe', 'inherit', 'pipe'] : 'pipe';
const ps = child_process.spawnSync(cmd, args, {encoding: 'utf-8', 'stdio': stdio});
if (ps.error) {
if (ps.error.code === 'ENOENT') {
throw new Error(`${cmd} not found! Please install it.`);
}
throw new Error(ps.error);
} else if (ps.status !== 0) {
throw new Error(ps.stderr);
}
return ps;
}
|
javascript
|
{
"resource": ""
}
|
q12983
|
linkto
|
train
|
function linkto(parentState, longname, name) {
if (!!longname && longname !== '') {
return '<a ui-sref="jsdoc.' + parentState + "({anchor:'" + longname.replace('module:', '') + "'})" + '">' + name + '</a>';
}
return '<a ui-sref="jsdoc.' + parentState + '">' + name + '</a>';
}
|
javascript
|
{
"resource": ""
}
|
q12984
|
linkToSrc
|
train
|
function linkToSrc(shortPath, lineNumber) {
var splitPath = shortPath.split("/");
return '<a href="{{srcroot}}' + shortPath+'">' + splitPath[splitPath.length - 1] + '</a>, <a href="{{srcroot}}' + shortPath+'#L'+lineNumber+'">' + lineNumber + '</a>';
}
|
javascript
|
{
"resource": ""
}
|
q12985
|
train
|
function (circle, options, redraw) {
if (typeof options === "undefined") { options = {}; }
if (typeof redraw === "undefined") { redraw = false; }
var screen = this.screen, prop, opts, svgCircle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
svgCircle.setAttribute('cx', circle.center[0]);
svgCircle.setAttribute('cy', circle.center[1]);
svgCircle.setAttribute('r', circle.radius);
if (options) {
svgCircle.setAttribute('stroke-width', (options.lineWidth || 4) / (screen.scale.x - screen.scale.y) + '');
opts = MathLib.SVG.convertOptions(options);
for (prop in opts) {
if (opts.hasOwnProperty(prop)) {
svgCircle.setAttribute(prop, opts[prop]);
}
}
}
this.ctx.appendChild(svgCircle);
if (!redraw) {
this.stack.push({
type: 'circle',
object: circle,
options: options
});
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q12986
|
train
|
function(instances) {
var queryKey = this.foreignKey;
var pks = _.map(instances, this.primaryKey);
if (instances.length === 1) { pks = pks[0]; }
else { queryKey += '$in'; }
var where = _.object([[queryKey, pks]]);
return this._relatedModel.objects.where(where);
}
|
javascript
|
{
"resource": ""
}
|
|
q12987
|
train
|
function (options) {
var convertedOptions = {};
if ('fillColor' in options) {
convertedOptions.fillStyle = MathLib.colorConvert(options.fillColor);
} else if ('color' in options) {
convertedOptions.fillStyle = MathLib.colorConvert(options.color);
}
if ('font' in options) {
convertedOptions.font = options.font;
}
if ('fontSize' in options) {
convertedOptions.fontSize = options.fontSize;
}
if ('lineColor' in options) {
convertedOptions.strokeStyle = MathLib.colorConvert(options.lineColor);
} else if ('color' in options) {
convertedOptions.strokeStyle = MathLib.colorConvert(options.color);
}
return convertedOptions;
}
|
javascript
|
{
"resource": ""
}
|
|
q12988
|
train
|
function (line, options, redraw) {
if (typeof options === "undefined") { options = {}; }
if (typeof redraw === "undefined") { redraw = false; }
var screen = this.screen, points, ctx = this.ctx, prop, opts;
ctx.save();
ctx.lineWidth = (options.lineWidth || 4) / (screen.scale.x - screen.scale.y);
// Don't try to draw the line at infinity
if (line.type === 'line' && MathLib.isZero(line[0]) && MathLib.isZero(line[1])) {
return this;
} else {
points = this.screen.getLineEndPoints(line);
}
// Set the drawing options
if (options) {
opts = MathLib.Canvas.convertOptions(options);
for (prop in opts) {
if (opts.hasOwnProperty(prop)) {
ctx[prop] = opts[prop];
}
}
if ('setLineDash' in ctx) {
ctx.setLineDash(('dash' in options ? options.dash : []));
}
if ('lineDashOffset' in ctx) {
ctx.lineDashOffset = ('dashOffset' in options ? options.dashOffset : 0);
}
}
// Draw the line
ctx.beginPath();
ctx.moveTo(points[0][0], points[0][1]);
ctx.lineTo(points[1][0], points[1][1]);
ctx.stroke();
ctx.closePath();
ctx.restore();
if (!redraw) {
this.stack.push({
type: 'line',
object: line,
options: options
});
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q12989
|
train
|
function (x) {
if (x.length === 2) {
return new THREE.Vector2(x[0], x[1]);
} else if (x.length === 3) {
return new THREE.Vector3(x[0], x[1], x[2]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q12990
|
sooner
|
train
|
function sooner (property) {
return function (a, b) {
if (a[property][0] < b[property][0]) return true;
if (a[property][0] > b[property][0]) return false;
return a[property][1] < b[property][1];
}
}
|
javascript
|
{
"resource": ""
}
|
q12991
|
EndPoint
|
train
|
function EndPoint (local) {
this.listeners = 0;
this.dgram = dgram.createSocket('udp4');
this.dgram.on('message', EndPoint.prototype.receive.bind(this));
this.dgram.bind(local.port, local.address);
this.local = this.dgram.address();
this.packet = new Buffer(2048);
this.sockets = {};
}
|
javascript
|
{
"resource": ""
}
|
q12992
|
lookupEndPoint
|
train
|
function lookupEndPoint (local) {
// No interfaces bound by the desired port. Note that this would also work for
// zero, which indicates an ephemeral binding, but we check for that case
// explicitly before calling this function.
if (!endPoints[local.port]) return null;
// Read datagram socket from cache.
var endPoint = endPoints[local.port][local.address];
// If no datagram exists, ensure that we'll be able to create one. This only
// inspects ports that have been bound by UDT, not by other protocols, so
// there is still an opportunity for error when the UDP bind is invoked.
if (!endPoint) {
if (endPoints[local.port][0]) {
throw new Error('Already bound to all interfaces.');
}
if (local.address == 0) {
throw new Error('Cannot bind to all interfaces because some interfaces are already bound.');
}
}
// Return cached datagram socket or nothing.
return endPoint;
}
|
javascript
|
{
"resource": ""
}
|
q12993
|
peerResolved
|
train
|
function peerResolved (ip, addressType) {
// Possible cancelation during DNS lookup.
if (!socket._connecting) return;
socket._peer = { address: ip || '127.0.0.1', port: options.port };
// Generate random bytes used to set randomized socket properties.
// `crypto.randomBytes` calls OpenSSL `RAND_bytes` to generate the bytes.
//
// * [RAND_bytes](http://www.openssl.org/docs/crypto/RAND_bytes.html).
// * [node_crypto.cc](https://github.com/joyent/node/blob/v0.8/src/node_crypto.cc#L4517)
crypto.randomBytes(4, valid(randomzied));
}
|
javascript
|
{
"resource": ""
}
|
q12994
|
randomzied
|
train
|
function randomzied (buffer) {
// Randomly generated randomness.
socket._sequence = buffer.readUInt32BE(0) % MAX_SEQ_NO;
// The end point sends a packet on our behalf.
socket._endPoint.shakeHands(socket);
}
|
javascript
|
{
"resource": ""
}
|
q12995
|
findOnLine
|
train
|
function findOnLine(find, patch, cb) {
if (find.test(patch)) {
var lineNum = 0
patch.split('\n').forEach(function(line) {
var range = /\@\@ \-\d+,\d+ \+(\d+),\d+ \@\@/g.exec(line)
if (range) {
lineNum = Number(range[1]) - 1
} else if (line.substr(0, 1) !== '-') {
lineNum++
}
if (find.test(line)) {
return cb(null, lineNum)
}
})
}
}
|
javascript
|
{
"resource": ""
}
|
q12996
|
addDerivedInfoForFile
|
train
|
function addDerivedInfoForFile(fileCoverage) {
var statementMap = fileCoverage.statementMap,
statements = fileCoverage.s,
lineMap;
if (!fileCoverage.l) {
fileCoverage.l = lineMap = {};
Object.keys(statements).forEach(function (st) {
var line = statementMap[st].start.line,
count = statements[st],
prevVal = lineMap[line];
if (count === 0 && statementMap[st].skip) { count = 1; }
if (typeof prevVal === 'undefined' || prevVal < count) {
lineMap[line] = count;
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
q12997
|
addDerivedInfo
|
train
|
function addDerivedInfo(coverage) {
Object.keys(coverage).forEach(function (k) {
addDerivedInfoForFile(coverage[k]);
});
}
|
javascript
|
{
"resource": ""
}
|
q12998
|
removeDerivedInfo
|
train
|
function removeDerivedInfo(coverage) {
Object.keys(coverage).forEach(function (k) {
delete coverage[k].l;
});
}
|
javascript
|
{
"resource": ""
}
|
q12999
|
mergeSummaryObjects
|
train
|
function mergeSummaryObjects() {
var ret = blankSummary(),
args = Array.prototype.slice.call(arguments),
keys = ['lines', 'statements', 'branches', 'functions'],
increment = function (obj) {
if (obj) {
keys.forEach(function (key) {
ret[key].total += obj[key].total;
ret[key].covered += obj[key].covered;
ret[key].skipped += obj[key].skipped;
});
}
};
args.forEach(function (arg) {
increment(arg);
});
keys.forEach(function (key) {
ret[key].pct = percent(ret[key].covered, ret[key].total);
});
return ret;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.