_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q27500 | baseInverter | train | function baseInverter(object, setter, iteratee, accumulator) {
baseForOwn(object, function(value, key, object) {
setter(accumulator, iteratee(value), key, object);
});
return accumulator;
} | javascript | {
"resource": ""
} |
q27501 | basePullAt | train | function basePullAt(array, indexes) {
var length = array ? indexes.length : 0,
lastIndex = length - 1;
while (length--) {
var index = indexes[length];
if (length == lastIndex || index !== previous) {
var previous = index;
if (isIndex(index)) {
splice.call(array, index, 1);
} else {
baseUnset(array, index);
}
}
}
return array;
} | javascript | {
"resource": ""
} |
q27502 | baseRepeat | train | function baseRepeat(string, n) {
var result = '';
if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
return result;
}
// Leverage the exponentiation by squaring algorithm for a faster repeat.
// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
do {
if (n % 2) {
result += string;
}
n = nativeFloor(n / 2);
if (n) {
string += string;
}
} while (n);
return result;
} | javascript | {
"resource": ""
} |
q27503 | baseSampleSize | train | function baseSampleSize(collection, n) {
var array = values(collection);
return shuffleSelf(array, baseClamp(n, 0, array.length));
} | javascript | {
"resource": ""
} |
q27504 | baseSortedIndex | train | function baseSortedIndex(array, value, retHighest) {
var low = 0,
high = array == null ? low : array.length;
if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
while (low < high) {
var mid = (low + high) >>> 1,
computed = array[mid];
if (computed !== null && !isSymbol(computed) &&
(retHighest ? (computed <= value) : (computed < value))) {
low = mid + 1;
} else {
high = mid;
}
}
return high;
}
return baseSortedIndexBy(array, value, identity, retHighest);
} | javascript | {
"resource": ""
} |
q27505 | baseUpdate | train | function baseUpdate(object, path, updater, customizer) {
return baseSet(object, path, updater(baseGet(object, path)), customizer);
} | javascript | {
"resource": ""
} |
q27506 | createBind | train | function createBind(func, bitmask, thisArg) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return fn.apply(isBind ? thisArg : this, arguments);
}
return wrapper;
} | javascript | {
"resource": ""
} |
q27507 | createRelationalOperation | train | function createRelationalOperation(operator) {
return function(value, other) {
if (!(typeof value == 'string' && typeof other == 'string')) {
value = toNumber(value);
other = toNumber(other);
}
return operator(value, other);
};
} | javascript | {
"resource": ""
} |
q27508 | customDefaultsAssignIn | train | function customDefaultsAssignIn(objValue, srcValue, key, object) {
if (objValue === undefined ||
(eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
return srcValue;
}
return objValue;
} | javascript | {
"resource": ""
} |
q27509 | getFuncName | train | function getFuncName(func) {
var result = (func.name + ''),
array = realNames[result],
length = hasOwnProperty.call(realNames, result) ? array.length : 0;
while (length--) {
var data = array[length],
otherFunc = data.func;
if (otherFunc == null || otherFunc == func) {
return data.name;
}
}
return result;
} | javascript | {
"resource": ""
} |
q27510 | getWrapDetails | train | function getWrapDetails(source) {
var match = source.match(reWrapDetails);
return match ? match[1].split(reSplitDetails) : [];
} | javascript | {
"resource": ""
} |
q27511 | setWrapToString | train | function setWrapToString(wrapper, reference, bitmask) {
var source = (reference + '');
return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
} | javascript | {
"resource": ""
} |
q27512 | wrapperClone | train | function wrapperClone(wrapper) {
if (wrapper instanceof LazyWrapper) {
return wrapper.clone();
}
var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
result.__actions__ = copyArray(wrapper.__actions__);
result.__index__ = wrapper.__index__;
result.__values__ = wrapper.__values__;
return result;
} | javascript | {
"resource": ""
} |
q27513 | dropRight | train | function dropRight(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
n = length - n;
return baseSlice(array, 0, n < 0 ? 0 : n);
} | javascript | {
"resource": ""
} |
q27514 | findIndex | train | function findIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseFindIndex(array, getIteratee(predicate, 3), index);
} | javascript | {
"resource": ""
} |
q27515 | flattenDeep | train | function flattenDeep(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, INFINITY) : [];
} | javascript | {
"resource": ""
} |
q27516 | fromPairs | train | function fromPairs(pairs) {
var index = -1,
length = pairs == null ? 0 : pairs.length,
result = {};
while (++index < length) {
var pair = pairs[index];
result[pair[0]] = pair[1];
}
return result;
} | javascript | {
"resource": ""
} |
q27517 | initial | train | function initial(array) {
var length = array == null ? 0 : array.length;
return length ? baseSlice(array, 0, -1) : [];
} | javascript | {
"resource": ""
} |
q27518 | sortedIndexOf | train | function sortedIndexOf(array, value) {
var length = array == null ? 0 : array.length;
if (length) {
var index = baseSortedIndex(array, value);
if (index < length && eq(array[index], value)) {
return index;
}
}
return -1;
} | javascript | {
"resource": ""
} |
q27519 | sortedUniqBy | train | function sortedUniqBy(array, iteratee) {
return (array && array.length)
? baseSortedUniq(array, getIteratee(iteratee, 2))
: [];
} | javascript | {
"resource": ""
} |
q27520 | unzip | train | function unzip(array) {
if (!(array && array.length)) {
return [];
}
var length = 0;
array = arrayFilter(array, function(group) {
if (isArrayLikeObject(group)) {
length = nativeMax(group.length, length);
return true;
}
});
return baseTimes(length, function(index) {
return arrayMap(array, baseProperty(index));
});
} | javascript | {
"resource": ""
} |
q27521 | forEachRight | train | function forEachRight(collection, iteratee) {
var func = isArray(collection) ? arrayEachRight : baseEachRight;
return func(collection, getIteratee(iteratee, 3));
} | javascript | {
"resource": ""
} |
q27522 | negate | train | function negate(predicate) {
if (typeof predicate != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function() {
var args = arguments;
switch (args.length) {
case 0: return !predicate.call(this);
case 1: return !predicate.call(this, args[0]);
case 2: return !predicate.call(this, args[0], args[1]);
case 3: return !predicate.call(this, args[0], args[1], args[2]);
}
return !predicate.apply(this, args);
};
} | javascript | {
"resource": ""
} |
q27523 | conformsTo | train | function conformsTo(object, source) {
return source == null || baseConformsTo(object, source, keys(source));
} | javascript | {
"resource": ""
} |
q27524 | create | train | function create(prototype, properties) {
var result = baseCreate(prototype);
return properties == null ? result : baseAssign(result, properties);
} | javascript | {
"resource": ""
} |
q27525 | replace | train | function replace() {
var args = arguments,
string = toString(args[0]);
return args.length < 3 ? string : string.replace(args[1], args[2]);
} | javascript | {
"resource": ""
} |
q27526 | startsWith | train | function startsWith(string, target, position) {
string = toString(string);
position = position == null
? 0
: baseClamp(toInteger(position), 0, string.length);
target = baseToString(target);
return string.slice(position, position + target.length) == target;
} | javascript | {
"resource": ""
} |
q27527 | truncate | train | function truncate(string, options) {
var length = DEFAULT_TRUNC_LENGTH,
omission = DEFAULT_TRUNC_OMISSION;
if (isObject(options)) {
var separator = 'separator' in options ? options.separator : separator;
length = 'length' in options ? toInteger(options.length) : length;
omission = 'omission' in options ? baseToString(options.omission) : omission;
}
string = toString(string);
var strLength = string.length;
if (hasUnicode(string)) {
var strSymbols = stringToArray(string);
strLength = strSymbols.length;
}
if (length >= strLength) {
return string;
}
var end = length - stringSize(omission);
if (end < 1) {
return omission;
}
var result = strSymbols
? castSlice(strSymbols, 0, end).join('')
: string.slice(0, end);
if (separator === undefined) {
return result + omission;
}
if (strSymbols) {
end += (result.length - end);
}
if (isRegExp(separator)) {
if (string.slice(end).search(separator)) {
var match,
substring = result;
if (!separator.global) {
separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');
}
separator.lastIndex = 0;
while ((match = separator.exec(substring))) {
var newEnd = match.index;
}
result = result.slice(0, newEnd === undefined ? end : newEnd);
}
} else if (string.indexOf(baseToString(separator), end) != end) {
var index = result.lastIndexOf(separator);
if (index > -1) {
result = result.slice(0, index);
}
}
return result + omission;
} | javascript | {
"resource": ""
} |
q27528 | cond | train | function cond(pairs) {
var length = pairs == null ? 0 : pairs.length,
toIteratee = getIteratee();
pairs = !length ? [] : arrayMap(pairs, function(pair) {
if (typeof pair[1] != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return [toIteratee(pair[0]), pair[1]];
});
return baseRest(function(args) {
var index = -1;
while (++index < length) {
var pair = pairs[index];
if (apply(pair[0], this, args)) {
return apply(pair[1], this, args);
}
}
});
} | javascript | {
"resource": ""
} |
q27529 | nthArg | train | function nthArg(n) {
n = toInteger(n);
return baseRest(function(args) {
return baseNth(args, n);
});
} | javascript | {
"resource": ""
} |
q27530 | toPath | train | function toPath(value) {
if (isArray(value)) {
return arrayMap(value, toKey);
}
return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
} | javascript | {
"resource": ""
} |
q27531 | train | function(cx, cy, r, width) {
return {type: 'ring', cx: cx, cy: cy, r: r, width: width}
} | javascript | {
"resource": ""
} | |
q27532 | renderStackup | train | function renderStackup(stackupLayers, next) {
var stackup = createStackup(stackupLayers, options)
stackup.layers = stackupLayers
next(null, stackup)
} | javascript | {
"resource": ""
} |
q27533 | makeRenderLayerTask | train | function makeRenderLayerTask(layer) {
return function renderLayer(next) {
var stackupLayer = makeBaseStackupLayer(layer)
if (stackupLayer.converter) return next(null, stackupLayer)
var converter = gerberToSvg(
stackupLayer.gerber,
stackupLayer.options,
function handleLayerDone(error) {
if (error) return next(error)
stackupLayer.converter = converter
next(null, stackupLayer)
}
)
}
} | javascript | {
"resource": ""
} |
q27534 | makeBaseStackupLayer | train | function makeBaseStackupLayer(layer) {
var layerSide = layer.side
var layerType = layer.type
if (
layer.filename &&
typeof layerSide === 'undefined' &&
typeof layerType === 'undefined'
) {
var gerberId = layerTypes[layer.filename]
layerSide = gerberId.side
layerType = gerberId.type
}
var layerOptions = extend(layer.options)
if (layerOptions.plotAsOutline == null && layerType === wtg.TYPE_OUTLINE) {
layerOptions.plotAsOutline = true
}
if (
options &&
options.outlineGapFill != null &&
layerOptions.plotAsOutline
) {
layerOptions.plotAsOutline = options.outlineGapFill
}
return extend(layer, {
side: layerSide,
type: layerType,
options: layerOptions,
})
} | javascript | {
"resource": ""
} |
q27535 | train | function() {
var t = tokens.shift()
var exp
if (RE_NUMBER.test(t)) {
exp = {type: 'n', val: t}
} else {
exp = parseExpression()
tokens.shift()
}
return exp
} | javascript | {
"resource": ""
} | |
q27536 | train | function() {
var exp = parsePrimary()
var t = tokens[0]
if (t === 'X') {
parser._warn("multiplication in macros should use 'x', not 'X'")
t = 'x'
}
while (t === 'x' || t === '/') {
tokens.shift()
var right = parsePrimary()
exp = {type: t, left: exp, right: right}
t = tokens[0]
}
return exp
} | javascript | {
"resource": ""
} | |
q27537 | train | function(op, mods) {
var getValue = function(t) {
if (t[0] === '$') {
return Number(mods[t])
}
return Number(t)
}
var type = op.type
if (type === 'n') {
return getValue(op.val)
}
if (type === '+') {
return evaluate(op.left, mods) + evaluate(op.right, mods)
}
if (type === '-') {
return evaluate(op.left, mods) - evaluate(op.right, mods)
}
if (type === 'x') {
return evaluate(op.left, mods) * evaluate(op.right, mods)
}
// else division
return evaluate(op.left, mods) / evaluate(op.right, mods)
} | javascript | {
"resource": ""
} | |
q27538 | findPrimes | train | function findPrimes(n) {
var i, s, p, ans;
s=new Array(n);
for (i=0; i<n; i++)
s[i]=0;
s[0]=2;
p=0; //first p elements of s are primes, the rest are a sieve
for (;s[p]<n;) { //s[p] is the pth prime
for (i=s[p]*s[p]; i<n; i+=s[p]) //mark multiples of s[p]
s[i]=1;
p++;
s[p]=s[p-1]+1;
for (; s[p]<n && s[s[p]]; s[p]++); //find next prime (where s[p]==0)
}
ans=new Array(p);
for (i=0; i<p; i++)
ans[i]=s[i];
return ans;
} | javascript | {
"resource": ""
} |
q27539 | millerRabinInt | train | function millerRabinInt(x, b) {
if (mr_x1.length!=x.length) {
mr_x1=dup(x);
mr_r=dup(x);
mr_a=dup(x);
}
copyInt_(mr_a, b);
return millerRabin(x, mr_a);
} | javascript | {
"resource": ""
} |
q27540 | bitSize | train | function bitSize(x) {
var j, z, w;
for (j=x.length-1; (x[j]==0) && (j>0); j--);
for (z=0, w=x[j]; w; (w>>=1), z++);
z+=bpe*j;
return z;
} | javascript | {
"resource": ""
} |
q27541 | expand | train | function expand(x, n) {
var ans=int2bigInt(0, (x.length>n ? x.length : n)*bpe, 0);
copy_(ans, x);
return ans;
} | javascript | {
"resource": ""
} |
q27542 | randTruePrime | train | function randTruePrime(k) {
var ans=int2bigInt(0, k, 0);
randTruePrime_(ans, k);
return trim(ans, 1);
} | javascript | {
"resource": ""
} |
q27543 | randProbPrime | train | function randProbPrime(k) {
if (k>=600) return randProbPrimeRounds(k, 2); //numbers from HAC table 4.3
if (k>=550) return randProbPrimeRounds(k, 4);
if (k>=500) return randProbPrimeRounds(k, 5);
if (k>=400) return randProbPrimeRounds(k, 6);
if (k>=350) return randProbPrimeRounds(k, 7);
if (k>=300) return randProbPrimeRounds(k, 9);
if (k>=250) return randProbPrimeRounds(k, 12); //numbers from HAC table 4.4
if (k>=200) return randProbPrimeRounds(k, 15);
if (k>=150) return randProbPrimeRounds(k, 18);
if (k>=100) return randProbPrimeRounds(k, 27);
return randProbPrimeRounds(k, 40); //number from HAC remark 4.26 (only an estimate)
} | javascript | {
"resource": ""
} |
q27544 | randBigInt_ | train | function randBigInt_(b, n, s) {
var i, a;
for (i=0; i<b.length; i++)
b[i]=0;
a=Math.floor((n-1)/bpe)+1; //# array elements to hold the BigInt
for (i=0; i<a; i++) {
b[i]=Math.floor(Math.random()*(1<<(bpe-1)));
}
b[a-1] &= (2<<((n-1)%bpe))-1;
if (s==1)
b[a-1] |= (1<<((n-1)%bpe));
} | javascript | {
"resource": ""
} |
q27545 | carry_ | train | function carry_(x) {
var i, k, c, b;
k=x.length;
c=0;
for (i=0; i<k; i++) {
c+=x[i];
b=0;
if (c<0) {
b=-(c>>bpe);
c+=b*radix;
}
x[i]=c & mask;
c=(c>>bpe)-b;
}
} | javascript | {
"resource": ""
} |
q27546 | modInt | train | function modInt(x, n) {
var i, c=0;
for (i=x.length-1; i>=0; i--)
c=(c*radix+x[i])%n;
return c;
} | javascript | {
"resource": ""
} |
q27547 | equals | train | function equals(x, y) {
var i;
var k=x.length<y.length ? x.length : y.length;
for (i=0; i<k; i++)
if (x[i]!=y[i])
return 0;
if (x.length>y.length) {
for (;i<x.length; i++)
if (x[i])
return 0;
} else {
for (;i<y.length; i++)
if (y[i])
return 0;
}
return 1;
} | javascript | {
"resource": ""
} |
q27548 | mod_ | train | function mod_(x, n) {
if (s4.length!=x.length)
s4=dup(x);
else
copy_(s4, x);
if (s5.length!=x.length)
s5=dup(x);
divide_(s4, n, s5, x); //x = remainder of s4 / n
} | javascript | {
"resource": ""
} |
q27549 | trim | train | function trim(x, k) {
var i, y;
for (i=x.length; i>0 && !x[i-1]; i--);
y=new Array(i+k);
copy_(y, x);
return y;
} | javascript | {
"resource": ""
} |
q27550 | parseIcon | train | function parseIcon(icon = "none") {
if (!!icon && icon !== "none") {
if (typeof icon === "string") {
return { icon, position: "left", style: {} };
}
return { position: "left", style: {}, ...icon };
}
return null;
} | javascript | {
"resource": ""
} |
q27551 | getOptions | train | function getOptions (ctx) {
const { vnode } = ctx
const { value } = ctx.binding
if (process.env.NODE_ENV !== 'production' && (isUndefined(value) || !isObject(value))) {
warn('v-position -> configuration is missing or is not an Object', vnode.context)
}
const options = assign({
target: null,
position: 'top-center',
boundary: window,
flip: true,
offset: false,
mainClass: ''
}, value)
return options
} | javascript | {
"resource": ""
} |
q27552 | getContext | train | function getContext (el, binding, vnode) {
const ctx = { el, binding, vnode }
ctx.props = getOptions(ctx)
if (!ctx.props) {
binding.def.unbind(el, binding)
return
}
return ctx
} | javascript | {
"resource": ""
} |
q27553 | extractSetterFromNode | train | function extractSetterFromNode( handler, node ) {
assignSetterFnForNode( handler, node );
if ( node.children ) {
// Recurse down to this node's children
Object.keys( node.children ).forEach( ( key ) => {
extractSetterFromNode( handler, node.children[ key ] );
} );
}
} | javascript | {
"resource": ""
} |
q27554 | createNodeHandlerSpec | train | function createNodeHandlerSpec( routeDefinition, resource ) {
const handler = {
// A "path" is an ordered (by key) set of values composed into the final URL
_path: {
'0': resource,
},
// A "level" is a level-keyed object representing the valid options for
// one level of the resource URL
_levels: {},
// Objects that hold methods and properties which will be copied to
// instances of this endpoint's handler
_setters: {},
// Arguments (query parameters) that may be set in GET requests to endpoints
// nested within this resource route tree, used to determine the mixins to
// add to the request handler
_getArgs: routeDefinition._getArgs,
};
// Walk the tree
Object.keys( routeDefinition ).forEach( ( routeDefProp ) => {
if ( routeDefProp !== '_getArgs' ) {
extractSetterFromNode( handler, routeDefinition[ routeDefProp ] );
}
} );
return handler;
} | javascript | {
"resource": ""
} |
q27555 | createPathPartSetter | train | function createPathPartSetter( node ) {
// Local references to `node` properties used by returned functions
const nodeLevel = node.level;
const nodeName = node.names[ 0 ];
const supportedMethods = node.methods || [];
const dynamicChildren = node.children ?
Object.keys( node.children )
.map( key => node.children[ key ] )
.filter( childNode => ( childNode.namedGroup === true ) ) :
[];
const dynamicChild = dynamicChildren.length === 1 && dynamicChildren[ 0 ];
const dynamicChildLevel = dynamicChild && dynamicChild.level;
if ( node.namedGroup ) {
/**
* Set a dymanic (named-group) path part of a query URL.
*
* @example
*
* // id() is a dynamic path part setter:
* wp.posts().id( 7 ); // Get posts/7
*
* @chainable
* @param {String|Number} val The path part value to set
* @returns {Object} The handler instance (for chaining)
*/
return function( val ) {
this.setPathPart( nodeLevel, val );
if ( supportedMethods.length ) {
this._supportedMethods = supportedMethods;
}
return this;
};
} else {
/**
* Set a non-dymanic (non-named-group) path part of a query URL, and
* set the value of a subresource if an input value is provided and
* exactly one named-group child node exists.
*
* @example
*
* // revisions() is a non-dynamic path part setter:
* wp.posts().id( 4 ).revisions(); // Get posts/4/revisions
* wp.posts().id( 4 ).revisions( 1372 ); // Get posts/4/revisions/1372
*
* @chainable
* @param {String|Number} [val] The path part value to set (if provided)
* for a subresource within this resource
* @returns {Object} The handler instance (for chaining)
*/
return function( val ) {
// If the path part is not a namedGroup, it should have exactly one
// entry in the names array: use that as the value for this setter,
// as it will usually correspond to a collection endpoint.
this.setPathPart( nodeLevel, nodeName );
// If this node has exactly one dynamic child, this method may act as
// a setter for that child node. `dynamicChildLevel` will be falsy if the
// node does not have a child or has multiple children.
if ( val !== undefined && dynamicChildLevel ) {
this.setPathPart( dynamicChildLevel, val );
}
return this;
};
}
} | javascript | {
"resource": ""
} |
q27556 | registerRoute | train | function registerRoute( namespace, restBase, options = {} ) {
// Support all methods until requested to do otherwise
let supportedMethods = [ 'head', 'get', 'patch', 'put', 'post', 'delete' ];
if ( Array.isArray( options.methods ) ) {
// Permit supported methods to be specified as an array
supportedMethods = options.methods.map( method => method.trim().toLowerCase() );
} else if ( typeof options.methods === 'string' ) {
// Permit a supported method to be specified as a string
supportedMethods = [ options.methods.trim().toLowerCase() ];
}
// Ensure that if GET is supported, then HEAD is as well, and vice-versa
if ( supportedMethods.indexOf( 'get' ) !== -1 && supportedMethods.indexOf( 'head' ) === -1 ) {
supportedMethods.push( 'head' );
} else if ( supportedMethods.indexOf( 'head' ) !== -1 && supportedMethods.indexOf( 'get' ) === -1 ) {
supportedMethods.push( 'get' );
}
const fullRoute = namespace
// Route should always have preceding slash
.replace( /^[\s/]*/, '/' )
// Route should always be joined to namespace with a single slash
.replace( /[\s/]*$/, '/' ) + restBase.replace( /^[\s/]*/, '' );
const routeObj = {};
routeObj[ fullRoute ] = {
namespace: namespace,
methods: supportedMethods,
};
// Go through the same steps used to bootstrap the client to parse the
// provided route out into a handler request method
const routeTree = buildRouteTree( routeObj );
// Parse the mock route object into endpoint factories
const endpointFactories = generateEndpointFactories( routeTree )[ namespace ];
const EndpointRequest = endpointFactories[ Object.keys( endpointFactories )[ 0 ] ].Ctor;
if ( options && options.params ) {
options.params.forEach( ( param ) => {
// Only accept string parameters
if ( typeof param !== 'string' ) {
return;
}
// If the parameter can be mapped to a mixin, apply that mixin
if ( typeof mixins[ param ] === 'object' ) {
Object.keys( mixins[ param ] ).forEach( ( key ) => {
applyMixin( EndpointRequest.prototype, key, mixins[ param ][ key ] );
} );
return;
}
// Attempt to create a simple setter for any parameters for which
// we do not already have a custom mixin
applyMixin( EndpointRequest.prototype, param, paramSetter( param ) );
} );
}
// Set any explicitly-provided object mixins
if ( options && typeof options.mixins === 'object' ) {
// Set any specified mixin functions on the response
Object.keys( options.mixins ).forEach( ( key ) => {
applyMixin( EndpointRequest.prototype, key, options.mixins[ key ] );
} );
}
function endpointFactory( options = {} ) {
return new EndpointRequest( {
...options,
...( this ? this._options : {} ),
} );
}
endpointFactory.Ctor = EndpointRequest;
return endpointFactory;
} | javascript | {
"resource": ""
} |
q27557 | reduceRouteComponents | train | function reduceRouteComponents( routeObj, topLevel, parentLevel, component, idx, components ) {
// Check to see if this component is a dynamic URL segment (i.e. defined by
// a named capture group regular expression). namedGroup will be `null` if
// the regexp does not match, or else an array defining the RegExp match, e.g.
// [
// 'P<id>[\\d]+)',
// 'id', // Name of the group
// '[\\d]+', // regular expression for this URL segment's contents
// index: 15,
// input: '/wp/v2/posts/(?P<id>[\\d]+)'
// ]
const namedGroup = component.match( namedGroupRE );
// Pull out references to the relevant indices of the match, for utility:
// `null` checking is necessary in case the component did not match the RE,
// hence the `namedGroup &&`.
const groupName = namedGroup && namedGroup[ 1 ];
const groupPattern = namedGroup && namedGroup[ 2 ];
// When branching based on a dynamic capture group we used the group's RE
// pattern as the unique identifier: this is done because the same group
// could be assigned different names in different endpoint handlers, e.g.
// "id" for posts/:id vs "parent_id" for posts/:parent_id/revisions.
//
// There is an edge case where groupPattern will be "" if we are registering
// a custom route via `.registerRoute` that does not include parameter
// validation. In this case we assume the groupName is sufficiently unique,
// and fall back to `|| groupName` for the levelKey string.
const levelKey = namedGroup ? ( groupPattern || groupName ) : component;
// Level name on the other hand takes its value from the group's name, if
// defined, and falls back to the component string to handle situations where
// `component` is a collection (e.g. "revisions")
const levelName = namedGroup ? groupName : component;
// Check whether we have a preexisting node at this level of the tree, and
// create a new level object if not. The component string is included so that
// validators can throw meaningful errors as appropriate.
const currentLevel = parentLevel[ levelKey ] || {
component: component,
namedGroup: namedGroup ? true : false,
level: idx,
names: [],
};
// A level's "names" correspond to the list of strings which could describe
// an endpoint's component setter functions: "id", "revisions", etc.
if ( currentLevel.names.indexOf( levelName ) < 0 ) {
currentLevel.names.push( levelName );
}
// A level's validate method is called to check whether a value being set
// on the request URL is of the proper type for the location in which it
// is specified. If a group pattern was found, the validator checks whether
// the input string exactly matches the group pattern.
const groupPatternRE = groupPattern === '' ?
// If groupPattern is an empty string, accept any input without validation
/.*/ :
// Otherwise, validate against the group pattern or the component string
new RegExp( groupPattern ? '^' + groupPattern + '$' : component, 'i' );
// Only one validate function is maintained for each node, because each node
// is defined either by a string literal or by a specific regular expression.
currentLevel.validate = input => groupPatternRE.test( input );
// Check to see whether to expect more nodes within this branch of the tree,
if ( components[ idx + 1 ] ) {
// and create a "children" object to hold those nodes if necessary
currentLevel.children = currentLevel.children || {};
} else {
// At leaf nodes, specify the method capabilities of this endpoint
currentLevel.methods = ( routeObj.methods || [] ).map( str => str.toLowerCase() );
// Ensure HEAD is included whenever GET is supported: the API automatically
// adds support for HEAD if you have GET
if ( currentLevel.methods.indexOf( 'get' ) > -1 && currentLevel.methods.indexOf( 'head' ) === -1 ) {
currentLevel.methods.push( 'head' );
}
// At leaf nodes also flag (at the top level) what arguments are
// available to GET requests, so that we may automatically apply the
// appropriate parameter mixins
if ( routeObj.endpoints ) {
topLevel._getArgs = topLevel._getArgs || {};
routeObj.endpoints.forEach( ( endpoint ) => {
// `endpoint.methods` will be an array of methods like `[ 'GET' ]`: we
// only care about GET for this exercise. Validating POST and PUT args
// could be useful but is currently deemed to be out-of-scope.
endpoint.methods.forEach( ( method ) => {
if ( method.toLowerCase() === 'get' ) {
Object.keys( endpoint.args ).forEach( ( argKey ) => {
// Reference param definition objects in the top _getArgs dictionary
topLevel._getArgs[ argKey ] = endpoint.args[ argKey ];
} );
}
} );
} );
}
}
// Return the child node object as the new "level"
parentLevel[ levelKey ] = currentLevel;
return currentLevel.children;
} | javascript | {
"resource": ""
} |
q27558 | WPAPI | train | function WPAPI( options ) {
// Enforce `new`
if ( this instanceof WPAPI === false ) {
return new WPAPI( options );
}
if ( typeof options.endpoint !== 'string' ) {
throw new Error( 'options hash must contain an API endpoint URL string' );
}
// Dictionary to be filled by handlers for default namespaces
this._ns = {};
this._options = {
// Ensure trailing slash on endpoint URI
endpoint: options.endpoint.replace( /\/?$/, '/' ),
};
// If any authentication credentials were provided, assign them now
if ( options && ( options.username || options.password || options.nonce ) ) {
this.auth( options );
}
return this
// Configure custom HTTP transport methods, if provided
.transport( options.transport )
// Bootstrap with a specific routes object, if provided
.bootstrap( options && options.routes );
} | javascript | {
"resource": ""
} |
q27559 | WPRequest | train | function WPRequest( options ) {
/**
* Configuration options for the request
*
* @property _options
* @type Object
* @private
* @default {}
*/
this._options = [
// Whitelisted options keys
'auth',
'endpoint',
'headers',
'username',
'password',
'nonce',
].reduce( ( localOptions, key ) => {
if ( options && options[ key ] ) {
localOptions[ key ] = options[ key ];
}
return localOptions;
}, {} );
/**
* The HTTP transport methods (.get, .post, .put, .delete, .head) to use for this request
*
* @property transport
* @type {Object}
* @private
*/
this.transport = options && options.transport;
/**
* A hash of query parameters
* This is used to store the values for supported query parameters like ?_embed
*
* @property _params
* @type Object
* @private
* @default {}
*/
this._params = {};
/**
* Methods supported by this API request instance:
* Individual endpoint handlers specify their own subset of supported methods
*
* @property _supportedMethods
* @type Array
* @private
* @default [ 'head', 'get', 'put', 'post', 'delete' ]
*/
this._supportedMethods = [ 'head', 'get', 'put', 'post', 'delete' ];
/**
* A hash of values to assemble into the API request path
* (This will be overwritten by each specific endpoint handler constructor)
*
* @property _path
* @type Object
* @private
* @default {}
*/
this._path = {};
} | javascript | {
"resource": ""
} |
q27560 | createEndpointRequest | train | function createEndpointRequest( handlerSpec, resource, namespace ) {
// Create the constructor function for this endpoint
class EndpointRequest extends WPRequest {
constructor( options ) {
super( options );
/**
* Semi-private instance property specifying the available URL path options
* for this endpoint request handler, keyed by ascending whole numbers.
*
* @property _levels
* @type {object}
* @private
*/
this._levels = handlerSpec._levels;
// Configure handler for this endpoint's root URL path & set namespace
this
.setPathPart( 0, resource )
.namespace( namespace );
}
}
// Mix in all available shortcut methods for GET request query parameters that
// are valid within this endpoint tree
if ( typeof handlerSpec._getArgs === 'object' ) {
Object.keys( handlerSpec._getArgs ).forEach( ( supportedQueryParam ) => {
const mixinsForParam = mixins[ supportedQueryParam ];
// Only proceed if there is a mixin available AND the specified mixins will
// not overwrite any previously-set prototype method
if ( typeof mixinsForParam === 'object' ) {
Object.keys( mixinsForParam ).forEach( ( methodName ) => {
applyMixin( EndpointRequest.prototype, methodName, mixinsForParam[ methodName ] );
} );
}
} );
}
Object.keys( handlerSpec._setters ).forEach( ( setterFnName ) => {
// Only assign setter functions if they do not overwrite preexisting methods
if ( ! EndpointRequest.prototype[ setterFnName ] ) {
EndpointRequest.prototype[ setterFnName ] = handlerSpec._setters[ setterFnName ];
}
} );
return EndpointRequest;
} | javascript | {
"resource": ""
} |
q27561 | _setHeaders | train | function _setHeaders( request, options ) {
// If there's no headers, do nothing
if ( ! options.headers ) {
return request;
}
return objectReduce(
options.headers,
( request, value, key ) => request.set( key, value ),
request
);
} | javascript | {
"resource": ""
} |
q27562 | _auth | train | function _auth( request, options, forceAuthentication ) {
// If we're not supposed to authenticate, don't even start
if ( ! forceAuthentication && ! options.auth && ! options.nonce ) {
return request;
}
// Enable nonce in options for Cookie authentication http://wp-api.org/guides/authentication.html
if ( options.nonce ) {
request.set( 'X-WP-Nonce', options.nonce );
return request;
}
// Retrieve the username & password from the request options if they weren't provided
const username = options.username;
const password = options.password;
// If no username or no password, can't authenticate
if ( ! username || ! password ) {
return request;
}
// Can authenticate: set basic auth parameters on the request
return request.auth( username, password );
} | javascript | {
"resource": ""
} |
q27563 | createPaginationObject | train | function createPaginationObject( result, options, httpTransport ) {
let _paging = null;
if ( ! result.headers ) {
// No headers: return as-is
return _paging;
}
// Guard against capitalization inconsistencies in returned headers
Object.keys( result.headers ).forEach( ( header ) => {
result.headers[ header.toLowerCase() ] = result.headers[ header ];
} );
if ( ! result.headers[ 'x-wp-totalpages' ] ) {
// No paging: return as-is
return _paging;
}
const totalPages = +result.headers[ 'x-wp-totalpages' ];
if ( ! totalPages || totalPages === 0 ) {
// No paging: return as-is
return _paging;
}
// Decode the link header object
const links = result.headers.link ?
parseLinkHeader( result.headers.link ) :
{};
// Store pagination data from response headers on the response collection
_paging = {
total: +result.headers[ 'x-wp-total' ],
totalPages: totalPages,
links: links,
};
// Create a WPRequest instance pre-bound to the "next" page, if available
if ( links.next ) {
_paging.next = new WPRequest( {
...options,
transport: httpTransport,
endpoint: links.next,
} );
}
// Create a WPRequest instance pre-bound to the "prev" page, if available
if ( links.prev ) {
_paging.prev = new WPRequest( {
...options,
transport: httpTransport,
endpoint: links.prev,
} );
}
return _paging;
} | javascript | {
"resource": ""
} |
q27564 | returnBody | train | function returnBody( wpreq, result ) {
const body = extractResponseBody( result );
const _paging = createPaginationObject( result, wpreq._options, wpreq.transport );
if ( _paging ) {
body._paging = _paging;
}
return body;
} | javascript | {
"resource": ""
} |
q27565 | _httpPost | train | function _httpPost( wpreq, data, callback ) {
checkMethodSupport( 'post', wpreq );
const url = wpreq.toString();
data = data || {};
let request = _auth( agent.post( url ), wpreq._options, true );
request = _setHeaders( request, wpreq._options );
if ( wpreq._attachment ) {
// Data must be form-encoded alongside image attachment
request = objectReduce(
data,
( req, value, key ) => req.field( key, value ),
request.attach( 'file', wpreq._attachment, wpreq._attachmentName )
);
} else {
request = request.send( data );
}
return invokeAndPromisify( request, callback, returnBody.bind( null, wpreq ) );
} | javascript | {
"resource": ""
} |
q27566 | applyEnv | train | function applyEnv(env, secrets = {}, required = {}) {
if (Array.isArray(env)) {
env.forEach(key => {
// if the key already exists don't overwrite it
if (!process.env[key]) {
const value = getValue(key, {}, secrets, required)
process.env[key] = value
}
})
} else {
Object.entries(env).forEach(([key, value]) => {
// if the key already exists don't overwrite it
if (!process.env[key]) {
const value = getValue(key, env, secrets, required)
process.env[key] = value
}
})
}
} | javascript | {
"resource": ""
} |
q27567 | config | train | function config() {
// only run this if it's not running inside Now.sh
if (Boolean(process.env.NOW_REGION || process.env.NOW)) return
const secrets = loadSecrets()
const required = loadRequired()
// load environment variables from now.json
loadNowJSON(secrets, required)
} | javascript | {
"resource": ""
} |
q27568 | setupCache | train | function setupCache (config = {}) {
// Extend default configuration
config = makeConfig(config)
// Axios adapter. Receives the axios request configuration as only parameter
async function adapter (req) {
// Merge the per-request config with the instance config.
const reqConfig = mergeRequestConfig(config, req)
// Execute request against local cache
let res = await request(reqConfig, req)
let next = res.next
// Response is not function, something was in cache, return it
if (!isFunction(next)) return next
// Nothing in cache so we execute the default adapter or any given adapter
// Will throw if the request has a status different than 2xx
let networkError
try {
res = await reqConfig.adapter(req)
} catch (err) {
networkError = err
}
if (networkError) {
// Check if we should attempt reading stale cache data
let readOnError = isFunction(reqConfig.readOnError)
? reqConfig.readOnError(networkError, req)
: reqConfig.readOnError
if (readOnError) {
try {
// Force cache tu return stale data
reqConfig.acceptStale = true
// Try to read from cache again
res = await request(reqConfig, req)
// Signal that data is from stale cache
res.next.request.stale = true
// No need to check if `next` is a function just return cache data
return res.next
} catch (cacheReadError) {
// Failed to read stale cache, do nothing here, just let the network error be thrown
}
}
// Re-throw error so that it can be caught in userland if we didn't find any stale cache to read
throw networkError
}
// Process response to store in cache
return next(res)
}
// Return adapter and store instance
return {
adapter,
config,
store: config.store
}
} | javascript | {
"resource": ""
} |
q27569 | buildSolidBrush | train | function buildSolidBrush(color, alpha) {
let component;
component = (color >> 16) & 0xff;
const R = component / 255;
component = (color >> 8) & 0xff;
const G = component / 255;
component = color & 0xff;
const B = component / 255;
const A = alpha;
const brush = new libui.DrawBrush();
brush.color = new libui.Color(R, G, B, A);
brush.type = libui.brushType.solid;
return brush;
} | javascript | {
"resource": ""
} |
q27570 | train | function(suffix) {
return function(now, tween) {
var floored_number = Math.floor(now),
target = $(tween.elem);
target.prop('number', now).text(floored_number + suffix);
};
} | javascript | {
"resource": ""
} | |
q27571 | train | function(separator, group_length, suffix) {
separator = separator || ' ';
group_length = group_length || 3;
suffix = suffix || '';
return function(now, tween) {
var negative = now < 0,
floored_number = Math.floor((negative ? -1 : 1) * now),
separated_number = floored_number.toString(),
target = $(tween.elem);
if (separated_number.length > group_length) {
var number_parts = extract_number_parts(separated_number, group_length);
separated_number = remove_precending_zeros(number_parts).join(separator);
separated_number = reverse(separated_number);
}
target.prop('number', now).text((negative ? '-' : '') + separated_number + suffix);
};
} | javascript | {
"resource": ""
} | |
q27572 | getMarkupFromData | train | function getMarkupFromData(dataForSingleItem) {
var name = dataForSingleItem.first_name + ' ' + dataForSingleItem.last_name;
// https://www.paulirish.com/2009/random-hex-color-code-snippets/
var randomColor = ('000000' + Math.random().toString(16).slice(2, 8)).slice(-6);
return [
'<div class="js-item col-3@xs col-3@sm person-item" data-id="' + dataForSingleItem.id + '">',
'<div class="person-item__inner" style="background-color:#' + randomColor + '">',
'<span>' + name + '</span>',
'</div>',
'</div>',
].join('');
} | javascript | {
"resource": ""
} |
q27573 | replaceLoadMoreButton | train | function replaceLoadMoreButton() {
var text = document.createTextNode('All users loaded');
var replacement = document.createElement('p');
replacement.appendChild(text);
loadMoreButton.parentNode.replaceChild(replacement, loadMoreButton);
} | javascript | {
"resource": ""
} |
q27574 | PhotoItem | train | function PhotoItem({ id, username, src, name }) {
return (
<div key={id} className="col-3@xs col-4@sm photo-item">
<div className="aspect aspect--4x3">
<div className="aspect__inner">
<img src={src} />
<PhotoAttribution username={username} name={name} />
</div>
</div>
</div>
)
} | javascript | {
"resource": ""
} |
q27575 | PhotoAttribution | train | function PhotoAttribution({ username, name }) {
if (!username) {
return null;
}
const href = `https://unsplash.com/${username}?utm_medium=referral&utm_campaign=photographer-credit&utm_content=creditBadge`;
const title = `Download free do whatever you want high-resolution photos from ${name}`;
return (
<a className="photo-attribution" href={href} target="_blank" rel="noopener noreferrer" title={title}>
<span>
<svg viewBox="0 0 32 32">
<path d="M20.8 18.1c0 2.7-2.2 4.8-4.8 4.8s-4.8-2.1-4.8-4.8c0-2.7 2.2-4.8 4.8-4.8 2.7.1 4.8 2.2 4.8 4.8zm11.2-7.4v14.9c0 2.3-1.9 4.3-4.3 4.3h-23.4c-2.4 0-4.3-1.9-4.3-4.3v-15c0-2.3 1.9-4.3 4.3-4.3h3.7l.8-2.3c.4-1.1 1.7-2 2.9-2h8.6c1.2 0 2.5.9 2.9 2l.8 2.4h3.7c2.4 0 4.3 1.9 4.3 4.3zm-8.6 7.5c0-4.1-3.3-7.5-7.5-7.5-4.1 0-7.5 3.4-7.5 7.5s3.3 7.5 7.5 7.5c4.2-.1 7.5-3.4 7.5-7.5z"></path>
</svg>
</span>
<span>{name}</span>
</a>
);
} | javascript | {
"resource": ""
} |
q27576 | addToList | train | function addToList(i, L, R) {
R[L[i + 1]] = R[i];
L[R[i]] = L[i + 1];
R[i] = i + 1;
L[i + 1] = i;
} | javascript | {
"resource": ""
} |
q27577 | removeFromList | train | function removeFromList(i, L, R) {
R[L[i]] = R[i];
L[R[i]] = L[i];
R[i] = i;
L[i] = i;
} | javascript | {
"resource": ""
} |
q27578 | breakInsideToken | train | function breakInsideToken(tokens, tokenIndex, breakIndex, removeBreakChar) {
let newBreakToken = {
type: TYPE_NEWLINE
};
let newTextToken = {
type: TYPE_TEXT,
value: tokens[tokenIndex].value.substring(breakIndex + (removeBreakChar ? 1 : 0))
};
tokens.splice(tokenIndex + 1, 0, newBreakToken, newTextToken);
return tokens[tokenIndex].value.substring(0, breakIndex);
} | javascript | {
"resource": ""
} |
q27579 | insertAfter | train | function insertAfter(newNode, referenceNode) {
if (!referenceNode.parentNode) {
referenceNode = AFRAME.INSPECTOR.selectedEntity;
}
if (!referenceNode) {
AFRAME.INSPECTOR.sceneEl.appendChild(newNode);
} else {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
} | javascript | {
"resource": ""
} |
q27580 | prepareForSerialization | train | function prepareForSerialization(entity) {
var clone = entity.cloneNode(false);
var children = entity.childNodes;
for (var i = 0, l = children.length; i < l; i++) {
var child = children[i];
if (
child.nodeType !== Node.ELEMENT_NODE ||
(!child.hasAttribute('aframe-injected') &&
!child.hasAttribute('data-aframe-inspector') &&
!child.hasAttribute('data-aframe-canvas'))
) {
clone.appendChild(prepareForSerialization(children[i]));
}
}
optimizeComponents(clone, entity);
return clone;
} | javascript | {
"resource": ""
} |
q27581 | optimizeComponents | train | function optimizeComponents(copy, source) {
var removeAttribute = HTMLElement.prototype.removeAttribute;
var setAttribute = HTMLElement.prototype.setAttribute;
var components = source.components || {};
Object.keys(components).forEach(function(name) {
var component = components[name];
var result = getImplicitValue(component, source);
var isInherited = result[1];
var implicitValue = result[0];
var currentValue = source.getAttribute(name);
var optimalUpdate = getOptimalUpdate(
component,
implicitValue,
currentValue
);
var doesNotNeedUpdate = optimalUpdate === null;
if (isInherited && doesNotNeedUpdate) {
removeAttribute.call(copy, name);
} else {
var schema = component.schema;
var value = stringifyComponentValue(schema, optimalUpdate);
setAttribute.call(copy, name, value);
}
});
} | javascript | {
"resource": ""
} |
q27582 | getImplicitValue | train | function getImplicitValue(component, source) {
var isInherited = false;
var value = (isSingleProperty(component.schema) ? _single : _multi)();
return [value, isInherited];
function _single() {
var value = getMixedValue(component, null, source);
if (value === undefined) {
value = getInjectedValue(component, null, source);
}
if (value !== undefined) {
isInherited = true;
} else {
value = getDefaultValue(component, null, source);
}
if (value !== undefined) {
// XXX: This assumes parse is idempotent
return component.schema.parse(value);
}
return value;
}
function _multi() {
var value;
Object.keys(component.schema).forEach(function(propertyName) {
var propertyValue = getFromAttribute(component, propertyName, source);
if (propertyValue === undefined) {
propertyValue = getMixedValue(component, propertyName, source);
}
if (propertyValue === undefined) {
propertyValue = getInjectedValue(component, propertyName, source);
}
if (propertyValue !== undefined) {
isInherited = isInherited || true;
} else {
propertyValue = getDefaultValue(component, propertyName, source);
}
if (propertyValue !== undefined) {
var parse = component.schema[propertyName].parse;
value = value || {};
// XXX: This assumes parse is idempotent
value[propertyName] = parse(propertyValue);
}
});
return value;
}
} | javascript | {
"resource": ""
} |
q27583 | getFromAttribute | train | function getFromAttribute(component, propertyName, source) {
var value;
var mappings = source.mappings || {};
var route = component.name + '.' + propertyName;
var primitiveAttribute = findAttribute(mappings, route);
if (primitiveAttribute && source.hasAttribute(primitiveAttribute)) {
value = source.getAttribute(primitiveAttribute);
}
return value;
function findAttribute(mappings, route) {
var attributes = Object.keys(mappings);
for (var i = 0, l = attributes.length; i < l; i++) {
var attribute = attributes[i];
if (mappings[attribute] === route) {
return attribute;
}
}
return undefined;
}
} | javascript | {
"resource": ""
} |
q27584 | getMixedValue | train | function getMixedValue(component, propertyName, source) {
var value;
var reversedMixins = source.mixinEls.reverse();
for (var i = 0; value === undefined && i < reversedMixins.length; i++) {
var mixin = reversedMixins[i];
if (mixin.attributes.hasOwnProperty(component.name)) {
if (!propertyName) {
value = mixin.getAttribute(component.name);
} else {
value = mixin.getAttribute(component.name)[propertyName];
}
}
}
return value;
} | javascript | {
"resource": ""
} |
q27585 | getInjectedValue | train | function getInjectedValue(component, propertyName, source) {
var value;
var primitiveDefaults = source.defaultComponentsFromPrimitive || {};
var aFrameDefaults = source.defaultComponents || {};
var defaultSources = [primitiveDefaults, aFrameDefaults];
for (var i = 0; value === undefined && i < defaultSources.length; i++) {
var defaults = defaultSources[i];
if (defaults.hasOwnProperty(component.name)) {
if (!propertyName) {
value = defaults[component.name];
} else {
value = defaults[component.name][propertyName];
}
}
}
return value;
} | javascript | {
"resource": ""
} |
q27586 | getDefaultValue | train | function getDefaultValue(component, propertyName, source) {
if (!propertyName) {
return component.schema.default;
}
return component.schema[propertyName].default;
} | javascript | {
"resource": ""
} |
q27587 | getOptimalUpdate | train | function getOptimalUpdate(component, implicit, reference) {
if (equal(implicit, reference)) {
return null;
}
if (isSingleProperty(component.schema)) {
return reference;
}
var optimal = {};
Object.keys(reference).forEach(function(key) {
var needsUpdate = !equal(reference[key], implicit[key]);
if (needsUpdate) {
optimal[key] = reference[key];
}
});
return optimal;
} | javascript | {
"resource": ""
} |
q27588 | getUniqueId | train | function getUniqueId(baseId) {
if (!document.getElementById(baseId)) {
return baseId;
}
var i = 2;
// If the baseId ends with _#, it extracts the baseId removing the suffix
var groups = baseId.match(/(\w+)-(\d+)/);
if (groups) {
baseId = groups[1];
i = groups[2];
}
while (document.getElementById(baseId + '-' + i)) {
i++;
}
return baseId + '-' + i;
} | javascript | {
"resource": ""
} |
q27589 | getModifiedProperties | train | function getModifiedProperties(entity, componentName) {
var data = entity.components[componentName].data;
var defaultData = entity.components[componentName].schema;
var diff = {};
for (var key in data) {
// Prevent adding unknown attributes
if (!defaultData[key]) {
continue;
}
var defaultValue = defaultData[key].default;
var currentValue = data[key];
// Some parameters could be null and '' like mergeTo
if ((currentValue || defaultValue) && currentValue !== defaultValue) {
diff[key] = data[key];
}
}
return diff;
} | javascript | {
"resource": ""
} |
q27590 | train | function(focusEl) {
this.opened = true;
Events.emit('inspectortoggle', true);
if (this.sceneEl.hasAttribute('embedded')) {
// Remove embedded styles, but keep track of it.
this.sceneEl.removeAttribute('embedded');
this.sceneEl.setAttribute('aframe-inspector-removed-embedded');
}
document.body.classList.add('aframe-inspector-opened');
this.sceneEl.resize();
this.sceneEl.pause();
this.sceneEl.exitVR();
Shortcuts.enable();
// Trick scene to run the cursor tick.
this.sceneEl.isPlaying = true;
this.cursor.play();
if (
!focusEl &&
this.isFirstOpen &&
AFRAME.utils.getUrlParameter('inspector')
) {
// Focus entity with URL parameter on first open.
focusEl = document.getElementById(
AFRAME.utils.getUrlParameter('inspector')
);
}
if (focusEl) {
this.selectEntity(focusEl);
Events.emit('objectfocus', focusEl.object3D);
}
this.isFirstOpen = false;
} | javascript | {
"resource": ""
} | |
q27591 | train | function() {
this.opened = false;
Events.emit('inspectortoggle', false);
// Untrick scene when we enabled this to run the cursor tick.
this.sceneEl.isPlaying = false;
this.sceneEl.play();
this.cursor.pause();
if (this.sceneEl.hasAttribute('aframe-inspector-removed-embedded')) {
this.sceneEl.setAttribute('embedded', '');
this.sceneEl.removeAttribute('aframe-inspector-removed-embedded');
}
document.body.classList.remove('aframe-inspector-opened');
this.sceneEl.resize();
Shortcuts.disable();
} | javascript | {
"resource": ""
} | |
q27592 | train | function() {
var xhr = new XMLHttpRequest();
var url = assetsBaseUrl + assetsRelativeUrl['images'];
// @todo Remove the sync call and use a callback
xhr.open('GET', url);
xhr.onload = () => {
var data = JSON.parse(xhr.responseText);
this.images = data.images;
this.images.forEach(image => {
image.fullPath = assetsBaseUrl + data.basepath.images + image.path;
image.fullThumbPath =
assetsBaseUrl + data.basepath.images_thumbnails + image.thumbnail;
});
Events.emit('assetsimagesload', this.images);
};
xhr.onerror = () => {
console.error('Error loading registry file.');
};
xhr.send();
this.hasLoaded = true;
} | javascript | {
"resource": ""
} | |
q27593 | onDoubleClick | train | function onDoubleClick(event) {
const array = getMousePosition(
inspector.container,
event.clientX,
event.clientY
);
onDoubleClickPosition.fromArray(array);
const intersectedEl = mouseCursor.components.cursor.intersectedEl;
if (!intersectedEl) {
return;
}
Events.emit('objectfocus', intersectedEl.object3D);
} | javascript | {
"resource": ""
} |
q27594 | equalArray | train | function equalArray(array1, array2) {
return (
array1.length === array2.length &&
array1.every(function(element, index) {
return element === array2[index];
})
);
} | javascript | {
"resource": ""
} |
q27595 | stringToArrayBuffer | train | function stringToArrayBuffer(text) {
if (window.TextEncoder !== undefined) {
return new TextEncoder().encode(text).buffer;
}
var array = new Uint8Array(new ArrayBuffer(text.length));
for (var i = 0, il = text.length; i < il; i++) {
var value = text.charCodeAt(i);
// Replacing multi-byte character with space(0x20).
array[i] = value > 0xff ? 0x20 : value;
}
return array.buffer;
} | javascript | {
"resource": ""
} |
q27596 | getMinMax | train | function getMinMax(attribute, start, count) {
var output = {
min: new Array(attribute.itemSize).fill(Number.POSITIVE_INFINITY),
max: new Array(attribute.itemSize).fill(Number.NEGATIVE_INFINITY)
};
for (var i = start; i < start + count; i++) {
for (var a = 0; a < attribute.itemSize; a++) {
var value = attribute.array[i * attribute.itemSize + a];
output.min[a] = Math.min(output.min[a], value);
output.max[a] = Math.max(output.max[a], value);
}
}
return output;
} | javascript | {
"resource": ""
} |
q27597 | isNormalizedNormalAttribute | train | function isNormalizedNormalAttribute(normal) {
if (cachedData.attributes.has(normal)) {
return false;
}
var v = new THREE.Vector3();
for (var i = 0, il = normal.count; i < il; i++) {
// 0.0005 is from glTF-validator
if (Math.abs(v.fromArray(normal.array, i * 3).length() - 1.0) > 0.0005)
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q27598 | createNormalizedNormalAttribute | train | function createNormalizedNormalAttribute(normal) {
if (cachedData.attributes.has(normal)) {
return cachedData.attributes.get(normal);
}
var attribute = normal.clone();
var v = new THREE.Vector3();
for (var i = 0, il = attribute.count; i < il; i++) {
v.fromArray(attribute.array, i * 3);
if (v.x === 0 && v.y === 0 && v.z === 0) {
// if values can't be normalized set (1, 0, 0)
v.setX(1.0);
} else {
v.normalize();
}
v.toArray(attribute.array, i * 3);
}
cachedData.attributes.set(normal, attribute);
return attribute;
} | javascript | {
"resource": ""
} |
q27599 | getPaddedArrayBuffer | train | function getPaddedArrayBuffer(arrayBuffer, paddingByte) {
paddingByte = paddingByte || 0;
var paddedLength = getPaddedBufferSize(arrayBuffer.byteLength);
if (paddedLength !== arrayBuffer.byteLength) {
var array = new Uint8Array(paddedLength);
array.set(new Uint8Array(arrayBuffer));
if (paddingByte !== 0) {
for (var i = arrayBuffer.byteLength; i < paddedLength; i++) {
array[i] = paddingByte;
}
}
return array.buffer;
}
return arrayBuffer;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.