_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q6700
|
handle
|
train
|
function handle(nativeEvent) {
var event = SyntheticKeyboardEvent.getPooled({}, 'hotkey', nativeEvent);
try {
dispatchEvent(event, handlers);
} finally {
if (!event.isPersistent()) {
event.constructor.release(event);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6701
|
dispatchEvent
|
train
|
function dispatchEvent(event, handlers) {
for (var i = (handlers.length - 1); i >= 0; i--) {
if (event.isPropagationStopped()) {
break;
}
var returnValue = handlers[i](event);
if (returnValue === false) {
event.stopPropagation();
event.preventDefault();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6702
|
train
|
function(nodes) {
if (nodes.length == 0) return nodes;
var results = [], n;
for (var i = 0, l = nodes.length; i < l; i++)
if (!(n = nodes[i])._counted) {
n._counted = true;
results.push(Element.extend(n));
}
return Selector.handlers.unmark(results);
}
|
javascript
|
{
"resource": ""
}
|
|
q6703
|
addNextNodesToASTObject
|
train
|
function addNextNodesToASTObject(ASTObject) {
const ASTObjectsForDepths = [ASTObject];
function addNextNodes(ASTObject, depth) {
const depthPlus1 = depth + 1;
ASTObjectsForDepths[depthPlus1] = ASTObject;
if (ASTObject.left)
addNextNodes(ASTObject.left, depthPlus1);
if (ASTObject.right)
addNextNodes(ASTObject.right, depthPlus1);
if (ASTObject.next) {
const ASTObjectForDepth = ASTObjectsForDepths[depth];
if (ASTObjectForDepth.nextNodes)
ASTObjectForDepth.nextNodes.push(ASTObject.next);
else
ASTObjectForDepth.nextNodes = [ASTObject.next];
addNextNodes(ASTObject.next, depth);
}
}
addNextNodes(ASTObject, 0);
}
|
javascript
|
{
"resource": ""
}
|
q6704
|
Counter
|
train
|
function Counter() {
this.total = 0;
this.executed = 0;
this.passed = 0;
this.error = 0;
this.failed = 0;
this.timeout = 0;
this.aborted = 0;
this.inconclusive = 0;
this.passedButRunAborted = 0;
this.notRunnable = 0;
this.notExecuted = 0;
this.disconnected = 0;
this.warning = 0;
this.completed = 0;
this.inProgress = 0;
this.pending = 0;
}
|
javascript
|
{
"resource": ""
}
|
q6705
|
Times
|
train
|
function Times(params) {
this.creation = params.creation;
this.queuing = params.queuing;
this.start = params.start;
this.finish = params.finish;
}
|
javascript
|
{
"resource": ""
}
|
q6706
|
Deployment
|
train
|
function Deployment(params) {
this.runDeploymentRoot = params.runDeploymentRoot
this.userDeploymentRoot = params.userDeploymentRoot
this.deploySatelliteAssemblies = params.deploySatelliteAssemblies
this.ignoredDependentAssemblies = params.ignoredDependentAssemblies
this.enabled = params.enabled
}
|
javascript
|
{
"resource": ""
}
|
q6707
|
assembleMiddleware
|
train
|
function assembleMiddleware (middlewareStackClasses, context)
{
var middlewares = [];
middlewareStackClasses.forEach (function (MiddlewareClass)
{
middlewares.push (new MiddlewareClass (context));
});
return middlewares;
}
|
javascript
|
{
"resource": ""
}
|
q6708
|
traceModule
|
train
|
function traceModule (moduleName, context, processHook)
{
var module = context.modules[moduleName];
if (!module)
fatal ('Module <cyan>%</cyan> was not found.', moduleName);
// Ignore the module if it's external.
if (module.external)
return;
// Include required submodules first.
context.trigger (ContextEvent.ON_BEFORE_DEPS, [module]);
module.requires.forEach (function (modName)
{
traceModule (modName, context, processHook);
});
// Ignore references to already loaded modules or to explicitly excluded modules.
if (!context.loaded[module.name] && !~context.options.excludedModules.indexOf (module.name)) {
info ('Including module <cyan>%</cyan>.', moduleName);
context.loaded[module.name] = true;
processHook (module);
}
}
|
javascript
|
{
"resource": ""
}
|
q6709
|
safeCall
|
train
|
function safeCall (fn, args, callback) {
args = Array.prototype.slice.call(arguments, 1);
callback = args.pop();
var callbackCalled;
try {
args.push(safeCallback);
fn.apply(null, args);
}
catch (err) {
if (callbackCalled) {
throw err;
}
else {
safeCallback(err);
}
}
function safeCallback (err, result) {
if (callbackCalled) {
err = ono('Error in %s: callback was called multiple times', fn.name);
}
callbackCalled = true;
callback(err, result);
}
}
|
javascript
|
{
"resource": ""
}
|
q6710
|
readReferencedFiles
|
train
|
function readReferencedFiles (schema, callback) {
var filesBeingRead = [], filesToRead = [];
var file, i;
// Check the state of all files in the schema
for (i = 0; i < schema.files.length; i++) {
file = schema.files[i];
if (file[__internal].state < STATE_READING) {
filesToRead.push(file);
}
else if (file[__internal].state < STATE_READ) {
filesBeingRead.push(file);
}
}
// Have we finished reading everything?
if (filesToRead.length === 0 && filesBeingRead.length === 0) {
return safeCall(finished, schema, callback);
}
// In sync mode, just read the next file.
// In async mode, start reading all files in the queue
var numberOfFilesToRead = schema.config.sync ? 1 : filesToRead.length;
for (i = 0; i < numberOfFilesToRead; i++) {
file = filesToRead[i];
safeCall(readFile, file, callback);
}
}
|
javascript
|
{
"resource": ""
}
|
q6711
|
finished
|
train
|
function finished (schema, callback) {
schema.plugins.finished();
delete schema.config.sync;
callback(null, schema);
}
|
javascript
|
{
"resource": ""
}
|
q6712
|
parseMetaEvent
|
train
|
function parseMetaEvent(delay, cursor) {
var type, specs = {}, length, value, rates;
rates = [24, 25, 30, 30];
type = cursor.readUInt8();
length = parseVarInt(cursor);
switch (type) {
case MetaEvent.TYPE.SEQUENCE_NUMBER:
specs.number = cursor.readUInt16LE();
break;
case MetaEvent.TYPE.TEXT:
case MetaEvent.TYPE.COPYRIGHT_NOTICE:
case MetaEvent.TYPE.SEQUENCE_NAME:
case MetaEvent.TYPE.INSTRUMENT_NAME:
case MetaEvent.TYPE.LYRICS:
case MetaEvent.TYPE.MARKER:
case MetaEvent.TYPE.CUE_POINT:
case MetaEvent.TYPE.PROGRAM_NAME:
case MetaEvent.TYPE.DEVICE_NAME:
specs.text = cursor.toString('utf8', length);
break;
case MetaEvent.TYPE.MIDI_CHANNEL:
specs.channel = cursor.readUInt8();
break;
case MetaEvent.TYPE.MIDI_PORT:
specs.port = cursor.readUInt8();
break;
case MetaEvent.TYPE.END_OF_TRACK:
break;
case MetaEvent.TYPE.SET_TEMPO:
specs.tempo = 60000000 / ((cursor.readUInt8() << 16) +
(cursor.readUInt8() << 8) +
cursor.readUInt8());
break;
case MetaEvent.TYPE.SMPTE_OFFSET:
value = cursor.readUInt8();
specs.rate = rates[value >> 6];
specs.hours = value & 0x3F;
specs.minutes = cursor.readUInt8();
specs.seconds = cursor.readUInt8();
specs.frames = cursor.readUInt8();
specs.subframes = cursor.readUInt8();
break;
case MetaEvent.TYPE.TIME_SIGNATURE:
specs.numerator = cursor.readUInt8();
specs.denominator = Math.pow(2, cursor.readUInt8());
specs.metronome = cursor.readUInt8();
specs.clockSignalsPerBeat = (192 / cursor.readUInt8());
break;
case MetaEvent.TYPE.KEY_SIGNATURE:
specs.note = cursor.readInt8();
specs.major = !cursor.readUInt8();
break;
case MetaEvent.TYPE.SEQUENCER_SPECIFIC:
specs.data = cursor.slice(length).buffer;
break;
default:
throw new error.MIDIParserError(
type,
'known MetaEvent type',
cursor.tell()
);
}
return new MetaEvent(type, specs, delay);
}
|
javascript
|
{
"resource": ""
}
|
q6713
|
parseSysexEvent
|
train
|
function parseSysexEvent(delay, type, cursor) {
var data, length = parseVarInt(cursor);
data = cursor.slice(length).buffer;
return new SysexEvent(type, data, delay);
}
|
javascript
|
{
"resource": ""
}
|
q6714
|
parseChannelEvent
|
train
|
function parseChannelEvent(delay, type, channel, cursor) {
var specs = {};
switch (type) {
case ChannelEvent.TYPE.NOTE_OFF:
specs.note = cursor.readUInt8();
specs.velocity = cursor.readUInt8();
break;
case ChannelEvent.TYPE.NOTE_ON:
specs.note = cursor.readUInt8();
specs.velocity = cursor.readUInt8();
break;
case ChannelEvent.TYPE.NOTE_AFTERTOUCH:
specs.note = cursor.readUInt8();
specs.pressure = cursor.readUInt8();
break;
case ChannelEvent.TYPE.CONTROLLER:
specs.controller = cursor.readUInt8();
specs.value = cursor.readUInt8();
break;
case ChannelEvent.TYPE.PROGRAM_CHANGE:
specs.program = cursor.readUInt8();
break;
case ChannelEvent.TYPE.CHANNEL_AFTERTOUCH:
specs.pressure = cursor.readUInt8();
break;
case ChannelEvent.TYPE.PITCH_BEND:
specs.value = cursor.readUInt8() +
(cursor.readUInt8() << 7) - 8192;
break;
}
return new ChannelEvent(type, specs, channel, delay);
}
|
javascript
|
{
"resource": ""
}
|
q6715
|
parseEvent
|
train
|
function parseEvent(cursor, runningStatus) {
var delay, status, result;
delay = parseVarInt(cursor);
status = cursor.readUInt8();
// if the most significant bit is not set,
// we use the last status
if ((status & 0x80) === 0) {
if (!runningStatus) {
throw new error.MIDIParserError(
'undefined event status',
cursor.tell()
);
}
status = runningStatus;
cursor.seek(cursor.tell() - 1);
} else {
runningStatus = status;
}
if (status === 0xFF) {
result = parseMetaEvent(delay, cursor);
} else if (status === 0xF0 || status === 0xF7) {
result = parseSysexEvent(delay, status & 0xF, cursor);
} else if (status >= 0x80 && status < 0xF0) {
result = parseChannelEvent(delay, status >> 4, status & 0xF, cursor);
} else {
throw new error.MIDIParserError(
status,
'known status type',
cursor.tell()
);
}
return {
runningStatus: runningStatus,
event: result
};
}
|
javascript
|
{
"resource": ""
}
|
q6716
|
encodeSysexEvent
|
train
|
function encodeSysexEvent(event) {
var cursor, length;
length = encodeVarInt(event.data.length);
cursor = new BufferCursor(new buffer.Buffer(
1 + length.length + event.data.length
));
cursor.writeUInt8(0xF0 | event.type);
cursor.copy(length);
cursor.copy(event.data);
return cursor.buffer;
}
|
javascript
|
{
"resource": ""
}
|
q6717
|
encodeChannelEvent
|
train
|
function encodeChannelEvent(event) {
var cursor, eventData, value;
switch (event.type) {
case ChannelEvent.TYPE.NOTE_OFF:
eventData = new BufferCursor(new buffer.Buffer(2));
eventData.writeUInt8(event.note);
eventData.writeUInt8(event.velocity);
break;
case ChannelEvent.TYPE.NOTE_ON:
eventData = new BufferCursor(new buffer.Buffer(2));
eventData.writeUInt8(event.note);
eventData.writeUInt8(event.velocity);
break;
case ChannelEvent.TYPE.NOTE_AFTERTOUCH:
eventData = new BufferCursor(new buffer.Buffer(2));
eventData.writeUInt8(event.note);
eventData.writeUInt8(event.pressure);
break;
case ChannelEvent.TYPE.CONTROLLER:
eventData = new BufferCursor(new buffer.Buffer(2));
eventData.writeUInt8(event.controller);
eventData.writeUInt8(event.value);
break;
case ChannelEvent.TYPE.PROGRAM_CHANGE:
eventData = new BufferCursor(new buffer.Buffer(1));
eventData.writeUInt8(event.program);
break;
case ChannelEvent.TYPE.CHANNEL_AFTERTOUCH:
eventData = new BufferCursor(new buffer.Buffer(1));
eventData.writeUInt8(event.pressure);
break;
case ChannelEvent.TYPE.PITCH_BEND:
value = event.value + 8192;
eventData = new BufferCursor(new buffer.Buffer(2));
eventData.writeUInt8(value & 0x7F);
eventData.writeUInt8(value >> 7);
break;
default:
throw new error.MIDIEncoderError(
event.type,
'known ChannelEvent type'
);
}
cursor = new BufferCursor(new buffer.Buffer(
1 + eventData.length
));
cursor.writeUInt8((event.type << 4) + event.channel);
cursor.copy(eventData.buffer);
return cursor.buffer;
}
|
javascript
|
{
"resource": ""
}
|
q6718
|
encodeEvent
|
train
|
function encodeEvent(event, runningStatus) {
var delay, eventData, cursor;
delay = encodeVarInt(event.delay);
if (event instanceof MetaEvent) {
eventData = encodeMetaEvent(event);
} else if (event instanceof SysexEvent) {
eventData = encodeSysexEvent(event);
} else if (event instanceof ChannelEvent) {
eventData = encodeChannelEvent(event);
} else {
throw new error.MIDIEncoderError(
event.constructor.name,
'known Event type'
);
}
// if current type is the same as the last one,
// we don't include it
// (sysex events cancel the running status and
// meta events ignore it)
if (event instanceof ChannelEvent) {
if (runningStatus === eventData[0]) {
eventData = eventData.slice(1);
} else {
runningStatus = eventData[0];
}
} else if (event instanceof SysexEvent) {
runningStatus = null;
}
cursor = new BufferCursor(new buffer.Buffer(
delay.length + eventData.length
));
cursor.copy(delay);
cursor.copy(eventData);
return {
runningStatus: runningStatus,
data: cursor.buffer
};
}
|
javascript
|
{
"resource": ""
}
|
q6719
|
OverrideDependenciesMiddleware
|
train
|
function OverrideDependenciesMiddleware (context)
{
/* jshint unused: vars */
var options = context.options.overrideDependencies
, enabled = options.dependencies && options.dependencies.length;
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
if (!enabled) return;
var mainModuleName = context.options.mainModule;
var mainModule = context.modules[mainModuleName] = new ModuleDef (mainModuleName);
mainModule.requires = options.dependencies;
// Must set head to a non-empty string to mark the module as being initialized.
mainModule.head = ' ';
};
this.trace = function (module)
{
/* jshint unused: vars */
};
this.build = function (targetScript)
{
/* jshint unused: vars */
if (!enabled) return;
if (context.options.debugBuild && context.options.debugBuild.enabled) {
var declaration = sprintf ("angular.module('%',%);",
context.options.mainModule,
util.toQuotedList (options.dependencies)
);
context.appendOutput += sprintf ('<script>%</script>', declaration);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q6720
|
Header
|
train
|
function Header(fileType, trackCount, ticksPerBeat) {
this._fileType = fileType || Header.FILE_TYPE.SYNC_TRACKS;
this._trackCount = trackCount || 0;
this._ticksPerBeat = ticksPerBeat || 120;
}
|
javascript
|
{
"resource": ""
}
|
q6721
|
BuildAssetsMiddleware
|
train
|
function BuildAssetsMiddleware (context)
{
var grunt = context.grunt
, options = context.options.assets;
/**
* Records which files have been already exported.
* Prevents duplicate asset exports.
* It's a map of absolute file names to boolean `true`.
* @type {Object.<string,boolean>}
*/
var exportedAssets = {};
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
// Do nothing
};
this.trace = function (module)
{
/* jshint unused: vars */
// Do nothing.
};
this.build = function (targetScript)
{
if (!options.enabled) return;
// Import file paths.
var stylehseets = grunt.config (context.options.requiredStylesheets.exportToConfigProperty);
if (!stylehseets) return; // No stylesheet sources are configured.
var targetPath = path.dirname (targetScript);
stylehseets.forEach (function (filePath)
{
var src = grunt.file.read (filePath);
scan (path.dirname (filePath), targetPath, src);
});
};
//--------------------------------------------------------------------------------------------------------------------
// PRIVATE
//--------------------------------------------------------------------------------------------------------------------
/**
* Scans a stylesheet for asset URL references and copies the assets to the build folder.
* @private
* @param {string} basePath
* @param {string} targetPath
* @param {string} sourceCode
*/
function scan (basePath, targetPath, sourceCode)
{
var match;
while ((match = MATCH_URLS.exec (sourceCode))) {
var url = match[2];
if (!url.match (/^http/i) && url[0] !== '/') { // Skip absolute URLs
var absSrcPath = path.resolve (basePath, url)
, absDestPath = path.resolve (targetPath, options.targetDir, url)
, relDestPath = path.relative (targetPath, absDestPath);
if (relDestPath[0] === '.')
return util.warn ('Relative asset url falls outside the build folder: <cyan>%</cyan>%', url, util.NL);
if (exportedAssets[absDestPath]) // skip already exported asset
continue;
else exportedAssets[absDestPath] = true;
var absTargetFolder = path.dirname (absDestPath);
grunt.file.mkdir (absTargetFolder);
if (options.symlink)
fs.symlinkSync (absSrcPath, absDestPath);
else grunt.file.copy (absSrcPath, absDestPath);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6722
|
MakeDebugBuildMiddleware
|
train
|
function MakeDebugBuildMiddleware (context)
{
var options = context.options.debugBuild;
/** @type {string[]} */
var traceOutput = [];
//--------------------------------------------------------------------------------------------------------------------
// EVENTS
//--------------------------------------------------------------------------------------------------------------------
context.listen (ContextEvent.ON_AFTER_ANALYZE, function ()
{
if (options.enabled) {
var space = context.verbose ? NL : '';
writeln ('%Generating the <cyan>debug</cyan> build...%', space, space);
}
});
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
// Do nothing
};
this.trace = function (/*ModuleDef*/ module)
{
if (!options.enabled) return;
var rep = options.rebaseDebugUrls;
module.filePaths ().forEach (function (path)
{
if (context.outputtedFiles[path] && context.outputtedFiles[path] !== module.name)
return;
context.outputtedFiles[path] = true;
if (rep)
for (var i = 0, m = rep.length; i < m; ++i)
path = path.replace (rep[i].match, rep[i].replaceWith);
if (path) // Ignore empty path; it means that this middleware should not output a script tag.
traceOutput.push (util.sprintf ('<script src=\"%\"></script>', path));
});
};
this.build = function (targetScript)
{
/* jshint unused: vars */
if (!options.enabled) return;
/** @type {string[]} */
var output = ['document.write (\''];
if (context.prependOutput)
output.push (context.prependOutput);
// Output the modules (if any).
util.arrayAppend (output, traceOutput);
if (context.appendOutput)
output.push (context.appendOutput);
output.push ('\');');
util.writeFile (targetScript, output.join ('\\\n'));
};
}
|
javascript
|
{
"resource": ""
}
|
q6723
|
Parser
|
train
|
function Parser( options ) {
if( !(this instanceof Parser) )
return new Parser( options )
Stream.Transform.call( this, options )
this._readableState.objectMode = true
this._buffer = ''
}
|
javascript
|
{
"resource": ""
}
|
q6724
|
readFileAsync
|
train
|
function readFileAsync (args) {
var file = args.file;
var config = args.config;
var next = args.next;
var url = parseUrl(file.url);
var transport;
switch (url.protocol) {
case 'http:':
transport = followRedirects.http;
break;
case 'https:':
transport = followRedirects.https;
break;
default:
// It's not an HTTP or HTTPS URL, so let some other plugin handle it
return next();
}
var httpConfig = {
hostname: url.hostname,
port: url.port,
path: url.pathname + url.search,
headers: Object.assign({}, defaultHeaders, config.http.headers),
timeout: config.http.timeout,
followRedirects: !!config.http.maxRedirects,
maxRedirects: config.http.maxRedirects,
};
var req = transport.get(httpConfig);
req.on('error', next);
req.on('timeout', function handleTimeout () {
req.abort();
});
req.once('response', function handleResponse (res) {
var responseChunks = [];
var chunksAreStrings = false;
decompressResponse(res);
setHttpMetadata(file, res);
res.on('error', next);
res.on('data', function handleResponseData (chunk) {
// Keep track of whether ANY of the chunks are strings (as opposed to Buffers)
if (typeof chunk === 'string') {
chunksAreStrings = true;
}
responseChunks.push(chunk);
});
res.on('end', function handleResponseEnd () {
try {
var response;
if (chunksAreStrings) {
// Return the response as a string
response = responseChunks.join('');
}
else {
// Return the response as a Buffer (Uint8Array)
response = Buffer.concat(responseChunks);
}
next(null, response);
}
catch (err) {
next(err);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q6725
|
parseUrl
|
train
|
function parseUrl (url) {
if (typeof URL === 'function') {
// Use the new WHATWG URL API
return new URL(url);
}
else {
// Use the legacy url API
var parsed = legacyURL.parse(url);
// Replace nulls with default values, for compatibility with the WHATWG URL API
parsed.pathname = parsed.pathname || '/';
parsed.search = parsed.search || '';
}
}
|
javascript
|
{
"resource": ""
}
|
q6726
|
decompressResponse
|
train
|
function decompressResponse (res) {
var encoding = lowercase(res.headers['content-encoding']);
var isCompressed = ['gzip', 'compress', 'deflate'].indexOf(encoding) >= 0;
if (isCompressed) {
// The response is compressed, so add decompression middleware to the stream
res.pipe(zlib.createUnzip());
// Remove the content-encoding header, to prevent double-decoding
delete res.headers['content-encoding'];
}
}
|
javascript
|
{
"resource": ""
}
|
q6727
|
fromHeaderOrQuerystring
|
train
|
function fromHeaderOrQuerystring(req) {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
} else if (req.query && req.query.token) {
return req.query.token;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q6728
|
train
|
function (a, b) {
if (a) {
if (Array.isArray(b)) {
for (var i = 0; i < b.length; i++) {
if (b[i]) {
a[i] = extend(a[i], b[i]);
}
}
return a;
} else if (typeof b === 'object') {
Object.getOwnPropertyNames(b).forEach(function (key) {
a[key] = extend(a[key], b[key]);
});
return a;
}
}
return b;
}
|
javascript
|
{
"resource": ""
}
|
|
q6729
|
allora
|
train
|
function allora (parent, prop) {
return new Proxy(prop ? parent[prop] : parent, {
get: (target, property) => {
// no function no need for promises in return
if (isOnCallback(property)) {
// detect properties like
// window.onload.then(() => console.log('loaded'))
return new Promise((resolve) => {
target[property] = resolve
})
} else if (typeof target[property] !== 'function') {
return target[property]
} else {
// make proxy also the nested object properties
return allora(target, property)
}
},
// this is cool to make promiseable event emitters
// and many other native node methods
apply: (target, thisArg, argumentsList) => {
let returnValue
const promise = new Promise((resolve, reject) => {
// guessing the timer functions from the type of arguments passed to the method
const isTimer = !argumentsList.length || typeof argumentsList[0] === 'number'
// assuming the callback will be always the second argument
argumentsList.splice(isTimer ? 0 : 1, 0, resolve)
returnValue = Reflect.apply(target, parent, argumentsList)
})
// Return the returnValue through valueOf
promise.valueOf = () => returnValue
promise.toString = () => returnValue
return promise
}
})
}
|
javascript
|
{
"resource": ""
}
|
q6730
|
renderToContext
|
train
|
function renderToContext (geoJson, projection) {
var shapePath = new THREE.ShapePath();
var mapRenderContext = new ThreeJSRenderContext(shapePath);
var mapPath = geoPath(projection, mapRenderContext);
mapPath(geoJson);
return mapRenderContext;
}
|
javascript
|
{
"resource": ""
}
|
q6731
|
train
|
function(callback){
var self = this;
// if we have no pages just fire callback
if(self.pageCollection.length === 0){
callback(self);
}
// this is called once a page is fully parsed
whenPageIsFetched = function(){
self.completed ++;
if(self.completed === self.pageCollection.length){
callback(self);
} else {
findUnfetchedPages();
}
}
findUnfetchedPages = function(){
_.each(self.pageCollection, function (page) {
if (page.status === "unfetched") {
page.fetch(whenPageIsFetched);
}
});
},
findUnfetchedPages();
}
|
javascript
|
{
"resource": ""
}
|
|
q6732
|
train
|
function (){
var out = {}
if(this.profiles.length !== 0){
out.profiles = this.profiles
}
if(this.noProfilesFound.length !== 0){
out.noProfilesFound = this.noProfilesFound;
}
if(utils.hasProperties(this.combinedProfile)){
out.combinedProfile = this.combinedProfile
}
return out;
}
|
javascript
|
{
"resource": ""
}
|
|
q6733
|
commonUserName
|
train
|
function commonUserName(objs, logger){
logger.info('finding common username');
var i = objs.length,
x = 0
usernames = [],
highest = 0,
out ='';
while (x < i) {
appendName(objs[x].userName);
x++;
}
var i = usernames.length;
while (i--) {
if(usernames[i].count > highest){
highest = usernames[i].count;
out = usernames[i].name;
}
}
function appendName(userName){
var i = usernames.length;
while (i--) {
if(usernames[i].name === userName){
usernames[i].count ++;
return;
}
}
usernames.push({
'name': userName,
'count': 1
})
}
return out;
}
|
javascript
|
{
"resource": ""
}
|
q6734
|
appendUrl
|
train
|
function appendUrl(url, urls) {
var i = urls.length
found = false;
while (i--) {
if (utils.compareUrl(urls[i], url))
found = true;
}
if (found === false && utils.isUrl(url))
urls.push(url);
}
|
javascript
|
{
"resource": ""
}
|
q6735
|
rateAddress
|
train
|
function rateAddress(addr){
var rating = 0;
if(addr != undefined){
if (addr['extended-address']) rating++;
if (addr['street-address']) rating++;
if (addr.locality) rating++;
if (addr.region) rating++;
if (addr['postal-code']) rating++;
if (addr['country-name']) rating++;
}
return rating;
}
|
javascript
|
{
"resource": ""
}
|
q6736
|
checkFamily
|
train
|
function checkFamily(program, family) {
var familyIndex = gm.families.indexOf(family.toLowerCase());
if (familyIndex === -1 || program < (familyIndex * 8) ||
program >= ((familyIndex + 1) * 8)) {
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q6737
|
format
|
train
|
function format(arg) {
if (typeof arg === 'number') {
return '0x' + arg.toString(16).toUpperCase();
}
if (typeof arg === 'string') {
return '"' + arg + '"';
}
return arg.toString();
}
|
javascript
|
{
"resource": ""
}
|
q6738
|
MIDIParserError
|
train
|
function MIDIParserError(actual, expected, byte) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.actual = actual;
this.expected = expected;
actual = format(actual);
expected = format(expected);
this.message = 'Invalid MIDI file: expected ' +
expected + ' but found ' + actual;
if (byte !== undefined) {
this.byte = byte;
this.message += ' (at byte ' + byte + ')';
}
}
|
javascript
|
{
"resource": ""
}
|
q6739
|
MIDIEncoderError
|
train
|
function MIDIEncoderError(actual, expected) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.actual = actual;
this.expected = expected;
actual = format(actual);
expected = format(expected);
this.message = 'MIDI encoding error: expected ' +
expected + ' but found ' + actual;
}
|
javascript
|
{
"resource": ""
}
|
q6740
|
MIDIInvalidEventError
|
train
|
function MIDIInvalidEventError(message) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
}
|
javascript
|
{
"resource": ""
}
|
q6741
|
MIDIInvalidArgument
|
train
|
function MIDIInvalidArgument(message) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
}
|
javascript
|
{
"resource": ""
}
|
q6742
|
MIDINotMIDIError
|
train
|
function MIDINotMIDIError() {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = 'Not a valid MIDI file';
}
|
javascript
|
{
"resource": ""
}
|
q6743
|
MIDINotSupportedError
|
train
|
function MIDINotSupportedError(message) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
}
|
javascript
|
{
"resource": ""
}
|
q6744
|
postMessage
|
train
|
function postMessage(message, target, force) {
var consumer;
var parsed;
if (!this.disposed) {
try {
if (message) {
if (this.ready || force) {
// Post the message
consumer = target || this.receiver;
parsed = _prepareMessage.call(this, message);
consumer.postMessage(parsed);
return true;
}
else if (this.maxConcurrency >= this.messageQueue.length) {
// Need to delay/queue messages till target is ready
this.messageQueue.push(message);
return true;
}
else {
return false;
}
}
}
catch(ex) {
/* istanbul ignore next */
PostMessageUtilities.log("Error while trying to post the message", "ERROR", "PostMessageChannel");
return false;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6745
|
_hookupMessageChannel
|
train
|
function _hookupMessageChannel(onmessage) {
return function() {
this.channel = new MessageChannel();
this.receiver = this.channel.port1;
this.dispatcher = this.channel.port2;
this.receiver.onmessage = onmessage;
this.neutered = false;
}.bind(this);
}
|
javascript
|
{
"resource": ""
}
|
q6746
|
_isHandshake
|
train
|
function _isHandshake(event) {
return (event && event.data && "string" === typeof event.data && (0 === event.data.indexOf(TOKEN_PREFIX) || (HANSHAKE_PREFIX + this.token) === event.data));
}
|
javascript
|
{
"resource": ""
}
|
q6747
|
_wrapReadyCallback
|
train
|
function _wrapReadyCallback(onready, target) {
return function(err) {
if (target && "function" === typeof target.callback) {
target.callback.call(target.context, err, this.target);
}
if (onready) {
if ("function" === typeof onready) {
onready(err, this.target);
}
else if ("function" === typeof onready.callback) {
onready.callback.call(onready.context, err, this.target);
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
q6748
|
_waitForBody
|
train
|
function _waitForBody(options) {
options = options || {};
var onready = options.onready;
var doc = options.doc || root.document;
var delay = options.delay;
function _ready() {
if (doc.body) {
onready();
}
else {
PostMessageUtilities.delay(_ready, delay || DEFAULT_BODY_LOAD_DELAY);
}
}
PostMessageUtilities.delay(_ready, delay || false);
}
|
javascript
|
{
"resource": ""
}
|
q6749
|
_createIFrame
|
train
|
function _createIFrame(options, container) {
var frame = document.createElement("IFRAME");
var name = PostMessageUtilities.createUniqueSequence(IFRAME_PREFIX + PostMessageUtilities.SEQUENCE_FORMAT);
var delay = options.delayLoad;
var defaultAttributes = {
"id": name,
"name" :name,
"tabindex": "-1", // To prevent it getting focus when tabbing through the page
"aria-hidden": "true", // To prevent it being picked up by screen-readers
"title": "", // Adding an empty title for accessibility
"role": "presentation", // Adding a presentation role http://yahoodevelopers.tumblr.com/post/59489724815/easy-fixes-to-common-accessibility-problems
"allowTransparency":"true"
};
var defaultStyle = {
width :"0px",
height : "0px",
position :"absolute",
top : "-1000px",
left : "-1000px"
};
options.attributes = options.attributes || defaultAttributes;
for (var key in options.attributes){
if (options.attributes.hasOwnProperty(key)) {
frame.setAttribute(key, options.attributes[key]);
}
}
options.style = options.style || defaultStyle;
if (options.style) {
for (var attr in options.style) {
if (options.style.hasOwnProperty(attr)) {
frame.style[attr] = options.style[attr];
}
}
}
// Append and hookup after body tag opens
_waitForBody({
delay: delay,
onready: function() {
(container || document.body).appendChild(frame);
this.rmload = _addLoadHandler.call(this, frame);
_setIFrameLocation.call(this, frame, options.url, (false !== options.bust));
}.bind(this)
});
return frame;
}
|
javascript
|
{
"resource": ""
}
|
q6750
|
_addLoadHandler
|
train
|
function _addLoadHandler(frame) {
var load = function() {
this.loading = false;
if (this.handshakeAttempts === this.handshakeAttemptsOrig) {
// Probably a first try for handshake or a reload of the iframe,
// Either way, we'll need to perform handshake, so ready flag should be set to false (if not already)
this.ready = false;
}
_handshake.call(this, this.handshakeInterval);
}.bind(this);
PostMessageUtilities.addEventListener(frame, "load", load);
return function() {
_removeLoadHandler(frame, load);
};
}
|
javascript
|
{
"resource": ""
}
|
q6751
|
_setIFrameLocation
|
train
|
function _setIFrameLocation(frame, src, bust){
src += (0 < src.indexOf("?") ? "&" : "?");
if (bust) {
src += "bust=";
src += (new Date()).getTime() + "&";
}
src += ((this.hostParam ? "hostParam=" + this.hostParam + "&" + this.hostParam + "=" : "lpHost=") + encodeURIComponent(PostMessageUtilities.getHost(void 0, frame, true)));
if (!_isNativeMessageChannelSupported.call(this)) {
src += "&lpPMCPolyfill=true";
}
if (false === this.useObjects) {
src += "&lpPMDeSerialize=true";
}
frame.setAttribute("src", src);
}
|
javascript
|
{
"resource": ""
}
|
q6752
|
Input
|
train
|
function Input(native) {
EventEmitter.call(this);
this.native = native;
this.id = native.id;
this.manufacturer = native.manufacturer;
this.name = native.name;
this.version = native.version;
native.onmidimessage = function (event) {
var data, type, object;
data = new BufferCursor(new buffer.Buffer(event.data));
type = data.readUInt8();
object = parseChannelEvent(
event.receivedTime,
type >> 4,
type & 0xF,
data
);
this.emit('event', object);
}.bind(this);
}
|
javascript
|
{
"resource": ""
}
|
q6753
|
fetch
|
train
|
function fetch(identity, options, callback){
var completed = 0
combinedProfile = {};
// this is called once a page is fully parsed
function whenFetched(err, data){
completed ++;
// combines the api and microformats data into one profile
if(data){
if(data.fn) {combinedProfile.fn = data.fn};
if(data.n) {combinedProfile.n = data.n};
if(data.nickname) {combinedProfile.nickname = data.nickname};
if(data.photo) {combinedProfile.photo = data.photo};
if(data.note) {combinedProfile.note = data.note};
// for the moment exclude microformat url structures
if(data.url && data.source === 'api') {
if(!combinedProfile.url) {combinedProfile.url = []};
var i = data.url.length;
while (i--) {
appendUrls(data.url[i], combinedProfile.url);
}
};
}
// once we have both bit of data fire callback
if(completed === 2){
callback(combinedProfile);
}
}
// get microformats data
getUFData(identity.userName, identity, options, function(err,data){
whenFetched(err, data);
});
// get api data
getAPIData(identity.userName, options, function(err,data){
whenFetched(err, data);
});
}
|
javascript
|
{
"resource": ""
}
|
q6754
|
whenFetched
|
train
|
function whenFetched(err, data){
completed ++;
// combines the api and microformats data into one profile
if(data){
if(data.fn) {combinedProfile.fn = data.fn};
if(data.n) {combinedProfile.n = data.n};
if(data.nickname) {combinedProfile.nickname = data.nickname};
if(data.photo) {combinedProfile.photo = data.photo};
if(data.note) {combinedProfile.note = data.note};
// for the moment exclude microformat url structures
if(data.url && data.source === 'api') {
if(!combinedProfile.url) {combinedProfile.url = []};
var i = data.url.length;
while (i--) {
appendUrls(data.url[i], combinedProfile.url);
}
};
}
// once we have both bit of data fire callback
if(completed === 2){
callback(combinedProfile);
}
}
|
javascript
|
{
"resource": ""
}
|
q6755
|
appendUrls
|
train
|
function appendUrls(url, arr){
var i = arr.length,
found = false;
while (i--) {
if(arr[i] === url){
found = true;
break;
}
}
if(!found) arr.push(url);
}
|
javascript
|
{
"resource": ""
}
|
q6756
|
getUFData
|
train
|
function getUFData(userName, identity, options, callback) {
var url = 'http://lanyrd.com/people/' + userName,
cache = options.cache,
page = new Page(url, identity, null, options);
page.fetchUrl(function(){
if(page.profile.hCards.length > 0){
page.profile.hCards[0].source = 'microformat';
callback(null, page.profile.hCards[0]);
}else{
callback(null, {});
}
})
}
|
javascript
|
{
"resource": ""
}
|
q6757
|
getAPIData
|
train
|
function getAPIData(userName, options, callback){
if(process.env.LANYRD_API_URL)
{
var url = process.env.LANYRD_API_URL + 'people/' + userName,
cache = options.cache,
startedRequest = new Date(),
requestObj = {
uri: url,
headers: options.httpHeaders
};
// if url is in the cache use that
if(cache && cache.has(url)){
options.logger.info('using cache for lanyrd API data');
callback(null, parse(cache.get(url)));
}else{
// if not get the json from the api url
request(requestObj, function(requestErrors, response, body){
options.logger.info('getting lanyrd API data from url');
if(!requestErrors && response.statusCode === 200){
var data = JSON.parse(body)
var out = parse(data);
// add to cache store
if(cache){
cache.set(url, data);
}
var endedRequest = new Date();
var requestTime = endedRequest.getTime() - startedRequest.getTime();
options.logger.log('made API call to: ' + requestTime + 'ms - ' + url);
callback(null, out);
}else{
callback('error requesting Lanyrd API', {});
}
});
}
}else{
callback('LANYRD_API_URL not found', {});
}
}
|
javascript
|
{
"resource": ""
}
|
q6758
|
record
|
train
|
function record(options) {
return new Promise((res, rej) => {
var micInstance = mic({
rate: "16000",
channels: "1",
debug: true,
exitOnSilence: 3,
});
var micInputStream = micInstance.getAudioStream();
// Encode the file as Opus in an Ogg container, to send to server.
var rate = 16000;
var channels = 1;
var opusEncodeStream = new opus.Encoder(rate, channels);
var oggEncoder = new ogg.Encoder();
micInputStream.pipe(opusEncodeStream).pipe(oggEncoder.stream());
var bufs = [];
oggEncoder.on("data", function(buffer) {
bufs.push(buffer);
});
oggEncoder.on("end", function() {
// Package up encoded recording into buffer to send
// over the network to the API endpoint.
var buffer = Buffer.concat(bufs);
sendRecordingToServer(buffer, options)
.then((results) => {
res(results);
})
.catch((err) => {
console.error("ERR", err);
rej(err);
});
});
micInputStream.on("silence", function() {
// Stop recording at first silence after speaking.
micInstance.stop();
});
micInputStream.on("error", function(err) {
console.error("Error in Input Stream: " + err);
});
micInstance.start();
});
}
|
javascript
|
{
"resource": ""
}
|
q6759
|
JsonSchemaLib
|
train
|
function JsonSchemaLib (config, plugins) {
if (plugins === undefined && Array.isArray(config)) {
plugins = config;
config = undefined;
}
/**
* The configuration for this instance of {@link JsonSchemaLib}.
*
* @type {Config}
*/
this.config = new Config(config);
/**
* The plugins that have been added to this instance of {@link JsonSchemaLib}
*
* @type {object[]}
*/
this.plugins = new PluginManager(plugins);
}
|
javascript
|
{
"resource": ""
}
|
q6760
|
_config
|
train
|
function _config(args) {
var opts = {};
if(args.removeExtraneous){
opts.removeExtraneous = true;
}
if (args.bitbucketAuthUser || args.bitbucketAuthPass) {
opts.bitbucket = {
authUser: args.bitbucketAuthUser,
authPass: args.bitbucketAuthPass
};
} else if (args.githubUser || args.githubOrg || args.githubAuthUser || args.githubAuthPass) {
opts.github = {
user : args.githubUser,
org : args.githubOrg,
authUser: args.githubAuthUser,
authPass: args.githubAuthPass,
useSsh : args.githubUseSsh
};
} else if (args.gitoriousUrl || args.gitoriousProject) {
opts.gitorious = {
url : args.gitoriousUrl,
project: args.gitoriousProject
};
} else if (args.local) {
opts.local = {
dir: process.cwd()
};
}
new Repoman().config(opts, bag.exit);
}
|
javascript
|
{
"resource": ""
}
|
q6761
|
Event
|
train
|
function Event(props, defaults, delay) {
var name;
this.delay = delay || 0;
props = props || {};
for (name in defaults) {
if (defaults.hasOwnProperty(name)) {
if (props.hasOwnProperty(name)) {
this[name] = props[name];
} else {
this[name] = defaults[name];
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6762
|
MetaEvent
|
train
|
function MetaEvent(type, props, delay) {
var defaults = {};
switch (type) {
case MetaEvent.TYPE.SEQUENCE_NUMBER:
defaults.number = 0;
break;
case MetaEvent.TYPE.TEXT:
case MetaEvent.TYPE.COPYRIGHT_NOTICE:
case MetaEvent.TYPE.SEQUENCE_NAME:
case MetaEvent.TYPE.INSTRUMENT_NAME:
case MetaEvent.TYPE.LYRICS:
case MetaEvent.TYPE.MARKER:
case MetaEvent.TYPE.CUE_POINT:
case MetaEvent.TYPE.PROGRAM_NAME:
case MetaEvent.TYPE.DEVICE_NAME:
defaults.text = '';
break;
case MetaEvent.TYPE.MIDI_CHANNEL:
defaults.channel = 0;
break;
case MetaEvent.TYPE.MIDI_PORT:
defaults.port = 0;
break;
case MetaEvent.TYPE.END_OF_TRACK:
break;
case MetaEvent.TYPE.SET_TEMPO:
defaults.tempo = 120;
break;
case MetaEvent.TYPE.SMPTE_OFFSET:
defaults.rate = 24;
defaults.hours = 0;
defaults.minutes = 0;
defaults.seconds = 0;
defaults.frames = 0;
defaults.subframes = 0;
break;
case MetaEvent.TYPE.TIME_SIGNATURE:
defaults.numerator = 4;
defaults.denominator = 4;
defaults.metronome = 24;
defaults.clockSignalsPerBeat = 24;
break;
case MetaEvent.TYPE.KEY_SIGNATURE:
defaults.note = 0;
defaults.major = true;
break;
case MetaEvent.TYPE.SEQUENCER_SPECIFIC:
defaults.data = new buffer.Buffer(0);
break;
default:
throw new error.MIDIInvalidEventError(
'Invalid MetaEvent type "' + type + '"'
);
}
this.type = type;
Event.call(this, props, defaults, delay);
}
|
javascript
|
{
"resource": ""
}
|
q6763
|
SysexEvent
|
train
|
function SysexEvent(type, data, delay) {
this.type = type;
this.data = data;
Event.call(this, {}, {}, delay);
}
|
javascript
|
{
"resource": ""
}
|
q6764
|
ChannelEvent
|
train
|
function ChannelEvent(type, props, channel, delay) {
var defaults = {};
switch (type) {
case ChannelEvent.TYPE.NOTE_OFF:
defaults.note = 0;
defaults.velocity = 127;
break;
case ChannelEvent.TYPE.NOTE_ON:
defaults.note = 0;
defaults.velocity = 127;
break;
case ChannelEvent.TYPE.NOTE_AFTERTOUCH:
defaults.note = 0;
defaults.pressure = 0;
break;
case ChannelEvent.TYPE.CONTROLLER:
defaults.controller = 0;
defaults.value = 127;
break;
case ChannelEvent.TYPE.PROGRAM_CHANGE:
defaults.program = 0;
break;
case ChannelEvent.TYPE.CHANNEL_AFTERTOUCH:
defaults.pressure = 0;
break;
case ChannelEvent.TYPE.PITCH_BEND:
defaults.value = 0;
break;
default:
throw new error.MIDIInvalidEventError(
'Invalid ChannelEvent type "' + type + '"'
);
}
this.type = type;
this.channel = channel || 0;
Event.call(this, props, defaults, delay);
}
|
javascript
|
{
"resource": ""
}
|
q6765
|
Jumio
|
train
|
function Jumio(config) {
var _this = this;
// setup configuration with defaults
this.config = __assign({ version: "1.0.0", identityApiBaseUrl: exports.identityRegionApiUrlMap[config.region], documentApiBaseUrl: exports.documentRegionApiUrlMap[config.region], callbackWhitelist: exports.regionCallbackWhitelistMap[config.region], handleIdentityVerification: function (_result) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); }); }, handleDocumentVerification: function (_result) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); }); }, log: ts_log_1.dummyLogger }, config);
// keep a shorter reference to the logger
this.log = this.config.log;
// build company-specific user agent
var userAgent = this.config.company + "/" + this.config.version;
// configure axios for making API requests to the identity verification api
this.identityApi = axios_1.default.create({
baseURL: this.config.identityApiBaseUrl,
auth: {
username: this.config.apiToken,
password: this.config.apiSecret
},
headers: {
"User-Agent": userAgent
}
});
// configure axios for making API requests to the document verification api
this.documentApi = axios_1.default.create({
baseURL: this.config.documentApiBaseUrl,
auth: {
username: this.config.apiToken,
password: this.config.apiSecret
},
headers: {
"User-Agent": userAgent
}
});
// log initialized
this.log.info({
identityApiBaseUrl: this.config.identityApiBaseUrl,
documentApiBaseUrl: this.config.documentApiBaseUrl,
apiToken: this.config.apiToken,
apiSecret: new Array(this.config.apiSecret.length + 1).join("x"),
userAgent: userAgent
}, "initialized");
}
|
javascript
|
{
"resource": ""
}
|
q6766
|
isTypedArray
|
train
|
function isTypedArray (obj) {
if (typeof obj === 'object') {
for (var i = 0; i < supportedDataTypes.length; i++) {
if (obj instanceof supportedDataTypes[i]) {
return true;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6767
|
getSupportedDataTypes
|
train
|
function getSupportedDataTypes () {
var types = [];
// NOTE: More frequently-used types come first, to improve lookup speed
if (typeof Uint8Array === 'function') {
types.push(Uint8Array);
}
if (typeof Uint16Array === 'function') {
types.push(Uint16Array);
}
if (typeof ArrayBuffer === 'function') {
types.push(ArrayBuffer);
}
if (typeof Uint32Array === 'function') {
types.push(Uint32Array);
}
if (typeof Int8Array === 'function') {
types.push(Int8Array);
}
if (typeof Int16Array === 'function') {
types.push(Int16Array);
}
if (typeof Int32Array === 'function') {
types.push(Int32Array);
}
if (typeof Uint8ClampedArray === 'function') {
types.push(Uint8ClampedArray);
}
if (typeof Float32Array === 'function') {
types.push(Float32Array);
}
if (typeof Float64Array === 'function') {
types.push(Float64Array);
}
if (typeof DataView === 'function') {
types.push(DataView);
}
return types;
}
|
javascript
|
{
"resource": ""
}
|
q6768
|
Bitbucket
|
train
|
function Bitbucket(user, pass) {
this.user = user;
this.client = bitbucket.createClient({ username: user, password: pass });
}
|
javascript
|
{
"resource": ""
}
|
q6769
|
parseChunk
|
train
|
function parseChunk(expected, cursor) {
var type, length;
type = cursor.toString('ascii', 4);
length = cursor.readUInt32BE();
if (type !== expected) {
throw new error.MIDIParserError(
type,
expected,
cursor.tell()
);
}
return cursor.slice(length);
}
|
javascript
|
{
"resource": ""
}
|
q6770
|
unbind
|
train
|
function unbind(unbindObj) {
if ("*" !== defaultAppName) {
unbindObj.appName = unbindObj.appName || defaultAppName;
}
return evUtil.unbind({
unbindObj: unbindObj,
attrName: attrName,
loggerName: appName,
lstnrs: lstnrs
});
}
|
javascript
|
{
"resource": ""
}
|
q6771
|
hasFired
|
train
|
function hasFired(app, evName) {
if ("undefined" === typeof evName) {
evName = app;
app = defaultAppName;
}
return evUtil.hasFired(fired, app, evName);
}
|
javascript
|
{
"resource": ""
}
|
q6772
|
_storeEventData
|
train
|
function _storeEventData(triggerData) {
evUtil.storeEventData({
triggerData: triggerData,
eventBufferLimit: eventBufferLimit,
attrName: attrName,
fired: fired,
index: indexer
});
}
|
javascript
|
{
"resource": ""
}
|
q6773
|
singleSource
|
train
|
function singleSource(graph, source) {
if (!isGraph(graph))
throw new Error('graphology-shortest-path: invalid graphology instance.');
if (arguments.length < 2)
throw new Error('graphology-shortest-path: invalid number of arguments. Expecting at least 2.');
if (!graph.hasNode(source))
throw new Error('graphology-shortest-path: the "' + source + '" source node does not exist in the given graph.');
source = '' + source;
var nextLevel = {},
paths = {},
currentLevel,
neighbors,
v,
w,
i,
l;
nextLevel[source] = true;
paths[source] = [source];
while (Object.keys(nextLevel).length) {
currentLevel = nextLevel;
nextLevel = {};
for (v in currentLevel) {
neighbors = graph.outNeighbors(v);
neighbors.push.apply(neighbors, graph.undirectedNeighbors(v));
for (i = 0, l = neighbors.length; i < l; i++) {
w = neighbors[i];
if (!paths[w]) {
paths[w] = paths[v].concat(w);
nextLevel[w] = true;
}
}
}
}
return paths;
}
|
javascript
|
{
"resource": ""
}
|
q6774
|
resolveUrl
|
train
|
function resolveUrl (from, to) {
if (typeof URL === 'function') {
// Use the new WHATWG URL API
return new URL(to, from).href;
}
else {
// Use the legacy url API
return legacyURL.resolve(from, to);
}
}
|
javascript
|
{
"resource": ""
}
|
q6775
|
abstractDijkstraMultisource
|
train
|
function abstractDijkstraMultisource(
graph,
sources,
weightAttribute,
cutoff,
target,
paths
) {
if (!isGraph(graph))
throw new Error('graphology-shortest-path/dijkstra: invalid graphology instance.');
if (target && !graph.hasNode(target))
throw new Error('graphology-shortest-path/dijkstra: the "' + target + '" target node does not exist in the given graph.');
weightAttribute = weightAttribute || DEFAULTS.weightAttribute;
// Building necessary functions
var getWeight = function(edge) {
return graph.getEdgeAttribute(edge, weightAttribute);
};
var distances = {},
seen = {},
fringe = new Heap(DIJKSTRA_HEAP_COMPARATOR);
var count = 0,
edges,
item,
cost,
v,
u,
e,
d,
i,
j,
l,
m;
for (i = 0, l = sources.length; i < l; i++) {
v = sources[i];
seen[v] = 0;
fringe.push([0, count++, v]);
if (paths)
paths[v] = [v];
}
while (fringe.size) {
item = fringe.pop();
d = item[0];
v = item[2];
if (v in distances)
continue;
distances[v] = d;
if (v === target)
break;
edges = graph
.undirectedEdges(v)
.concat(graph.outEdges(v));
for (j = 0, m = edges.length; j < m; j++) {
e = edges[j];
u = graph.opposite(v, e);
cost = getWeight(e) + distances[v];
if (cutoff && cost > cutoff)
continue;
if (u in distances && cost < distances[u]) {
throw Error('graphology-shortest-path/dijkstra: contradictory paths found. Do some of your edges have a negative weight?');
}
else if (!(u in seen) || cost < seen[u]) {
seen[u] = cost;
fringe.push([cost, count++, u]);
if (paths)
paths[u] = paths[v].concat(u);
}
}
}
return distances;
}
|
javascript
|
{
"resource": ""
}
|
q6776
|
singleSourceDijkstra
|
train
|
function singleSourceDijkstra(graph, source, weightAttribute) {
var paths = {};
abstractDijkstraMultisource(
graph,
[source],
weightAttribute,
0,
null,
paths
);
return paths;
}
|
javascript
|
{
"resource": ""
}
|
q6777
|
PluginHelper
|
train
|
function PluginHelper (plugins, schema) {
validatePlugins(plugins);
plugins = plugins || [];
// Clone the array of plugins, and sort by priority
var pluginHelper = plugins.slice().sort(sortByPriority);
/**
* Internal stuff. Use at your own risk!
*
* @private
*/
pluginHelper[__internal] = {
/**
* A reference to the {@link Schema} object
*/
schema: schema,
};
// Return an array that "inherits" from PluginHelper
return assign(pluginHelper, PluginHelper.prototype);
}
|
javascript
|
{
"resource": ""
}
|
q6778
|
encodeChunk
|
train
|
function encodeChunk(type, data) {
var cursor = new BufferCursor(new buffer.Buffer(
buffer.Buffer.byteLength(type) + 4 + data.length
));
cursor.write(type);
cursor.writeUInt32BE(data.length);
cursor.copy(data);
return cursor.buffer;
}
|
javascript
|
{
"resource": ""
}
|
q6779
|
train
|
function( value ) {
var lines = TLE.trim( value + '' ).split( /\r?\n/g )
var line, checksum
// Line 0
if (lines.length === 3) {
this.name = TLE.trim( lines.shift() )
}
// Line 1
line = lines.shift()
checksum = TLE.check( line )
if( checksum != line.substring( 68, 69 ) ) {
throw new Error(
'Line 1 checksum mismatch: ' + checksum + ' != ' +
line.substring( 68, 69 ) + ': ' + line
)
}
this.number = TLE.parseFloat( line.substring( 2, 7 ) )
this.class = TLE.trim( line.substring( 7, 9 ) )
this.id = TLE.trim( line.substring( 9, 18 ) )
this.date = TLE.parseDate( line.substring( 18, 33 ) )
this.fdmm = TLE.parseFloat( line.substring( 33, 44 ) )
this.sdmm = TLE.parseFloat( line.substring( 44, 53 ) )
this.drag = TLE.parseDrag( line.substring( 53, 62 ) )
this.ephemeris = TLE.parseFloat( line.substring( 62, 64 ) )
this.esn = TLE.parseFloat( line.substring( 64, 68 ) )
// Line 2
line = lines.shift()
checksum = TLE.check( line )
if( checksum != line.substring( 68, 69 ) ) {
throw new Error(
'Line 2 checksum mismatch: ' + checksum + ' != ' +
line.substring( 68, 69 ) + ': ' + line
)
}
this.inclination = TLE.parseFloat( line.substring( 8, 17 ) )
this.ascension = TLE.parseFloat( line.substring( 17, 26 ) )
this.eccentricity = TLE.parseFloat( '0.' + line.substring( 26, 34 ) )
this.perigee = TLE.parseFloat( line.substring( 34, 43 ) )
this.anomaly = TLE.parseFloat( line.substring( 43, 52 ) )
this.motion = TLE.parseFloat( line.substring( 52, 64 ) )
this.revolution = TLE.parseFloat( line.substring( 64, 68 ) )
return this
}
|
javascript
|
{
"resource": ""
}
|
|
q6780
|
callSyncPlugin
|
train
|
function callSyncPlugin (pluginHelper, methodName, args) {
var plugins = pluginHelper.filter(filterByMethod(methodName));
args.schema = pluginHelper[__internal].schema;
args.config = args.schema.config;
return callNextPlugin(plugins, methodName, args);
}
|
javascript
|
{
"resource": ""
}
|
q6781
|
load
|
train
|
function load(dirPath) {
findFiles(dirPath, function(filePath){
collection.push( require(filePath) );
})
function findFiles(dirPath, callback){
fs.readdir(dirPath, function(err, files) {
files.forEach(function(file){
fs.stat(dirPath + '/' + file, function(err, stats) {
if(stats.isFile()) {
callback(dirPath + '/' + file);
}
if(stats.isDirectory()) {
getDirectoryFiles(dirPath + '/' + file, callback);
}
});
});
});
}
}
|
javascript
|
{
"resource": ""
}
|
q6782
|
add
|
train
|
function add(interface){
var i = arr.collection,
found = false;
while (i--) {
if(interface.name === collection[i].name){
found = true;
}
}
if(!found){ collection.push( interface ) };
}
|
javascript
|
{
"resource": ""
}
|
q6783
|
parseTrack
|
train
|
function parseTrack(cursor) {
var chunk, events = [],
result, runningStatus = null;
chunk = parseChunk('MTrk', cursor);
while (!chunk.eof()) {
result = parseEvent(chunk, runningStatus);
runningStatus = result.runningStatus;
events.push(result.event);
}
return new Track(events);
}
|
javascript
|
{
"resource": ""
}
|
q6784
|
train
|
function(request, options){
if(typeof options == "undefined") options = {}; // define options if not yet defined
options.relative_path_root = relative_path_root; // overwrite user defined rel path root - TODO - make this a private property
return require_function(request, options);
}
|
javascript
|
{
"resource": ""
}
|
|
q6785
|
stripBOM
|
train
|
function stripBOM (str) {
var bom = str.charCodeAt(0);
// Check for the UTF-16 byte order mark (0xFEFF or 0xFFFE)
if (bom === 0xFEFF || bom === 0xFFFE) {
return str.slice(1);
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q6786
|
parseFile
|
train
|
function parseFile (args) {
var file = args.file;
var next = args.next;
try {
// Optimistically try to parse the file as JSON.
return JSON.parse(file.data);
}
catch (error) {
if (isJsonFile(file)) {
// This is a JSON file, but its contents are invalid
throw error;
}
else {
// This probably isn't a JSON file, so call the next parser plugin
next();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6787
|
isJsonFile
|
train
|
function isJsonFile (file) {
return file.data && // The file has data
(typeof file.data === 'string') && // and it's a string
(
mimeTypePattern.test(file.mimeType) || // and it has a JSON MIME type
extensionPattern.test(file.url) // or at least a .json file extension
);
}
|
javascript
|
{
"resource": ""
}
|
q6788
|
ExportRequiredTemplatesMiddleware
|
train
|
function ExportRequiredTemplatesMiddleware (context)
{
var options = context.options.requiredTemplates;
var path = require ('path');
/**
* Paths of the required templates.
* @type {string[]}
*/
var paths = [];
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
// Do nothing
};
this.trace = function (module)
{
scan (module.head, module.headPath);
module.bodies.forEach (function (path, i)
{
scan (path, module.bodyPaths[i]);
});
};
this.build = function (targetScript)
{
/* jshint unused: vars */
// Export file paths.
context.grunt.config (options.exportToConfigProperty, paths);
};
//--------------------------------------------------------------------------------------------------------------------
// PRIVATE
//--------------------------------------------------------------------------------------------------------------------
/**
* Extracts file paths from embedded comment references to templates and appends them to `paths`.
* @param {string} sourceCode
* @param {string} filePath
*/
function scan (sourceCode, filePath)
{
/* jshint -W083 */
var match;
while ((match = MATCH_DIRECTIVE.exec (sourceCode))) {
match[1].split (',').forEach (function (s)
{
var url = s.match (/(["'])(.*?)\1/)[2];
paths.push (path.normalize (path.dirname (filePath) + '/' + url));
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6789
|
findFile
|
train
|
function findFile (schema, url) {
if (schema.files.length === 0) {
return null;
}
if (url instanceof File) {
// Short-circuit behavior for File obejcts
return findByURL(schema.files, url.url);
}
// Try to find an exact URL match
var file = findByURL(schema.files, url);
if (!file) {
// Resolve the URL and see if we can find a match
var absoluteURL = schema.plugins.resolveURL({ from: schema.rootURL, to: url });
file = findByURL(schema.files, absoluteURL);
}
return file;
}
|
javascript
|
{
"resource": ""
}
|
q6790
|
findByURL
|
train
|
function findByURL (files, url) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (file.url === url) {
return file;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q6791
|
train
|
function (num) {
for (var ext = '', i = 0; i < 4; i++) {
ext = String.fromCharCode(num & 0xFF) + ext
num >>= 8
}
return ext
}
|
javascript
|
{
"resource": ""
}
|
|
q6792
|
train
|
function (str) {
while (str.length < 4) str += ' '
for (var num = 0, i = 0; i < 4; i++) {
num = (num << 8) + str.charCodeAt(i)
}
return num
}
|
javascript
|
{
"resource": ""
}
|
|
q6793
|
DRS
|
train
|
function DRS (file) {
if (!(this instanceof DRS)) return new DRS(file)
this.tables = []
this.isSWGB = null
if (typeof file === 'undefined') {
file = {}
}
if (typeof file === 'string') {
if (typeof FsSource !== 'function') {
throw new Error('Cannot instantiate with a string filename in the browser')
}
this.source = new FsSource(file)
} else if (typeof Blob !== 'undefined' && file instanceof Blob) { // eslint-disable-line no-undef
this.source = new BlobSource(file)
} else {
if (typeof file !== 'object') {
throw new TypeError('Expected a file path string or an options object, got ' + typeof file)
}
this.isSWGB = file.hasOwnProperty('isSWGB') ? file.isSWGB : false
this.copyright = file.hasOwnProperty('copyright')
? file.copyright
: (this.isSWGB ? COPYRIGHT_SWGB : COPYRIGHT_AOE)
this.fileVersion = file.hasOwnProperty('fileVersion') ? file.fileVersion : '1.00'
this.fileType = file.hasOwnProperty('fileType') ? file.fileType : 'tribe\0\0\0\0\0\0\0'
}
}
|
javascript
|
{
"resource": ""
}
|
q6794
|
ExportSourceCodePathsMiddleware
|
train
|
function ExportSourceCodePathsMiddleware (context)
{
var options = context.options.sourcePaths;
/**
* Paths of all the required files (excluding standalone scripts) in the correct loading order.
* @type {string[]}
*/
var tracedPaths = [];
//--------------------------------------------------------------------------------------------------------------------
// PUBLIC API
//--------------------------------------------------------------------------------------------------------------------
this.analyze = function (filesArray)
{
/* jshint unused: vars */
// Do nothing
};
this.trace = function (module)
{
tracedPaths.push (module.headPath);
arrayAppend (tracedPaths, module.bodyPaths);
};
this.build = function (targetScript)
{
/* jshint unused: vars */
var scripts = [];
// Include paths of forced-include scripts.
if (context.standaloneScripts.length)
arrayAppend (scripts, context.standaloneScripts.map (function (e)
{
return e.path;
}));
// Include all module files.
arrayAppend (scripts, tracedPaths);
// Export.
context.grunt.config (options.exportToConfigProperty, scripts);
};
}
|
javascript
|
{
"resource": ""
}
|
q6795
|
Driver
|
train
|
function Driver(native) {
var outputs = [], inputs = [], length, i;
EventEmitter.call(this);
this.native = native;
length = native.outputs.size;
for (i = 0; i < length; i += 1) {
outputs[i] = new Output(native.outputs.get(i));
}
length = native.inputs.size;
for (i = 0; i < length; i += 1) {
inputs[i] = new Input(native.inputs.get(i));
}
this.outputs = outputs;
this.output = null;
this.inputs = inputs;
this.input = null;
native.onconnect = function (event) {
var port = event.port;
if (port.type === 'input') {
port = new Input(port);
this.inputs.push(port);
} else {
port = new Output(port);
this.outputs.push(port);
}
this.emit('connect', port);
}.bind(this);
native.ondisconnect = function (event) {
var port = event.port;
if (port.type === 'input') {
port = new Input(port);
this.inputs = this.inputs.filter(function (input) {
return (input.id !== port.id);
});
} else {
port = new Output(port);
this.outputs = this.outputs.filter(function (output) {
return (output.id !== port.id);
});
}
this.emit('disconnect', port);
}.bind(this);
}
|
javascript
|
{
"resource": ""
}
|
q6796
|
Context
|
train
|
function Context (grunt, task, defaultOptions)
{
this.grunt = grunt;
this.options = extend ({}, defaultOptions, task.options ());
switch (this.options.buildMode) {
case 'release':
this.options.debugBuild.enabled = false;
this.options.releaseBuild.enabled = true;
break;
case 'debug':
this.options.debugBuild.enabled = true;
this.options.releaseBuild.enabled = false;
}
if (task.flags.debug !== undefined || grunt.option ('build') === 'debug') {
this.options.debugBuild.enabled = true;
this.options.releaseBuild.enabled = false;
}
this.verbose = grunt.option ('verbose');
// Clone the external modules and use it as a starting point.
this.modules = extend ({}, this._setupExternalModules ());
// Reset tracer.
this.loaded = {};
this.outputtedFiles = {};
this.filesRefCount = {};
// Reset the scripts list to a clone of the `require` option or to an empty list.
this.standaloneScripts = (this.options.require || []).slice ();
this.shared = {};
this._events = {};
}
|
javascript
|
{
"resource": ""
}
|
q6797
|
train
|
function (eventName, handler)
{
if (!this._events[eventName])
this._events[eventName] = [];
this._events[eventName].push (handler);
}
|
javascript
|
{
"resource": ""
}
|
|
q6798
|
train
|
function (eventName, args)
{
var e = this._events[eventName];
if (e) {
args = args || [];
e.forEach (function (handler)
{
handler.apply (this, args);
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q6799
|
train
|
function ()
{
/** @type {Object.<string, ModuleDef>} */
var modules = {};
((typeof this.options.externalModules === 'string' ?
[this.options.externalModules] : this.options.externalModules
) || []).
concat (this.options.builtinModules).
forEach (function (moduleName)
{
// Ignore redundant names.
if (!modules[moduleName]) {
/** @type {ModuleDef} */
var module = modules[moduleName] = new ModuleDef (moduleName);
module.external = true;
}
});
return modules;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.