_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q45100 | expand | train | function expand( v1, v2, pixels ) {
var x = v2.x - v1.x, y = v2.y - v1.y,
det = x * x + y * y, idet;
if ( det === 0 ) return;
idet = pixels / Math.sqrt( det );
x *= idet; y *= idet;
v2.x += x; v2.y += y;
v1.x -= x; v1.y -= y;
} | javascript | {
"resource": ""
} |
q45101 | binarySearchIndices | train | function binarySearchIndices( value ) {
function binarySearch( start, end ) {
// return closest larger index
// if exact number is not found
if ( end < start )
return start;
var mid = start + Math.floor( ( end - start ) / 2 );
if ( cumulativeAreas[ mid ] > value ) {
return binaryS... | javascript | {
"resource": ""
} |
q45102 | train | function ( geometry ) {
geometry.computeBoundingBox();
var bb = geometry.boundingBox;
var offset = new THREE.Vector3();
offset.addVectors( bb.min, bb.max );
offset.multiplyScalar( -0.5 );
geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
geometry.computeBoun... | javascript | {
"resource": ""
} | |
q45103 | train | function ( points, scale ) {
var c = [], v3 = [],
point, intPoint, weight, w2, w3,
pa, pb, pc, pd;
point = ( points.length - 1 ) * scale;
intPoint = Math.floor( point );
weight = point - intPoint;
c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
c[ 1 ] = intPoint;
c[ 2 ] = intPoint > points.lengt... | javascript | {
"resource": ""
} | |
q45104 | updateVirtualLight | train | function updateVirtualLight( light, cascade ) {
var virtualLight = light.shadowCascadeArray[ cascade ];
virtualLight.position.copy( light.position );
virtualLight.target.position.copy( light.target.position );
virtualLight.lookAt( virtualLight.target );
virtualLight.shadowCameraVisible = light.shadowCamera... | javascript | {
"resource": ""
} |
q45105 | updateShadowCamera | train | function updateShadowCamera( camera, light ) {
var shadowCamera = light.shadowCamera,
pointsFrustum = light.pointsFrustum,
pointsWorld = light.pointsWorld;
_min.set( Infinity, Infinity, Infinity );
_max.set( -Infinity, -Infinity, -Infinity );
for ( var i = 0; i < 8; i ++ ) {
var p = pointsWorld[ i ... | javascript | {
"resource": ""
} |
q45106 | getObjectMaterial | train | function getObjectMaterial( object ) {
return object.material instanceof THREE.MeshFaceMaterial
? object.material.materials[ 0 ]
: object.material;
} | javascript | {
"resource": ""
} |
q45107 | train | function(){
this.frameIndex++;
if (this.frameIndex >= this.rightCropPosition) {
this.frameIndex = this.frameIndex % (this.rightCropPosition || 1);
if ((this.frameIndex < this.leftCropPosition)) {
this.frameIndex = this.leftCropPosition;
}
}else{
this.frameIndex--;
}
} | javascript | {
"resource": ""
} | |
q45108 | train | function (factor) {
console.log('cull frames', factor);
factor || (factor = 1);
for (var i = 0; i < this.frameData.length; i++) {
this.frameData.splice(i, factor);
}
this.setMetaData();
} | javascript | {
"resource": ""
} | |
q45109 | train | function () {
if (this.frameData.length == 0) {
return 0
}
return this.frameData.length / (this.frameData[this.frameData.length - 1].timestamp - this.frameData[0].timestamp) * 1000000;
} | javascript | {
"resource": ""
} | |
q45110 | train | function(){
var frameData = this.croppedFrameData(),
packedFrames = [],
frameDatum;
packedFrames.push(this.packingStructure);
for (var i = 0, len = frameData.length; i < len; i++){
frameDatum = frameData[i];
packedFrames.push(
this.packArray(
this.packingStructur... | javascript | {
"resource": ""
} | |
q45111 | train | function(packedFrames){
var packingStructure = packedFrames[0];
var frameData = [],
frameDatum;
for (var i = 1, len = packedFrames.length; i < len; i++) {
frameDatum = packedFrames[i];
frameData.push(
this.unPackArray(
packingStructure,
frameDatum
)
... | javascript | {
"resource": ""
} | |
q45112 | train | function (callback) {
var xhr = new XMLHttpRequest(),
url = this.url,
recording = this,
contentLength = 0;
xhr.onreadystatechange = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200 || xhr.status === 0) {
if (xhr.responseText) {
... | javascript | {
"resource": ""
} | |
q45113 | train | function () {
this.idle();
delete this.recording;
this.recording = new Recording({
timeBetweenLoops: this.options.timeBetweenLoops,
loop: this.options.loop,
requestProtocolVersion: this.controller.connection.opts.requestProtocolVersion,
service... | javascript | {
"resource": ""
} | |
q45114 | train | function () {
if (!this.recording || this.recording.blank()) return;
var finalFrame = this.recording.cloneCurrentFrame();
finalFrame.hands = [];
finalFrame.fingers = [];
finalFrame.pointables = [];
finalFrame.tools = [];
this.sendImmediateFrame(finalFrame);
} | javascript | {
"resource": ""
} | |
q45115 | train | function (frameData) {
// Would be better to check controller.streaming() in showOverlay, but that method doesn't exist, yet.
this.setGraphic('wave');
if (frameData.hands.length > 0) {
this.recording.addFrame(frameData);
this.hideOverlay();
} else if ( !this.recording.blank() ) {... | javascript | {
"resource": ""
} | |
q45116 | train | function (frames) {
this.setFrames(frames);
if (player.recording != this){
console.log('recordings changed during load');
return
}
// it would be better to use streamingCount here, but that won't be in until 0.5.0+
// For now, it just flashes for a moment u... | javascript | {
"resource": ""
} | |
q45117 | train | function (graphicName) {
if (!this.overlay) return;
if (this.graphicName == graphicName) return;
this.graphicName = graphicName;
switch (graphicName) {
case 'connect':
this.overlay.style.display = 'block';
this.overlay.innerHTML = CONNECT_LEAP_ICON;
break;
... | javascript | {
"resource": ""
} | |
q45118 | hasNestedProperty | train | function hasNestedProperty(obj, propertyPath, returnVal = false) {
if (!propertyPath) return false;
// strip the leading dot
propertyPath = propertyPath.replace(/^\./, '');
const properties = propertyPath.split('.');
for (var i = 0; i < properties.length; i++) {
var prop = properties[i];
if (!obj |... | javascript | {
"resource": ""
} |
q45119 | DumperGetArgs | train | function DumperGetArgs(a,index) {
var args = new Array();
// This is kind of ugly, but I don't want to use js1.2 functions, just in case...
for (var i=index; i<a.length; i++) {
args[args.length] = a[i];
}
return args;
} | javascript | {
"resource": ""
} |
q45120 | train | function(onReady) {
var self = this;
if (APPID === 'change me') {
console.log('Error -- edit weatherman.js and provide the APPID for Open Weathermap.'.bold.yellow);
}
// Load the replies and process them.
rs.loadFile("weatherman.rive").then(function() {
rs.sortReplies();
onReady();
}).catch(function(err) ... | javascript | {
"resource": ""
} | |
q45121 | train | function(rs, args) {
// This function is invoked by messages such as:
// what is 5 subtracted by 2
// add 6 to 7
if (args[0].match(/^\d+$/)) {
// They used the first form, with a number.
return Controllers.doMath(args[1], args[0], args[2]);
}
else {
// The second form, first word being... | javascript | {
"resource": ""
} | |
q45122 | DocusignAPIError | train | function DocusignAPIError(message, type, code, subcode, traceID) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'DocusignAPIError';
this.message = message;
this.type = type;
this.code = code;
this.subcode = subcode;
this.traceID = traceID;
this.status = 500;
} | javascript | {
"resource": ""
} |
q45123 | checkMethods | train | function checkMethods(spec) {
assert(spec.method, 'missing route methods');
if (typeof spec.method === 'string') {
spec.method = spec.method.split(' ');
}
if (!Array.isArray(spec.method)) {
throw new TypeError('route methods must be an array or string');
}
if (spec.method.length === 0) {
thro... | javascript | {
"resource": ""
} |
q45124 | checkValidators | train | function checkValidators(spec) {
if (!spec.validate) return;
let text;
if (spec.validate.body) {
text = 'validate.type must be declared when using validate.body';
assert(/json|form/.test(spec.validate.type), text);
}
if (spec.validate.type) {
text = 'validate.type must be either json, form, mult... | javascript | {
"resource": ""
} |
q45125 | wrapError | train | function wrapError(spec, parsePayload) {
return async function errorHandler(ctx, next) {
try {
await parsePayload(ctx, next);
} catch (err) {
captureError(ctx, 'type', err);
if (spec.validate.continueOnError) {
return await next();
} else {
return ctx.throw(err);
... | javascript | {
"resource": ""
} |
q45126 | makeJSONBodyParser | train | function makeJSONBodyParser(spec) {
const opts = spec.validate.jsonOptions || {};
if (typeof opts.limit === 'undefined') {
opts.limit = spec.validate.maxBody;
}
return async function parseJSONPayload(ctx, next) {
if (!ctx.request.is('json')) {
return ctx.throw(400, 'expected json');
}
ctx... | javascript | {
"resource": ""
} |
q45127 | makeFormBodyParser | train | function makeFormBodyParser(spec) {
const opts = spec.validate.formOptions || {};
if (typeof opts.limit === 'undefined') {
opts.limit = spec.validate.maxBody;
}
return async function parseFormBody(ctx, next) {
if (!ctx.request.is('urlencoded')) {
return ctx.throw(400, 'expected x-www-form-urlencod... | javascript | {
"resource": ""
} |
q45128 | makeBodyParser | train | function makeBodyParser(spec) {
if (!(spec.validate && spec.validate.type)) return noopMiddleware;
switch (spec.validate.type) {
case 'json':
return wrapError(spec, makeJSONBodyParser(spec));
case 'form':
return wrapError(spec, makeFormBodyParser(spec));
case 'stream':
case 'multipart':... | javascript | {
"resource": ""
} |
q45129 | makeValidator | train | function makeValidator(spec) {
const props = 'header query params body'.split(' ');
return async function validator(ctx, next) {
if (!spec.validate) return await next();
let err;
for (let i = 0; i < props.length; ++i) {
const prop = props[i];
if (spec.validate[prop]) {
err = vali... | javascript | {
"resource": ""
} |
q45130 | makeSpecExposer | train | function makeSpecExposer(spec) {
const defn = clone(spec);
return async function specExposer(ctx, next) {
ctx.state.route = defn;
await next();
};
} | javascript | {
"resource": ""
} |
q45131 | prepareRequest | train | async function prepareRequest(ctx, next) {
ctx.request.params = ctx.params;
await next();
} | javascript | {
"resource": ""
} |
q45132 | addConfig | train | function addConfig(configObj, platformObj) {
for (const n in configObj) {
if (n != PLATFORM && configObj.hasOwnProperty(n)) {
if (angular.isObject(configObj[n])) {
if (angular.isUndefined(platformObj[n])) {
... | javascript | {
"resource": ""
} |
q45133 | removeImplementedInterfaces | train | function removeImplementedInterfaces(context, node, ast) {
if (node.implements && node.implements.length > 0) {
var first = node.implements[0];
var last = node.implements[node.implements.length - 1];
var idx = findTokenIndex(ast.tokens, first.start);
do {
idx--;
} while (ast.tokens[idx].valu... | javascript | {
"resource": ""
} |
q45134 | regexpPattern | train | function regexpPattern(pattern) {
if (!pattern) {
return pattern;
}
// A very simplified glob transform which allows passing legible strings like
// "myPath/*.js" instead of a harder to read RegExp like /\/myPath\/.*\.js/.
if (typeof pattern === 'string') {
pattern = pattern.replace(/\./g, '\\.').repl... | javascript | {
"resource": ""
} |
q45135 | train | function(e) {
var current = _this._getCurrentTab(); // Fetch current tab
var activatedTab = e.data.tab;
e.preventDefault();
// Trigger click event for whenever a tab is clicked/touched even if the tab is disabled
activatedTab.tab.trigger('tabs-click', activa... | javascript | {
"resource": ""
} | |
q45136 | after | train | function after(count, callback) {
var countdown = count;
return function shim(err) {
if (typeof callback !== 'function') return;
if (err) {
callback(err);
callback = null;
return;
}
if (--countdown === 0) {
callback();
... | javascript | {
"resource": ""
} |
q45137 | createJsonFileDiscoverProvider | train | function createJsonFileDiscoverProvider(hostsFile) {
var fs = require('fs');
return function jsonFileProvider(callback) {
fs.readFile(hostsFile, function onFileRead(err, data) {
if (err) {
callback(err);
return;
}
var hosts;
... | javascript | {
"resource": ""
} |
q45138 | retryDiscoverProvider | train | function retryDiscoverProvider(opts, innerDiscoverProvider) {
if (!opts) {
return innerDiscoverProvider;
}
return function retryingDiscoverProvider(callback) {
var policy;
var defaultPolicy = {
minDelay: 500,
maxDelay: 15000,
timeout: 60000
... | javascript | {
"resource": ""
} |
q45139 | createFromOpts | train | function createFromOpts(opts) {
opts = opts || {};
if (typeof opts === 'function') {
return opts;
}
if (typeof opts === 'string') {
return createJsonFileDiscoverProvider(opts);
}
if (Array.isArray(opts)) {
return createStaticHostsProvider(opts);
}
var discoverPr... | javascript | {
"resource": ""
} |
q45140 | resolveEventConfig | train | function resolveEventConfig(ringpop, traceEvent) {
var tracerConfig = tracerConfigMap[traceEvent];
if (!tracerConfig) {
return null;
}
var sourcePath = tracerConfig.sourcePath;
// subtle but important -- if we resolve here, then the underlying object
// can never change. if we do latent... | javascript | {
"resource": ""
} |
q45141 | Config | train | function Config(ringpop, seedConfig) {
seedConfig = seedConfig || {};
this.ringpop = ringpop;
this.store = {};
this._seed(seedConfig);
} | javascript | {
"resource": ""
} |
q45142 | Update | train | function Update(subject, source) {
if (!(this instanceof Update)) {
return new Update(subject, source);
}
this.id = uuid.v4();
this.timestamp = Date.now();
// Populate subject
subject = subject || {};
this.address = subject.address;
this.incarnationNumber = subject.incarnationNu... | javascript | {
"resource": ""
} |
q45143 | takeNode | train | function takeNode(hosts) {
var index = Math.floor(Math.random() * hosts.length);
var host = hosts[index];
hosts.splice(index, 1);
return host;
} | javascript | {
"resource": ""
} |
q45144 | DampingReusableEvent | train | function DampingReusableEvent(member, oldDampScore) {
this.name = this.constructor.name;
this.member = member;
this.oldDampScore = oldDampScore;
} | javascript | {
"resource": ""
} |
q45145 | createDampReqHandler | train | function createDampReqHandler(addr) {
var start = self.Date.now();
return function onDampReq(err, res) {
var timing = self.Date.now() - start;
self.ringpop.stat('timing', 'protocol.damp-req', timing);
// Prevents double-callback
if (typeof callback !== 'f... | javascript | {
"resource": ""
} |
q45146 | callRequestMiddleware | train | function callRequestMiddleware(arg2, arg3) {
i += 1;
if (i < self.middlewares.length) {
var next = self.middlewares[i].request;
if (typeof next === 'function') {
next(req, arg2, arg3, callRequestMiddleware);
} else {
// skip this middle... | javascript | {
"resource": ""
} |
q45147 | callResponseMiddleware | train | function callResponseMiddleware(err, res1, res2) {
i -= 1;
if (i >= 0) {
var next = self.middlewares[i].response;
if (typeof next === 'function') {
next(req, err, res1, res2, callResponseMiddleware);
} else {
// skip this middleware if ... | javascript | {
"resource": ""
} |
q45148 | dedupeNonExistent | train | function dedupeNonExistent(nonExistent) {
const deduped = new Set(nonExistent);
nonExistent.length = deduped.size;
let i = 0;
for (const elem of deduped) {
nonExistent[i] = elem;
i++;
}
} | javascript | {
"resource": ""
} |
q45149 | setLocale | train | async function setLocale (sim, opts, localeConfig = {}, safari = false) {
if (!opts.language && !opts.locale && !opts.calendarFormat) {
logger.debug('No reason to set locale');
return {
_updated: false,
};
}
// we need the simulator to have its directories in place
if (await sim.isFresh()) {
... | javascript | {
"resource": ""
} |
q45150 | train | function (strategy, selector, mult, context) {
let ext = mult ? 's' : '';
let command = '';
context = !context ? context : `, '${context}'` ;
switch (strategy) {
case 'name':
command = `au.getElement${ext}ByName('${selector}'${context})`;
break;
case 'accessibility id':
... | javascript | {
"resource": ""
} | |
q45151 | train | function () {
var alert = getAlert();
if (alert.isNil()) {
throw new ERROR.NoAlertOpenError();
}
var texts = this.getElementsByType('text', alert);
// If an alert does not have a title, alert.name() is null, use empty string
var text = alert.name() || "";
if (texts.len... | javascript | {
"resource": ""
} | |
q45152 | quickLaunch | train | async function quickLaunch (udid, appPath = path.resolve(__dirname, '..', '..', 'assets', 'TestApp.app')) {
let traceTemplatePath = await xcode.getAutomationTraceTemplatePath();
let scriptPath = path.resolve(__dirname, '..', '..', 'assets', 'blank_instruments_test.js');
let traceDocument = path.resolve('/', 'tmp'... | javascript | {
"resource": ""
} |
q45153 | convertCookie | train | function convertCookie (value, converter) {
if (value.indexOf('"') === 0) {
// this is a quoted cookied according to RFC2068
// remove enclosing quotes and internal quotes and backslashes
value = value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
let parsedValue;
try {
parsedValu... | javascript | {
"resource": ""
} |
q45154 | createJSCookie | train | function createJSCookie (key, value, options = {}) {
return [
encodeURIComponent(key), '=', value,
options.expires
? `; expires=${options.expires}`
: '',
options.path
? `; path=${options.path}`
: '',
options.domain
? `; domain=${options.domain}`
: '',
options.se... | javascript | {
"resource": ""
} |
q45155 | createJWPCookie | train | function createJWPCookie (key, cookieString, converter = null) {
let result = {};
let cookies = cookieString ? cookieString.split('; ') : [];
for (let cookie of cookies) {
let parts = cookie.split('=');
// get the first and second element as name and value
let name = decodeURIComponent(parts.shift())... | javascript | {
"resource": ""
} |
q45156 | getValue | train | function getValue (key, cookieString, converter = null) {
let result = createJWPCookie(key, cookieString, converter);
// if `key` is undefined we want the entire cookie
return _.isUndefined(key) ? result : result.value;
} | javascript | {
"resource": ""
} |
q45157 | train | function (selector, ctx) {
if (typeof selector !== 'string') {
return null;
}
var _ctx = $.mainApp()
, elems = [];
if (typeof ctx === 'string') {
_ctx = this.cache[ctx];
} else if (typeof ctx !== 'undefined') {
_ctx = ctx;
}
$.target().pushTim... | javascript | {
"resource": ""
} | |
q45158 | train | function () {
var orientation = $.orientation()
, value = null;
switch (orientation) {
case UIA_DEVICE_ORIENTATION_UNKNOWN:
case UIA_DEVICE_ORIENTATION_FACEUP:
case UIA_DEVICE_ORIENTATION_FACEDOWN:
value = "UNKNOWN";
break;
case UIA_DEVICE_ORIENTAT... | javascript | {
"resource": ""
} | |
q45159 | Request | train | function Request(options) {
return new Promise(function(resolve, reject) {
client(options, function(err, res) {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
} | javascript | {
"resource": ""
} |
q45160 | BlameRangeList | train | function BlameRangeList(blame) {
var ranges = blame.ranges;
return ranges
.filter(function(range) {
return (
range &&
range.commit &&
range.commit.author &&
range.commit.author.user &&
range.commit.author.user.login
);
})
.map(function(range) {
... | javascript | {
"resource": ""
} |
q45161 | parseGithubURL | train | function parseGithubURL(url) {
var githubUrlRe = /github\.com\/([^/]+)\/([^/]+)\/pull\/([0-9]+)/;
var match = url.match(githubUrlRe);
if (!match) {
return null;
}
return {
owner: match[1],
repo: match[2],
number: match[3]
};
} | javascript | {
"resource": ""
} |
q45162 | main | train | async function main() {
event.$emit('before-client-render')
if (globalState.initialData) {
dataStore.replaceState(globalState.initialData)
}
await routerReady(router)
if (router.getMatchedComponents().length === 0) {
throw new ReamError(pageNotFound(router.currentRoute.path))
}
} | javascript | {
"resource": ""
} |
q45163 | SendStream | train | function SendStream (req, path, options) {
Stream.call(this)
var opts = options || {}
this.options = opts
this.path = path
this.req = req
this._acceptRanges = opts.acceptRanges !== undefined
? Boolean(opts.acceptRanges)
: true
this._cacheControl = opts.cacheControl !== undefined
? Boolean(... | javascript | {
"resource": ""
} |
q45164 | clearHeaders | train | function clearHeaders (res) {
var headers = getHeaderNames(res)
for (var i = 0; i < headers.length; i++) {
res.removeHeader(headers[i])
}
} | javascript | {
"resource": ""
} |
q45165 | containsDotFile | train | function containsDotFile (parts) {
for (var i = 0; i < parts.length; i++) {
var part = parts[i]
if (part.length > 1 && part[0] === '.') {
return true
}
}
return false
} | javascript | {
"resource": ""
} |
q45166 | contentRange | train | function contentRange (type, size, range) {
return type + ' ' + (range ? range.start + '-' + range.end : '*') + '/' + size
} | javascript | {
"resource": ""
} |
q45167 | getHeaderNames | train | function getHeaderNames (res) {
return typeof res.getHeaderNames !== 'function'
? Object.keys(res._headers || {})
: res.getHeaderNames()
} | javascript | {
"resource": ""
} |
q45168 | hasListeners | train | function hasListeners (emitter, type) {
var count = typeof emitter.listenerCount !== 'function'
? emitter.listeners(type).length
: emitter.listenerCount(type)
return count > 0
} | javascript | {
"resource": ""
} |
q45169 | normalizeList | train | function normalizeList (val, name) {
var list = [].concat(val || [])
for (var i = 0; i < list.length; i++) {
if (typeof list[i] !== 'string') {
throw new TypeError(name + ' must be array of strings or false')
}
}
return list
} | javascript | {
"resource": ""
} |
q45170 | parseTokenList | train | function parseTokenList (str) {
var end = 0
var list = []
var start = 0
// gather tokens
for (var i = 0, len = str.length; i < len; i++) {
switch (str.charCodeAt(i)) {
case 0x20: /* */
if (start === end) {
start = end = i + 1
}
break
case 0x2c: /* , */
... | javascript | {
"resource": ""
} |
q45171 | tarballedProps | train | function tarballedProps (pkg, spec, opts) {
const needsShrinkwrap = (!pkg || (
pkg._hasShrinkwrap !== false &&
!pkg._shrinkwrap
))
const needsBin = !!(!pkg || (
!pkg.bin &&
pkg.directories &&
pkg.directories.bin
))
const needsIntegrity = !pkg || (!pkg._integrity && pkg._integrity !== false... | javascript | {
"resource": ""
} |
q45172 | stripBOM | train | function stripBOM (content) {
content = content.toString()
// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
// because the buffer-to-string conversion in `fs.readFileSync()`
// translates it to FEFF, the UTF-16 BOM.
if (content.charCodeAt(0) === 0xFEFF) return content.slice(1)
... | javascript | {
"resource": ""
} |
q45173 | genPoints | train | function genPoints (inArr, ref, ref$1) {
var minX = ref.minX;
var minY = ref.minY;
var maxX = ref.maxX;
var maxY = ref.maxY;
var max = ref$1.max;
var min = ref$1.min;
var arr = inArr.map(function (item) { return (typeof item === 'number' ? item : item.value); });
var minValue = Math.min.apply(Math, arr... | javascript | {
"resource": ""
} |
q45174 | ignorePlugins | train | function ignorePlugins(plugins, currentPlugin) {
return plugins.reduce(function (acc, plugin) {
if (currentPlugin && currentPlugin.indexOf(plugin) > -1) {
return true;
}
return acc;
}, false);
} | javascript | {
"resource": ""
} |
q45175 | generateGCMPayload | train | function generateGCMPayload(requestData, pushId, timeStamp, expirationTime) {
let payload = {
priority: 'high'
};
payload.data = {
data: requestData.data,
push_id: pushId,
time: new Date(timeStamp).toISOString()
}
const optionalKeys = ['content_available', 'notification'];
optionalKeys.forEa... | javascript | {
"resource": ""
} |
q45176 | sliceDevices | train | function sliceDevices(devices, chunkSize) {
let chunkDevices = [];
while (devices.length > 0) {
chunkDevices.push(devices.splice(0, chunkSize));
}
return chunkDevices;
} | javascript | {
"resource": ""
} |
q45177 | runMicroBenchmarks | train | function runMicroBenchmarks(lists, resources) {
console.log('Run micro bench...');
// Create adb engine to use in benchmark
const { engine, serialized } = createEngine(lists, resources, {
loadCosmeticFilters: true,
loadNetworkFilters: true,
}, true /* Also serialize engine */);
const filters = getFil... | javascript | {
"resource": ""
} |
q45178 | train | function() {
let docDomain = this.getDocDomain();
if ( docDomain === '' ) { docDomain = this.docHostname; }
if ( this.domain !== undefined && this.domain !== '' ) {
return this.domain !== docDomain;
}
const hostname = this.getHostname();
if ( hostname.endsWith... | javascript | {
"resource": ""
} | |
q45179 | train | function() {
let tabDomain = this.getTabDomain();
if ( tabDomain === '' ) { tabDomain = this.tabHostname; }
if ( this.domain !== undefined && this.domain !== '' ) {
return this.domain !== tabDomain;
}
const hostname = this.getHostname();
if ( hostname.endsWith... | javascript | {
"resource": ""
} | |
q45180 | train | function() {
const buf8 = pslBuffer8;
const buf32 = pslBuffer32;
const iCharData = buf32[CHARDATA_PTR_SLOT];
let iNode = pslBuffer32[RULES_PTR_SLOT];
let cursorPos = -1;
let iLabel = LABEL_INDICES_SLOT;
// Label-lookup loop
for (;;) {
// Extract label indices
const labe... | javascript | {
"resource": ""
} | |
q45181 | train | function(tabId, url) {
var entry = tabContexts.get(tabId);
if ( entry === undefined ) {
entry = new TabContext(tabId);
entry.autodestroy();
}
entry.push(url);
mostRecentRootDocURL = url;
mostRecentRootDocURLTimestamp = Date.now();
return en... | javascript | {
"resource": ""
} | |
q45182 | train | function(tabId) {
var entry = tabContexts.get(tabId);
if ( entry !== undefined ) {
return entry;
}
// https://github.com/chrisaljoudi/uBlock/issues/1025
// Google Hangout popup opens without a root frame. So for now we will
// just discard that best-guess root... | javascript | {
"resource": ""
} | |
q45183 | train | function(s) {
const match = reParseRegexLiteral.exec(s);
let regexDetails;
if ( match !== null ) {
regexDetails = match[1];
if ( isBadRegex(regexDetails) ) { return; }
if ( match[2] ) {
regexDetails = [ regexDetails,... | javascript | {
"resource": ""
} | |
q45184 | train | function(server, port, options, cb) {
return this.client.connect.call(this.client, server, port, options, cb);
} | javascript | {
"resource": ""
} | |
q45185 | train | function(middleware, options) {
if (this.server && this.server.auth) {
this.server.auth(middleware, options);
} else {
throw new Error("vantage.auth is only available in Vantage.IO. Please use this (npm install vantage-io --save)");
}
return this;
} | javascript | {
"resource": ""
} | |
q45186 | train | function(args, cb) {
var ssn = this.getSessionById(args.sessionId);
if (!this._authFn) {
var nodeEnv = process.env.NODE_ENV || "development";
if (nodeEnv !== "development") {
var msg = "The Node server you are connecting to appears "
+ "to be a production server, and yet its Va... | javascript | {
"resource": ""
} | |
q45187 | on | train | function on(str, opts, cbk) {
cbk = (_.isFunction(opts)) ? opts : cbk;
cbk = cbk || function() {};
opts = opts || {};
ssn.server.on(str, function() {
if (!ssn.server || (!ssn.authenticating && !ssn.authenticated)) {
//console.log("Not Authenticated. Closing Session.", ssn... | javascript | {
"resource": ""
} |
q45188 | matrMult | train | function matrMult(m, v) {
return [
new Fraction(m[0]).mul(v[0]).add(new Fraction(m[1]).mul(v[1])),
new Fraction(m[2]).mul(v[0]).add(new Fraction(m[3]).mul(v[1]))
];
} | javascript | {
"resource": ""
} |
q45189 | vecSub | train | function vecSub(a, b) {
return [
new Fraction(a[0]).sub(b[0]),
new Fraction(a[1]).sub(b[1])
];
} | javascript | {
"resource": ""
} |
q45190 | run | train | function run(V, j) {
var t = H(V);
//console.log("H(X)");
for (var i in t) {
// console.log(t[i].toFraction());
}
var s = grad(V);
//console.log("vf(X)");
for (var i in s) {
// console.log(s[i].toFraction());
}
//console.log("multiplikation");
var r = matrMult(t, s);
for (var i in r) ... | javascript | {
"resource": ""
} |
q45191 | train | function(a, b) {
parse(a, b);
return new Fraction(
this["s"] * this["n"] * P["d"] + P["s"] * this["d"] * P["n"],
this["d"] * P["d"]
);
} | javascript | {
"resource": ""
} | |
q45192 | train | function(a, b) {
if (isNaN(this['n']) || isNaN(this['d'])) {
return new Fraction(NaN);
}
if (a === undefined) {
return new Fraction(this["s"] * this["n"] % this["d"], 1);
}
parse(a, b);
if (0 === P["n"] && 0 === this["d"]) {
Fraction(0, 0); // Throw Divisio... | javascript | {
"resource": ""
} | |
q45193 | train | function(a, b) {
parse(a, b);
var t = (this["s"] * this["n"] * P["d"] - P["s"] * P["n"] * this["d"]);
return (0 < t) - (t < 0);
} | javascript | {
"resource": ""
} | |
q45194 | regularizeNone | train | function regularizeNone(weights, gradientCount) {
const [gradient, count] = gradientCount;
for (let i = 0; i < gradient.length; i++) {
let grad = (gradient[i] || 0) / count;
weights[i] = (weights[i] || 0) - grad;
}
} | javascript | {
"resource": ""
} |
q45195 | regularizeL1 | train | function regularizeL1(weights, gradientCount, stepSize) {
const [gradient, count] = gradientCount;
for (let i = 0; i < gradient.length; i++) {
let grad = (gradient[i] || 0) / count;
weights[i] = weights[i] || 0;
weights[i] -= stepSize * grad + (weights[i] > 0 ? 1 : -1);
}
} | javascript | {
"resource": ""
} |
q45196 | regularizeL2 | train | function regularizeL2(weights, gradientCount, stepSize, regParam) {
const [gradient, count] = gradientCount;
for (let i = 0; i < gradient.length; i++) {
let grad = (gradient[i] || 0) / count;
weights[i] = weights[i] || 0;
weights[i] -= stepSize * (grad + regParam * weights[i]);
}
} | javascript | {
"resource": ""
} |
q45197 | randomizeArray | train | function randomizeArray(array) {
let i = array.length;
while (i) {
let j = Math.floor(Math.random() * i--);
[array[i], array[j]] = [array[j], array[i]];
}
return array;
} | javascript | {
"resource": ""
} |
q45198 | sampleSizeFraction | train | function sampleSizeFraction(num, total, withReplacement) {
const minSamplingRate = 1e-10; // Limited by RNG's resolution
const delta = 1e-4; // To have 0.9999 success rate
const fraction = num / total;
let upperBound;
if (withReplacement) {
// Poisson upper bound for Pr(num succe... | javascript | {
"resource": ""
} |
q45199 | iterateDone | train | function iterateDone() {
dlog(start, 'iterate');
blocksToRegister.map(function(block) {mm.register(block);});
if (action) {
if (action.opt._postIterate) {
action.opt._postIterate(action.init, action.opt, self, tmpPart.partitionIndex, function () {
done({data: {host: self.grid.host.uu... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.