_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q3500
|
train
|
function(value) {
var wrapper = createElement('div');
wrapper.innerHTML = ''+value;
// trim extraneous whitespace
trimWhitespace(wrapper);
// eliminate wrapper for single nodes
if (wrapper.childNodes.length === 1) {
return wrapper.firstChild;
}
// create a document fragment to hold elements
var frag = createElement('');
while (wrapper.firstChild) {
frag.appendChild(wrapper.firstChild);
}
return frag;
}
|
javascript
|
{
"resource": ""
}
|
|
q3501
|
toggle
|
train
|
function toggle(ev) {
if (ev)
ev.preventDefault()
autoTime = 0
autoPlay = true
curTimeline = curTimeline === anim1 ? anim2 : anim1
duration = curTimeline.duration()
//clear style
widget.element.style.cssText = ''
editor.show(curTimeline === anim1 ? 0 : 1)
editor.hide(curTimeline === anim1 ? 1 : 0)
}
|
javascript
|
{
"resource": ""
}
|
q3502
|
incrementPosition
|
train
|
function incrementPosition() {
comparison._animateInterval = setInterval(function () {
currentPositionInPercent++;
comparison._updatePosition(currentPositionInPercent);
if (currentPositionInPercent >= newPositionInPercent) {
setFinalPositionAndClearInterval();
}
}, 10);
}
|
javascript
|
{
"resource": ""
}
|
q3503
|
train
|
function (target, objects, options) {
for (var object in objects) {
if (objects.hasOwnProperty(object)) {
recursiveMerge(target, objects[object]);
}
}
function recursiveMerge(target, object) {
for (var property in object) {
if (object.hasOwnProperty(property)) {
var current = object[property];
if (utils.getConstructor(current) === 'Object') {
if (!target[property]) {
target[property] = {};
}
recursiveMerge(target[property], current);
}
else {
// clearEmpty
if (options.clearEmpty) {
if (current == null) {
continue;
}
}
target[property] = current;
}
}
}
}
return target;
}
|
javascript
|
{
"resource": ""
}
|
|
q3504
|
train
|
function (element, events, func) {
for (var i = 0; i < events.length; i++) {
element.addEventListener(events[i], func);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3505
|
destroyWidgets
|
train
|
function destroyWidgets(vNode, patch, index) {
if (isWidget(vNode)) {
if (typeof vNode.destroy === "function") {
patch[index] = new VPatch(VPatch.REMOVE, vNode, null)
}
} else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) {
var children = vNode.children
var len = children.length
for (var i = 0; i < len; i++) {
var child = children[i]
index += 1
destroyWidgets(child, patch, index)
if (isVNode(child) && child.count) {
index += child.count
}
}
} else if (isThunk(vNode)) {
thunks(vNode, null, patch, index)
}
}
|
javascript
|
{
"resource": ""
}
|
q3506
|
thunks
|
train
|
function thunks(a, b, patch, index) {
var nodes = handleThunk(a, b);
var thunkPatch = diff(nodes.a, nodes.b)
if (hasPatches(thunkPatch)) {
patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch)
}
}
|
javascript
|
{
"resource": ""
}
|
q3507
|
use
|
train
|
function use(options) {
options = _.defaults(options || {}, {
stdout: true,
stderr: true,
print: false
});
if (options.stdout)
wrapWrite('stdout', options.print);
if (options.stderr)
wrapWrite('stderr', options.print);
}
|
javascript
|
{
"resource": ""
}
|
q3508
|
wrapWrite
|
train
|
function wrapWrite(std, print) {
process[std].write = function (data) {
cachedData[std].push(data);
if (print)
originalWrites[std].apply(process[std], arguments);
};
}
|
javascript
|
{
"resource": ""
}
|
q3509
|
restore
|
train
|
function restore(options) {
options = _.defaults(options || {}, {
stdout: true,
stderr: true
});
if (options.stdout)
process.stdout.write = originalWrites.stdout;
if (options.stderr)
process.stderr.write = originalWrites.stderr;
}
|
javascript
|
{
"resource": ""
}
|
q3510
|
flush
|
train
|
function flush(options) {
options = _.defaults(options || {}, {
stdout: true,
stderr: true
});
var flushed = {};
if (options.stdout) {
flushed.stdout = cachedData.stdout;
cachedData.stdout = [];
}
if (options.stderr) {
flushed.stderr = cachedData.stderr;
cachedData.stderr = [];
}
return flushed;
}
|
javascript
|
{
"resource": ""
}
|
q3511
|
eval$ref
|
train
|
function eval$ref(params, dataPath) {
dataPath = dataPath.replace(this.refPrefixRegexp, '');
var $ref = params.$ref;
if ($ref.indexOf('0/') == 0) throw new Error('Cannot reference the same $ref instruction or child');
var pathParsed = pointer.parse(dataPath);
var absPointerParsed = util.toAbsolutePointer($ref, pathParsed);
// N# pointer returns property/index
if (typeof absPointerParsed == 'string') return absPointerParsed;
if (!absPointerParsed) absPointerParsed = pointer.parse($ref);
var i = 0; // find the root to be evaluated
while (i < pathParsed.length
&& pathParsed[i] == absPointerParsed[i]) i++;
if (i == pathParsed.length) throw new Error('Cannot reference the same $ref instruction or child');
if (!isNaN(pathParsed[i]) && !isNaN(absPointerParsed[i]) && absPointerParsed[i] > pathParsed[i])
throw new Error('cannot reference the next item from the previous item');
var rootPointerParsed = absPointerParsed.slice(0, i+1);
var rootPointer = pointer.compile(rootPointerParsed);
var pointerFromRoot = pointer.compile(absPointerParsed.slice(i+1));
if (this.evaluatedRefs[rootPointer])
return getRefValue(this.script, rootPointer, pointerFromRoot);
var self = this;
var pendingRef = self.pendingRefs[rootPointer]
= self.pendingRefs[rootPointer] || new PendingRef(rootPointer);
return new Promise(function (resolve, reject) {
pendingRef.addCallback(function () {
resolve(getRefValue(self.script, rootPointer, pointerFromRoot));
});
});
}
|
javascript
|
{
"resource": ""
}
|
q3512
|
addInstruction
|
train
|
function addInstruction(definition, keywordFunc, _regenerateSchemas) {
var valid = this._validateInstruction(definition);
if (!valid) throw new Ajv.ValidationError(this._validateInstruction.errors);
// TODO check instruction is unique
this._instructions.push(definition);
var keyword = definition.evaluate.validatorKeyword;
this._evalKeywords[keyword] = keywordFunc;
addAjvKeyword.call(this, keyword, 'object', true);
if (_regenerateSchemas !== false) generateSchemas();
}
|
javascript
|
{
"resource": ""
}
|
q3513
|
addMacro
|
train
|
function addMacro(definition, _regenerateSchemas) {
var valid = this._validateMacro(definition);
if (!valid) throw new Ajv.ValidationError(this._validateMacro.errors);
// TODO check macro is unique
this._macros.push(definition);
if (_regenerateSchemas !== false) generateSchemas();
}
|
javascript
|
{
"resource": ""
}
|
q3514
|
addExecutor
|
train
|
function addExecutor(name, executor) {
if (this._executors[name]) throw new Error('executor "' + name + '" is already defined');
this._executors[name] = executor;
}
|
javascript
|
{
"resource": ""
}
|
q3515
|
addAjvKeywords
|
train
|
function addAjvKeywords() {
addAjvKeyword.call(this, 'validateAsync');
addAjvKeyword.call(this, 'itemsSerial', 'array');
this._evalKeywords.objectToAsync = util.objectToPromise;
this._evalKeywords.valueToAsync = util.toPromise;
addAjvKeyword.call(this, 'objectToAsync', 'object', true);
addAjvKeyword.call(this, 'valueToAsync', undefined, true);
this.ajv.addKeyword('resolvePendingRefs', {
validate: evaluationKeywords.resolvePendingRefs,
schema: false
});
this.ajv.addKeyword('expandJsMacro', {
compile: compileExpandJsMacro
});
}
|
javascript
|
{
"resource": ""
}
|
q3516
|
addCoreInstructions
|
train
|
function addCoreInstructions() {
this._validateInstruction = this.ajv.compile(require('jsonscript/schema/instruction.json'));
coreInstructions.forEach(function (inst) {
this.addInstruction(inst, instructionKeywords[inst.evaluate.validatorKeyword], false);
}, this);
}
|
javascript
|
{
"resource": ""
}
|
q3517
|
addCoreMacros
|
train
|
function addCoreMacros() {
this._validateMacro = this.ajv.compile(require('jsonscript/schema/macro.json'));
coreMacros.forEach(function (macro) {
this.addMacro(macro, false);
}, this);
}
|
javascript
|
{
"resource": ""
}
|
q3518
|
generateSchemas
|
train
|
function generateSchemas() {
// this.ajv.addMetaSchema(_generate.call(this, 'evaluate_metaschema'));
this._validate = this.ajv.compile(_generate.call(this, 'schema'));
this._expandMacros = this.ajv.compile(_generate.call(this, 'expand_macros'));
this._evaluate = this.ajv.compile(_generate.call(this, 'evaluate'));
// console.log(this._validate.toString().length, this._evaluate.toString().length);
}
|
javascript
|
{
"resource": ""
}
|
q3519
|
_generate
|
train
|
function _generate(schemaName) {
var schema = generateSchema(schemaName, this._instructions, this._macros, this._opts.strict);
this.ajv.removeSchema(schema.id);
return schema;
}
|
javascript
|
{
"resource": ""
}
|
q3520
|
resolvePendingRefs
|
train
|
function resolvePendingRefs(data, dataPath) {
dataPath = dataPath.replace(/^\/script/, '');
this.evaluatedRefs[dataPath] = true;
var ref = this.pendingRefs[dataPath];
if (ref) ref.resolve();
return true;
}
|
javascript
|
{
"resource": ""
}
|
q3521
|
toAbsolutePointer
|
train
|
function toAbsolutePointer(relativePointer, basePointerParsed) {
var base = basePointerParsed;
var matches = relativePointer.match(RELATIVE_JSON_POINTER);
if (!matches) return;
var lvl = base.length;
var up = +matches[1];
var jsonPointer = matches[2];
if (jsonPointer == '#') {
if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
return base[lvl-up-1]; // resolved pointer value
}
if (up > lvl) throw new Error('Cannot reference script ' + up + ' levels up, current level is ' + lvl);
var parsedPointer = pointer.parse(jsonPointer);
if (up > 0) base = base.slice(0, -up);
return base.concat(parsedPointer); // parsed absolute pointer as array
}
|
javascript
|
{
"resource": ""
}
|
q3522
|
suiteStarted
|
train
|
function suiteStarted() {
// Have all suites started?
if(hasPendingSuites()) {
return;
}
// All suites have started, send the total to karma
let [total, finished] = countTests();
if(isDebug) {
console.debug(`All ${Object.keys(suites).length} suites have started, expecting ${total} tests (of which ${finished} have already finished)`);
}
karma.info({total});
// Send the pending results
pendingResults.forEach(sendResult);
pendingResults = [];
}
|
javascript
|
{
"resource": ""
}
|
q3523
|
suiteComplete
|
train
|
function suiteComplete(result) {
if (result.coverage) {
coverageCollector.addCoverage(result.coverage);
}
// Have all suites completed?
let completedSuites = suitesWithState('complete');
if(Object.keys(completedSuites).length < Object.keys(suites).length) {
return;
}
// All suites have completed, send the “complete” message to karma
if(isDebug) {
let [total, finished] = countTests();
console.debug(`All ${Object.keys(suites).length} suites have completed, ran ${finished} of ${total} tests`);
}
if (result.coverage) {
result.coverage = coverageCollector.getFinalCoverage();
}
karma.complete(result);
}
|
javascript
|
{
"resource": ""
}
|
q3524
|
includeServedOnly
|
train
|
function includeServedOnly(files) {
files = Object.assign({}, files);
let oldIncluded = files.included;
files.included = files.served
// Don’t include the files that are included in the outer context
.filter(file => oldIncluded.indexOf(file) === -1)
// Don’t include this (or other) contexts
.filter(file => !isIFrameHtml(file.path))
// Don’t include files that were never included to begin with (before the framework ran)
// FIXME: find the most specific applicable pattern first
.filter(file => !nonIncludedFiles.some(pattern => minimatch(file.originalPath, pattern.pattern)))
// Don’t include the reverse context (it is included by the `transform` function below)
.filter(file => file.originalPath !== REVERSE_CONTEXT);
return files;
}
|
javascript
|
{
"resource": ""
}
|
q3525
|
getAttachment
|
train
|
function getAttachment( val, valType, onFound, onNotFound ) {
var requestData;
if ( ! val ) {
onNotFound();
return;
}
if ( 'url' === valType ) {
requestData = {
action: 'get-attachment-by-url',
url: val
};
} else {
requestData = {
action: 'get-attachment',
id: parseInt( val, 10 )
};
}
wp.media.ajax({
type: 'POST',
data: requestData,
success: onFound,
error: onNotFound
});
}
|
javascript
|
{
"resource": ""
}
|
q3526
|
train
|
function() {
_.defaults( this.options, {
query: {},
multiple: false,
editable: true,
filterable: 'all',
searchable: true,
displaySettings: false,
displayUserSettings: false,
editing: false,
state: 'insert',
metadata: {}
});
Select.prototype.initialize.apply( this, arguments );
}
|
javascript
|
{
"resource": ""
}
|
|
q3527
|
train
|
function() {
this.states.add([
new wp.media.controller.Library({
id: 'insert',
title: this.options.title,
selection: this.options.selection,
priority: 20,
toolbar: 'main-insert',
filterable: this.options.filterable,
searchable: this.options.searchable,
library: wp.media.query( this.options.query ),
multiple: this.options.multiple,
editable: this.options.editable,
displaySettings: this.options.displaySettings,
displayUserSettings: this.options.displayUserSettings
}),
new wp.media.controller.EditImage({ model: this.options.editImage })
]);
}
|
javascript
|
{
"resource": ""
}
|
|
q3528
|
train
|
function() {
var view = new wp.media.view.EditImage({
controller: this,
model: this.state().get( 'image' )
}).render();
this.content.set( view );
view.loadEditor();
}
|
javascript
|
{
"resource": ""
}
|
|
q3529
|
train
|
function( view ) {
var controller = this;
view.set( 'insert', {
style: 'primary',
priority: 80,
text: controller.options.buttonText,
requires: { selection: true },
click: function() {
controller.close();
controller.state().trigger( 'insert', controller.state().get( 'selection' ) ).reset();
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q3530
|
train
|
function() {
var self = this;
$.extend( self.options, self.element.data() );
// Use the 'type' query attribute in favor of 'post_mime_type'.
if ( self.options.query && self.options.query.post_mime_type ) {
self.options.query.type = self.options.query.post_mime_type;
delete self.options.query.post_mime_type;
}
self._content_id = 'wp-mediapicker-content-' + self.element.attr( 'id' );
self.element.hide().wrap( '<div class="wp-mediapicker-container" />' );
self._wrap = self.element.parent();
self._open_button = $( '<button type="button" class="wp-mediapicker-open-button button" />' ).insertAfter( self.element );
self._remove_button = $( '<button type="button" class="wp-mediapicker-remove-button button-link button-link-delete" />' ).hide().insertAfter( self._open_button ).text( self.options.label_remove );
self._content_wrap = $( '<div class="wp-mediapicker-content-wrap" />' ).insertAfter( self._remove_button );
self._content = $( '<div class="wp-mediapicker-content" />' ).appendTo( self._content_wrap ).attr( 'id', self._content_id );
self._frame = new MediaPickerFrame({
title: self.options.label_modal,
buttonText: self.options.label_button,
frame: 'select',
state: 'insert',
selection: new wp.media.model.Selection( [], {
multiple: self.options.multiple
}),
query: self.options.query,
multiple: self.options.multiple,
filterable: self.options.filterable,
searchable: self.options.searchable,
editable: self.options.editable
});
self._setValue( self.element.val() );
self._addListeners();
}
|
javascript
|
{
"resource": ""
}
|
|
q3531
|
train
|
function() {
var self = this;
self._frame.on( 'insert', function() {
var selection = self._frame.state().get( 'selection' );
var attachments = selection.models.map( function( model ) {
return _.extend( {}, model.toJSON() );
});
var attachment = _.extend( {}, selection.first().toJSON() );
self._setAttachment( attachment );
$( document ).trigger( 'wpMediaPicker.insert', [ attachments, self ] );
});
self._open_button.on( 'click', function() {
var selection = self._frame.state( 'insert' ).get( 'selection' );
selection.reset( self._attachment ? [ self._attachment ] : [] );
self.open();
});
self._remove_button.on( 'click', function() {
self._setAttachment( null );
});
}
|
javascript
|
{
"resource": ""
}
|
|
q3532
|
train
|
function( attachment ) {
var self = this;
self._attachment = attachment;
self._open_button.text( self.options.label_replace );
self._remove_button.show();
var preview_content = '';
if ( 'video' === attachment.type ) {
// for video attachments, show the video player, optionally with the poster
var poster = '';
if ( attachment.image && attachment.image.src !== attachment.icon ) {
poster = attachment.image.src;
}
preview_content += '<video class="wp-video-shortcode" preload="metadata"' + ( poster ? ' poster="' + poster + '"' : '' ) + ' controls><source type="' + attachment.mime + '" src="' + attachment.url + '" /></video>';
} else if ( 'audio' === attachment.type ) {
// for audio attachments, show the audio player, with either the cover or the mime type icon
if ( attachment.image && attachment.image.src && attachment.image.src !== attachment.icon ) {
preview_content += '<img class="wp-audio-cover" src="' + attachment.image.src + '" alt="' + attachment.filename + '" />';
} else {
preview_content += '<div class="mime-type-icon"><img src="' + attachment.icon + '" /><span>' + attachment.filename + '</span></div>';
}
preview_content += '<audio class="wp-audio-shortcode" width="100%" preload="none" controls><source type="' + attachment.mime + '" src="' + attachment.url + '" /></audio>';
} else {
var src = 'image' === attachment.type ? attachment.url : undefined;
if ( attachment.sizes ) {
if ( attachment.sizes.large ) {
src = attachment.sizes.large.url;
} else if ( attachment.sizes.full ) {
src = attachment.sizes.full.url;
}
}
if ( src ) {
preview_content += '<img src="' + src + '" alt="' + attachment.alt + '" />';
} else {
preview_content += '<div class="mime-type-icon"><img src="' + attachment.icon + '" /><span>' + attachment.filename + '</span></div>';
}
}
if ( 0 <= preview_content.search( '<img ' ) ) {
self._content.addClass( 'size-auto' );
} else {
self._content.removeClass( 'size-auto' );
}
self._content.show().html( preview_content );
}
|
javascript
|
{
"resource": ""
}
|
|
q3533
|
train
|
function() {
var self = this;
self._attachment = null;
self._open_button.text( self.options.label_add );
self._remove_button.hide();
self._content.hide().empty().removeClass( 'size-auto' );
}
|
javascript
|
{
"resource": ""
}
|
|
q3534
|
train
|
function( attachment ) {
var noChange = ( attachment && this._attachment && attachment.id === this._attachment.id ) || ( ! attachment && ! this._attachment );
if ( ! attachment ) {
this._resetContent();
if ( noChange ) {
return;
}
this.element.val( null );
this.element.trigger( 'change' );
if ( 'function' === typeof this.options.clear ) {
this.options.clear.call( this );
}
$( document ).trigger( 'wpMediaPicker.updateField', [ null, this ] );
return;
}
this._createContent( attachment );
if ( noChange ) {
return;
}
if ( 'url' === this.options.store ) {
this.element.val( attachment.url );
} else {
this.element.val( attachment.id );
}
this.element.trigger( 'change' );
if ( 'function' === typeof this.options.change ) {
this.options.change.call( this );
}
$( document ).trigger( 'wpMediaPicker.updateField', [ attachment, this ] );
}
|
javascript
|
{
"resource": ""
}
|
|
q3535
|
train
|
function( val ) {
var self = this;
getAttachment(
val,
self.options.store,
function( attachment ) {
self._setAttachment( attachment );
},
function() {
self._setAttachment( null );
}
);
}
|
javascript
|
{
"resource": ""
}
|
|
q3536
|
determineParents
|
train
|
function determineParents() {
var featuresWithoutParent = [];
for (var i = 0; i < output.features.length; i++) {
debugAll("Output ring " + i + " has parent " + output.features[i].properties.parent);
if (output.features[i].properties.parent == -1) featuresWithoutParent.push(i);
}
debugAll("The following output ring(s) have no parent: " + featuresWithoutParent);
if (featuresWithoutParent.length > 1) {
for (var i = 0; i < featuresWithoutParent.length; i++) {
var parent = -1;
var parentArea = Infinity;
for (var j = 0; j < output.features.length; j++) {
if (featuresWithoutParent[i] == j) continue
if (inside(helpers.point(output.features[featuresWithoutParent[i]].geometry.coordinates[0][0]), output.features[j], true)) {
if (area(output.features[j]) < parentArea) {
parent = j;
debugAll("Ring "+featuresWithoutParent[i]+" lies inside output ring "+j);
}
}
}
output.features[featuresWithoutParent[i]].properties.parent = parent;
debugAll("Ring "+featuresWithoutParent[i]+" is assigned parent "+parent);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q3537
|
train
|
function (coord, ringAndEdge1, ringAndEdge2, nxtIsectAlongRingAndEdge1, nxtIsectAlongRingAndEdge2, ringAndEdge1Walkable, ringAndEdge2Walkable) {
this.coord = coord; // [x,y] of this intersection
this.ringAndEdge1 = ringAndEdge1; // first edge of this intersection
this.ringAndEdge2 = ringAndEdge2; // second edge of this intersection
this.nxtIsectAlongRingAndEdge1 = nxtIsectAlongRingAndEdge1; // the next intersection when following ringAndEdge1
this.nxtIsectAlongRingAndEdge2 = nxtIsectAlongRingAndEdge2; // the next intersection when following ringAndEdge2
this.ringAndEdge1Walkable = ringAndEdge1Walkable; // May we (still) walk away from this intersection over ringAndEdge1?
this.ringAndEdge2Walkable = ringAndEdge2Walkable; // May we (still) walk away from this intersection over ringAndEdge2?
}
|
javascript
|
{
"resource": ""
}
|
|
q3538
|
isConvex
|
train
|
function isConvex(pts, righthanded){
// 'pts' is an [x,y] pair
// 'righthanded' is a boolean
if (typeof(righthanded) === 'undefined') righthanded = true;
if (pts.length != 3) throw new Error("This function requires an array of three points [x,y]");
var d = (pts[1][0] - pts[0][0]) * (pts[2][1] - pts[0][1]) - (pts[1][1] - pts[0][1]) * (pts[2][0] - pts[0][0]);
return (d >= 0) == righthanded;
}
|
javascript
|
{
"resource": ""
}
|
q3539
|
windingOfRing
|
train
|
function windingOfRing(ring){
// 'ring' is an array of [x,y] pairs with the last equal to the first
// Compute the winding number based on the vertex with the smallest x-value, it precessor and successor. An extremal vertex of a simple, non-self-intersecting ring is always convex, so the only reason it is not is because the winding number we use to compute it is wrong
var leftVtx = 0;
for (var i = 0; i < ring.length-1; i++) { if (ring[i][0] < ring[leftVtx][0]) leftVtx = i; }
if (isConvex([ring[(leftVtx-1).modulo(ring.length-1)],ring[leftVtx],ring[(leftVtx+1).modulo(ring.length-1)]],true)) {
var winding = 1;
} else {
var winding = -1;
}
return winding
}
|
javascript
|
{
"resource": ""
}
|
q3540
|
natural_minor
|
train
|
function natural_minor(note) {
var i = get_notes(notes.to_major(note));
var arr = i.slice(5, i.length);
for (var k = 0; k < 5; k++) {
arr.push(i[k]);
};
return arr;
}
|
javascript
|
{
"resource": ""
}
|
q3541
|
train
|
function (item, comparer, index, count) {
index = index || 0;
count = count || this.length;
comparer = Comparer.from(comparer);
return binarySearch(this, index, count, item, comparer.compare);
}
|
javascript
|
{
"resource": ""
}
|
|
q3542
|
train
|
function (startIndexOrMatch, countOrMatch, match) {
var len = this.length,
startIndex = isNumber(startIndexOrMatch) ? startIndexOrMatch : 0,
count = isNumber(countOrMatch) ? countOrMatch : len - startIndex;
match = isFunction(startIndexOrMatch) ? startIndexOrMatch : (isFunction(countOrMatch) ? countOrMatch : match);
assertType(match, Function);
validateListIndex(this, startIndex);
while (count-- > 0 && startIndex < len) {
if (match(this[startIndex]) === true) {
return startIndex;
}
startIndex++;
}
return -1;
}
|
javascript
|
{
"resource": ""
}
|
|
q3543
|
train
|
function (match) {
assertType(match, Function);
var len = this.length;
while (len-- > 0) {
if (match(this[len]) === true) {
return this[len];
}
}
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
|
q3544
|
train
|
function (match) {
assertType(match, Function);
var arr = new Array(this.length),
count = 0;
for (var i = 0, len = this.length; i < len; i++) {
if (match(this[i]) === true) {
arr[count++] = this[i];
}
}
arr.length = count;
return new List(arr);
}
|
javascript
|
{
"resource": ""
}
|
|
q3545
|
train
|
function (index, count) {
validateListIndex(this, index + count - 1);
return new List(this.slice(index, index + count));
}
|
javascript
|
{
"resource": ""
}
|
|
q3546
|
train
|
function (index, item) {
if (index !== this.length) {
validateListIndex(this, index);
}
var len = ++this.length;
while (len-- > index) {
this[len] = this[len - 1];
}
this[index] = item;
}
|
javascript
|
{
"resource": ""
}
|
|
q3547
|
train
|
function (index, collection) {
assertType(index, Number);
assertNotNull(collection);
if (index !== this.length) {
validateListIndex(this, index);
}
var arr = buffer(collection),
count = arr.length,
len = this.length + count;
this.length = len;
while (len-- > index) {
this[len] = this[len - count];
}
while (count-- > 0) {
this[index + count] = arr[count];
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3548
|
train
|
function (match) {
assertType(match, Function);
var freeIndex = 0,
len = this.length;
while (freeIndex < len && !match(this[freeIndex])) {
freeIndex++;
}
if (freeIndex >= len) {
return 0;
}
var current = freeIndex + 1;
while (current < len) {
while (current < len && match(this[current])) {
current++;
}
if (current < len) {
this[freeIndex++] = this[current++];
}
}
shrinkList(this, freeIndex);
return len - freeIndex;
}
|
javascript
|
{
"resource": ""
}
|
|
q3549
|
train
|
function (index) {
validateListIndex(this, index);
var i = index,
len = --this.length;
for (; i < len; i++) {
this[i] = this[i + 1];
}
delete this[len];
}
|
javascript
|
{
"resource": ""
}
|
|
q3550
|
train
|
function (index, count) {
validateListIndex(this, index + count - 1);
var len = this.length - count;
for (; index < len; index++) {
this[index] = this[index + count];
}
shrinkList(this, len);
}
|
javascript
|
{
"resource": ""
}
|
|
q3551
|
train
|
function (index, count) {
index = index || 0;
count = count || this.length;
validateListIndex(this, index + count - 1);
var arr = this.slice(index, index + count).reverse(),
len = arr.length;
while (len-- > 0) {
this[len + index] = arr[len];
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q3552
|
train
|
function (indexOrComparer, count, comparer) {
var index = isNumber(indexOrComparer) ? indexOrComparer : 0,
total = count || this.length - index,
comparision = indexOrComparer === null ? null :
(isFunction(indexOrComparer) ? indexOrComparer :
Comparer.from(comparer || indexOrComparer).compare);
validateListIndex(this, index + total - 1);
var arr = this.slice(index, index + total).sort(comparision),
len = arr.length;
while (len-- > 0) {
this[len + index] = arr[len];
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3553
|
train
|
function (match) {
assertType(match, Function);
for (var i = 0, len = this.length; i < len; i++) {
if (match(this[i]) === false) {
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q3554
|
hashMany
|
train
|
function hashMany(obj) {
var h = hash(obj, false);
// Combine hash codes for given inputs
if (arguments.length > 1) {
var len = arguments.length,
i = 0;
while (i < len) {
h = combineHash(h, hash(arguments[i++], false));
}
}
return h;
}
|
javascript
|
{
"resource": ""
}
|
q3555
|
basePick
|
train
|
function basePick(object, props) {
object = Object(object);
return reduce(props, function(result, key) {
if (key in object) {
result[key] = object[key];
}
return result;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q3556
|
train
|
function () {
while (this.head !== null) {
var temp = this.head;
this.head = this.head.next(); // use next() the instead of "_next", otherwise it will loop forever
temp._list = null;
temp._next = null;
temp._prev = null;
}
this.head = null;
this.size = 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q3557
|
train
|
function (node, value) {
assertType(node, LinkedListNode);
var newNode;
if (value instanceof LinkedListNode) {
newNode = value;
this.insertNodeBefore(node._next, newNode);
}
else {
newNode = new LinkedListNode(value);
this.addAfter(node, newNode);
}
return newNode;
}
|
javascript
|
{
"resource": ""
}
|
|
q3558
|
train
|
function (node, value) {
assertType(node, LinkedListNode);
var newNode;
if (value instanceof LinkedListNode) {
newNode = value;
this.insertNodeBefore(node, newNode);
if (node === this.head) {
this.head = newNode;
}
}
else {
newNode = new LinkedListNode(value);
this.addBefore(node, newNode);
}
return newNode;
}
|
javascript
|
{
"resource": ""
}
|
|
q3559
|
train
|
function (value) {
var node;
if (value instanceof LinkedListNode) {
node = value;
validateNode(node, null);
if (this.head === null) {
this.insertNodeToEmptyList(node);
}
else {
this.insertNodeBefore(this.head, node);
this.head = node;
}
}
else {
node = new LinkedListNode(value);
this.addFirst(node);
}
return node;
}
|
javascript
|
{
"resource": ""
}
|
|
q3560
|
train
|
function (value) {
var node = this.head;
if (node !== null) {
if (value !== null) {
do {
if (runtimeEquals(node._value, value)) {
return node;
}
node = node._next;
}
while (node !== this.head);
}
else {
do {
if (node._value === null) {
return node;
}
node = node._next;
}
while (node !== this.head);
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q3561
|
train
|
function (value) {
if (this.head === null) {
return null;
}
var last = this.head._prev,
node = last;
if (node !== null) {
if (value !== null) {
do {
if (runtimeEquals(node._value, value)) {
return node;
}
node = node._prev;
}
while (node !== last);
}
else {
do {
if (node._value === null) {
return node;
}
node = node._prev;
}
while (node !== last);
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q3562
|
train
|
function (value) {
var node;
if (value instanceof LinkedListNode) {
node = value;
validateNode(node, this);
if (node._next === node) {
this.head = null;
}
else {
node._next._prev = node._prev;
node._prev._next = node._next;
if (this.head === node) {
this.head = node._next;
}
}
node._list = null;
node._next = null;
node._prev = null;
this.size--;
return true;
}
else {
if ((node = this.find(value)) !== null) {
this.remove(node);
return true;
}
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3563
|
transpile
|
train
|
function transpile() {
return rollup.rollup({
entry: path.join(dirs.source, files.main)
}).then(function (bundle) {
return bundle.write({
// output format - 'amd', 'cjs', 'es6', 'iife', 'umd'
format: 'umd',
dest: path.join(dirs.build, files.main),
sourceMap: false,
banner: grunt.config('banner'),
intro: 'mx.version = \'' + grunt.config('pkg').version + '\';\n',
footer: '\n',
moduleName: 'mx'
});
});
}
|
javascript
|
{
"resource": ""
}
|
q3564
|
train
|
function( name, testEnvironment, executeNow ) {
var module, moduleFns;
var currentModule = config.currentModule;
if ( arguments.length === 2 ) {
if ( objectType( testEnvironment ) === "function" ) {
executeNow = testEnvironment;
testEnvironment = undefined;
}
}
module = createModule();
if ( testEnvironment && ( testEnvironment.setup || testEnvironment.teardown ) ) {
console.warn(
"Module's `setup` and `teardown` are not hooks anymore on QUnit 2.0, use " +
"`beforeEach` and `afterEach` instead\n" +
"Details in our upgrade guide at https://qunitjs.com/upgrade-guide-2.x/"
);
}
moduleFns = {
before: setHook( module, "before" ),
beforeEach: setHook( module, "beforeEach" ),
afterEach: setHook( module, "afterEach" ),
after: setHook( module, "after" )
};
if ( objectType( executeNow ) === "function" ) {
config.moduleStack.push( module );
setCurrentModule( module );
executeNow.call( module.testEnvironment, moduleFns );
config.moduleStack.pop();
module = module.parentModule || currentModule;
}
setCurrentModule( module );
function createModule() {
var parentModule = config.moduleStack.length ?
config.moduleStack.slice( -1 )[ 0 ] : null;
var moduleName = parentModule !== null ?
[ parentModule.name, name ].join( " > " ) : name;
var module = {
name: moduleName,
parentModule: parentModule,
tests: [],
moduleId: generateHash( moduleName ),
testsRun: 0
};
var env = {};
if ( parentModule ) {
parentModule.childModule = module;
extend( env, parentModule.testEnvironment );
delete env.beforeEach;
delete env.afterEach;
}
extend( env, testEnvironment );
module.testEnvironment = env;
config.modules.push( module );
return module;
}
function setCurrentModule( module ) {
config.currentModule = module;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3565
|
skip
|
train
|
function skip( testName ) {
if ( focused ) { return; }
var test = new Test( {
testName: testName,
skip: true
} );
test.queue();
}
|
javascript
|
{
"resource": ""
}
|
q3566
|
selectionChange
|
train
|
function selectionChange( evt ) {
var i,
checkbox = evt && evt.target || allCheckbox,
modulesList = dropDownList.getElementsByTagName( "input" ),
selectedNames = [];
toggleClass( checkbox.parentNode, "checked", checkbox.checked );
dirty = false;
if ( checkbox.checked && checkbox !== allCheckbox ) {
allCheckbox.checked = false;
removeClass( allCheckbox.parentNode, "checked" );
}
for ( i = 0; i < modulesList.length; i++ ) {
if ( !evt ) {
toggleClass( modulesList[ i ].parentNode, "checked", modulesList[ i ].checked );
} else if ( checkbox === allCheckbox && checkbox.checked ) {
modulesList[ i ].checked = false;
removeClass( modulesList[ i ].parentNode, "checked" );
}
dirty = dirty || ( checkbox.checked !== checkbox.defaultChecked );
if ( modulesList[ i ].checked ) {
selectedNames.push( modulesList[ i ].parentNode.textContent );
}
}
commit.style.display = reset.style.display = dirty ? "" : "none";
moduleSearch.placeholder = selectedNames.join( ", " ) || allCheckbox.parentNode.textContent;
moduleSearch.title = "Type to filter list. Current selection:\n" +
( selectedNames.join( "\n" ) || allCheckbox.parentNode.textContent );
}
|
javascript
|
{
"resource": ""
}
|
q3567
|
train
|
function (value) {
if (value === null || value === undefined || value === defaultComparer) {
return defaultComparer;
}
else if (value instanceof Comparer) {
return value;
}
else if (isFunction(value)) {
return new Comparer(value);
}
else if (isFunction(value.compare)) {
return new Comparer(value.compare);
}
else {
return defaultComparer;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3568
|
train
|
function (value) {
if (value === null || value === undefined || value === defaultEqualityComparer) {
return defaultEqualityComparer;
}
else if (value instanceof EqualityComparer) {
return value;
}
else if (isFunction(value.hash) && isFunction(value.equals)) {
return new EqualityComparer(value.hash, value.equals);
}
return defaultEqualityComparer;
}
|
javascript
|
{
"resource": ""
}
|
|
q3569
|
train
|
function (key, value) {
assertNotNull(key);
var index = binarySearch(this.slot.keys, 0, this.slot.size, key, this.slot.comparer.compare);
if (index >= 0) {
error(ERROR_DUPLICATE_KEY);
}
this.insert(~index, key, value);
}
|
javascript
|
{
"resource": ""
}
|
|
q3570
|
train
|
function (value) {
if (value === null || value === undefined) {
return this.slot.keys.length;
} else {
assertType(value, Number);
if (value !== this.slot.keys.length) {
if (value < this.slot.size) {
error(ERROR_ARGUMENT_OUT_OF_RANGE);
}
this.slot.keys.length = value;
this.slot.values.length = value;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3571
|
train
|
function (key) {
assertNotNull(key);
return binarySearch(this.slot.keys, 0, this.slot.size, key, this.slot.comparer.compare);
}
|
javascript
|
{
"resource": ""
}
|
|
q3572
|
train
|
function (index) {
assertType(index, Number);
if (index < 0 || index >= this.slot.size) {
error(ERROR_ARGUMENT_OUT_OF_RANGE);
}
this.slot.size--;
this.slot.keys.splice(index, 1);
this.slot.values.splice(index, 1);
this.slot.keys.length++;
this.slot.values.length++;
}
|
javascript
|
{
"resource": ""
}
|
|
q3573
|
train
|
function (key, value) {
var index = this.indexOfKey(key);
if (index >= 0) {
this.slot.values[index] = value;
return;
}
this.insert(~index, key, value);
}
|
javascript
|
{
"resource": ""
}
|
|
q3574
|
train
|
function () {
var threshold = this.slot.keys.length * 0.9;
if (this.slot.size < threshold) {
this.capacity(this.slot.size);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3575
|
train
|
function (other) {
assertNotNull(other);
if (this.count() === 0) {
return;
}
else if (other === this) {
this.clear();
return;
}
var table = this.table;
forOf(other, function (element) {
table.remove(element);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q3576
|
train
|
function (other) {
assertNotNull(other);
// intersection of anything with empty set is empty set, so return if count is 0
if (this.count() === 0) {
return;
}
var c = collectionCount(other);
if (c !== -1) {
if (c === 0) {
this.clear();
return;
}
// If other is a HashSet, it has unique elements according to its equality comparer,
// but if they're using different equality comparers, then assumption of uniqueness
// will fail. So first check if other is a hashset using the same equality comparer;
// intersect is a lot faster if we can assume uniqueness.
if (areEqualityComparersEqual(this, other)) {
var arr = this.table.entries(true),
item;
c = this.count();
while (c-- > 0) {
item = arr[c];
if (!other.contains(item)) {
this.table.remove(item);
}
}
return;
}
}
this.intersectWith(new HashSet(other, this.compare));
}
|
javascript
|
{
"resource": ""
}
|
|
q3577
|
train
|
function (other) {
assertNotNull(other);
var c = collectionCount(other);
if (c !== -1) {
// if other is the empty set then this is a superset
if (c === 0) {
return true;
}
else if (areEqualityComparersEqual(this, other)) {
if (c > this.count()) {
return false;
}
}
}
return containsAllElements(this, other);
}
|
javascript
|
{
"resource": ""
}
|
|
q3578
|
train
|
function (other) {
assertNotNull(other);
if (this.count() === 0) {
return false;
}
var table = this.table,
res = false;
forOf(other, function (element) {
if (table.contains(element)) {
res = true;
return res;
}
});
return res;
}
|
javascript
|
{
"resource": ""
}
|
|
q3579
|
train
|
function (match) {
assertType(match, Function);
var len = this.count(),
arr = this.table.entries(true),
removed = 0,
item;
while (len-- > 0) {
item = arr[len];
if (match(item) && this.table.remove(item)) {
removed++;
}
}
return removed;
}
|
javascript
|
{
"resource": ""
}
|
|
q3580
|
train
|
function (other) {
assertNotNull(other);
if (this.count() === 0) {
this.unionWith(other);
return;
}
else if (other === this) {
this.clear();
return;
}
// If other is a HashSet, it has unique elements according to its equality comparer,
// but if they're using different equality comparers, then assumption of uniqueness
// will fail. So first check if other is a hashset using the same equality comparer;
// symmetric except is a lot faster if we can assume uniqueness
if (areEqualityComparersEqual(this, other)) {
var table = this.table;
forOf(other, function (element) {
if (!table.remove(element)) {
table.add(element, null);
}
});
}
else {
this.symmetricExceptWith(new HashSet(other, this.comparer));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3581
|
train
|
function (other) {
assertNotNull(other);
var table = this.table;
forOf(other, function (element) {
table.add(element);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q3582
|
train
|
function (insn, arch) {
this.arch = arch;
// Convert arch number to string
var archStr = archs.toString(arch);
Object.defineProperty(this, "_nativeInsn", {
"configurable" : true,
"value" : null,
});
/**
* Instruction id
* @name id
* @type {Number}
* @memberOf CsInsn
*/
this.id = insn.id;
/**
* Instruction address
* @name address
* @type {Number}
* @memberOf CsInsn
*/
this.address = insn.address;
/**
* Instruction bytes
* @name bytes
* @type {Array}
* @memberOf CsInsn
*/
this.bytes = insn.bytes.buffer.toJSON().data.slice(0, insn.size);
/**
* Instruction mnemonic string
* @name mnemonic
* @type {String}
* @memberOf CsInsn
*/
this.mnemonic = insn.mnemonic.buffer.readCString(0);
/**
* Instruction operand string
* @name op_str
* @type {String}
* @memberOf CsInsn
*/
this.op_str = insn.op_str.buffer.readCString(0);
if (insn.detail.address()) {
var detail = insn.detail.deref();
/**
* Instruction detailed information
*
* *NOTE: only valid when detail option is ON (OFF by default)*
*
* @name detail
* @type {Object}
* @memberOf CsInsn
*/
this.detail = {
/**
* Registers implicitly read by this instruction
* @name detail.regs_read
* @type {Array}
* @memberOf CsInsn
*/
"regs_read" : detail.regs_read.buffer.toJSON().data.slice(
0,
detail.regs_read_count
),
/**
* Registers implicitly modified by this instruction
* @name detail.regs_write
* @type {Array}
* @memberOf CsInsn
*/
"regs_write" : detail.regs_write.buffer.toJSON().data.slice(
0,
detail.regs_write_count
),
/**
* Groups this instruction belongs to
* @name detail.groups
* @type {Array}
* @memberOf CsInsn
*/
"groups" : detail.groups.buffer.toJSON().data.slice(
0,
detail.groups_count
),
};
var ArchDetail = exports[archStr]._Detail;
this.detail[archStr] = new ArchDetail(detail.arch[archStr]);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q3583
|
option
|
train
|
function option(csh, type, value) {
var errno = capstone.cs_option(csh, type, value);
if (errno) {
throw "cs_option returned " + errno + ": " + exports.strerror(errno);
}
}
|
javascript
|
{
"resource": ""
}
|
q3584
|
genStyleSection
|
train
|
function genStyleSection(style, styles, options) {
if (shouldReplaceCurrentSection(style, styles, options)) {
replaceWithSpacer(style);
}
// Remove the 'id', theme' and 'replace' attributes from the output set of
// attributes since they're not really valid SFC <style> attributes
_.set(style, 'attrs', _.omit(style.attrs, 'id', 'theme', 'replace'));
return genSection('style', style);
}
|
javascript
|
{
"resource": ""
}
|
q3585
|
iconSpriteLoader
|
train
|
function iconSpriteLoader({ customSpriteId, fetchOptions, useCache } = {}) {
const spriteId = customSpriteId || ICON_SPRITE_ID
if (
useCache &&
localStorage &&
localStorage.getItem &&
localStorage.getItem('ICON_SPRITE_ID') === spriteId
) {
// Current version is in localStorage, get it and inject it
document.body.insertAdjacentHTML(
'afterbegin',
localStorage.getItem('SVG_SPRITE_DATA')
)
} else {
fetch(spriteId, fetchOptions)
.then(res => {
if (!res.ok) throw new Error(res.statusText)
return res
})
.then(res => res.text())
.then(svgSprite => {
document.body.insertAdjacentHTML('afterbegin', svgSprite)
// Add version and data to localstorage for subsequent fetches 🎉
if (localStorage && localStorage.setItem) {
localStorage.setItem('ICON_SPRITE_ID', spriteId)
localStorage.setItem('SVG_SPRITE_DATA', svgSprite)
}
})
// eslint-disable-next-line
.catch(err => console.warn(`SVG sprite fetch failure: ${err.message}`))
}
}
|
javascript
|
{
"resource": ""
}
|
q3586
|
delimiterMutator
|
train
|
function delimiterMutator(input){
var delimiter=this.ra([' ','\n','<','>','\"','\'',',','.',';','|'])
// console.log('Delimiter: '+delimiter)
var chunks=input.split(delimiter)
var chunk=this.ra(chunks)
if(chunk.length>5 && chunk.length<300)
this.storage.storeKeyValuePair([delimiter,chunk],'delimiterMutator')
var oldChunk=this.storage.getValueForKey(delimiter,'delimiterMutator')
if(chunks.length<3 || chunks.length<input.length/300){
// console.log('Fail:'+ (chunks.length)+'<'+(input.length/300) )
return false
}
switch(this.rint(3)) {
case 0:
// console.log('Repeat')
return chunkRepeat.call(this,chunks,delimiter,oldChunk)
case 1:
// console.log('Swap')
return chunkSwap.call(this,chunks,delimiter,oldChunk)
case 2:
// console.log('Move')
return chunkMove.call(this,chunks,delimiter)
default:
console.log('WTF?')
}
}
|
javascript
|
{
"resource": ""
}
|
q3587
|
Option
|
train
|
function Option(handler, options, desc) {
Option.super_.apply(this, [handler, options, desc]);
if (options.params && options.params.hasOwnProperty('optional')) {
throw new Error('optional parameter is not allowed for options');
}
}
|
javascript
|
{
"resource": ""
}
|
q3588
|
train
|
function (path, options, callback) {
var self = this;
if (typeof options === 'function') {
callback = options;
options = undefined;
}
_.defaults(options || (options = {}), OPTIM_DEFAULT_OPTIONS);
var bucks = new Bucks();
bucks.empty();
if (REG_OPTIPNG_FILE.test(path) && options.optipng.use) { // optipng
bucks.add(function(err, res, next) {
self.optipng(path, options.optipng.options, function(err) {
if (err) {
logger.error('optipng error.', err);
next(err);
return;
}
logger.info('execute optipng:', path);
next();
});
});
}
if (REG_OPTIPNG_FILE.test(path) && options.pngquant.use) { // pngquant
bucks.add(function(err, res, next) {
self.pngquant(path, options.pngquant.options, function(err) { // pngquant
if (err) {
logger.error('pngquant error.', err);
next(err);
return;
}
logger.info('execute pngquant:', path);
next();
});
});
}
if (REG_JPEGOPTIM_FILE.test(path) && options.jpegoptim.use) { // jpegoptim
bucks.add(function(err, res, next) {
self.jpegoptim(path, options.jpegoptim.options, function(err) {
if (err) {
logger.error('jpegoptim error.', err);
next(err);
return;
}
logger.info('executejpegoptim:', path);
next();
});
});
}
if (bucks._tasks.length === 0) {
logger.info('no match extension. path: ' + path);
}
bucks.end(function(err, ress) {
callback && callback(err, path);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q3589
|
train
|
function (dirpath, options, callback) {
var self = this;
if (typeof options === 'function') {
callback = options;
options = undefined;
}
if (!fsys.isDirectorySync(dirpath)) {
logger.error('not a directory. path:', dirpath);
callback && callback(new Error('not a directory. path: ' + dirpath));
return;
}
var bucks = new Bucks();
bucks.empty();
var tasks = [];
fsys.walk(dirpath, function filefn(prefix, dir, file, stats) {
var src = path.join(dir, file);
tasks.push(function (err, res, next) {
self.optim(src, options, next);
});
});
var range = options.limit || 10;
var gtasks = [];
for(var i = 0; i < Math.ceil(tasks.length / range); i++) {
var j = i * range;
var p = tasks.slice(j, j + range);
gtasks.push(p);
}
logger.warn('tasks:', tasks.length); // all task num
for (var k = 0; k < gtasks.length; k++) {
bucks.parallel(gtasks[k]);
}
bucks.end(function(err, ress) {
callback && callback(err, ress);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q3590
|
train
|
function(base) {
var node = $(base).children('img:first');
if (node.attr('src').substr(0, 5) !== 'data:') {
node.attr('src', imgBase64(node, this.file.mime));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3591
|
train
|
function(base) {
var dfd = $.Deferred(),
ab = 'about:blank';
base.src = ab;
setTimeout(function() {
var src;
try {
src = base.contentWindow.location.href;
} catch(e) {
src = null;
}
if (src === ab) {
dfd.resolve();
} else {
dfd.reject();
}
}, 100);
return dfd;
}
|
javascript
|
{
"resource": ""
}
|
|
q3592
|
deepEqual
|
train
|
function deepEqual(object, ...compareWith) {
// check if object is an object
if (is(object)) {
// deflate the original object (easier then looping through the inner objects)
const ogObject = deflate(object);
// use reduce to compare all the objects with the original object
return compareWith.reduce((isEqual, currentObject) => {
// if isEqual already is false just skip
if (!isEqual) return false;
// deflate the current object (easier then looping through the inner objects)
return equal(ogObject, deflate(currentObject));
}, true);
}
// if the object isn't an object return false
return false;
}
|
javascript
|
{
"resource": ""
}
|
q3593
|
_makeJsonResponseBody
|
train
|
function _makeJsonResponseBody (statusCode, flash) {
const hasSession = !!R.path(['session', 'flash'], this);
return {
statusCode : statusCode,
flash : {
notice : hasSession ? flash.apply(this, ['notice']) : [],
error : hasSession ? flash.apply(this, ['error']) : []
}
};
}
|
javascript
|
{
"resource": ""
}
|
q3594
|
train
|
function (basedir, filefn, dirfn) {
filefn = filefn || function() {};
dirfn = dirfn || function() {};
var readdirSync = function(dir) {
var files = fs.readdirSync(dir);
for (var i = 0; i < files.length; i++) {
var file = dir+'/'+files[i];
//debug('before fs.statsSync:', file);
var stats = fs.statSync(file);
if (stats.isFile()) {
var prefix = dir.replace(basedir, '');
filefn(prefix, dir, files[i], stats);
} else if (stats.isDirectory()) {
var prefix = file.replace(basedir, '');
dirfn(prefix, stats);
readdirSync(file);
} else {
console.error('error:'.error, 'It is a file type that is not assumed. file:', file);
return;
}
}
};
readdirSync(basedir);
}
|
javascript
|
{
"resource": ""
}
|
|
q3595
|
train
|
function(link, first_time) {
var char = (link.href.indexOf('?')>-1) ? '&' : '?';
link.href += (first_time === true) ? (char+(new Date()).getTime()) : char;
}
|
javascript
|
{
"resource": ""
}
|
|
q3596
|
train
|
function(first_time) {
var links = document.getElementsByTagName("link");
var link;
var replacing = [];
for(var i = 0; i < links.length; i++) {
link = links[i];
char = '?';
if(link.rel === "stylesheet") {
replacing.push(link);
}
}
var fn = is_touch_device() ? simple_swap_links : swap_links;
for(i=0; i < replacing.length; i++) {
fn(replacing[i], first_time);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3597
|
sort
|
train
|
function sort(object, iterator, follow = false) {
// check if the object is an object and isn't empty
if (is(object) && !empty(object) && typeof iterator === 'function') {
// create empty object for result
let result = {};
// for each over the object keys and values
// follow is passed into each therefore the
// each function works out whether to follow
// the objects
each(object, (key, value) => {
// run the iterator function on the key and
// value and if it evaluates to true set
// the result object
if (iterator(key, value) === true) {
// set the key/value on the result object
result = set(result, key, value);
}
}, follow);
// return the result
return result;
}
// if the object isn't an object or is empty return
// an empty object this will keep the return immutable
return {};
}
|
javascript
|
{
"resource": ""
}
|
q3598
|
train
|
function (srcPath, options) {
_.defaults(options || (options = {}), DEFAULT_OPTIONS);
if(!this.isSpriteImage(srcPath, options)) {
logger.error('is not SpriteImage. srcPath:' + srcPath);
return [];
}
var separator = options.separator;
var ratios = options.ratios;
var group = this.getGroup(srcPath, options);
var head = this.getHead(srcPath, options);
var files = [];
files.push(head + separator + group + '.styl');
for (var i = 0; i < ratios.length; i++) {
files.push('sprite' + separator + group + '@' + (ratios[i] * 10) + 'x.png');
}
return files;
}
|
javascript
|
{
"resource": ""
}
|
|
q3599
|
values
|
train
|
function values(object, follow) {
// check if object is an object
if (is(object) && !empty(object)) {
// create an empty array for the result
const result = [];
// if follow is true flatten the object keys so
// its easy to get the path to get the value
// if follow is false it will just be the base
// object therefore it will only need to base keys
const keysObject = follow
? deflate(object)
: object;
// loop over the keys of the object
Object.keys(keysObject).forEach((key) => {
// get the current key value
const value = keysObject[key];
// add it to the result array
result.push(value);
});
// return the result
return result;
}
// if the object isn't an object or is empty return
// an empty array because it won't contain any values
return [];
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.