_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q2600
|
train
|
function (key, n) {
var int;
var numeral;
try {
int = key.getInterval(n);
} catch (err) {
try {
int = key.getInterval(n.clean());
} catch (err2) {
int = key.getInterval(n.toggleAccidental());
}
}
// Although dim7, for example, is
|
javascript
|
{
"resource": ""
}
|
|
q2601
|
train
|
function (numeral) {
var matches = numeral.match(/([b#]?)([iIvV]+)/);
var halfSteps = interval.parse(_.indexOf(romanNumeral,
|
javascript
|
{
"resource": ""
}
|
|
q2602
|
train
|
function (numeral, quality) {
// Roman numeral representing chord
this.numeral = numeral;
// Chord quality: M, m, x, o, ø, s
this.quality = quality;
if (!_.contains(['M', 'm', 'x', 'o', 'ø',
|
javascript
|
{
"resource": ""
}
|
|
q2603
|
train
|
function (key, ch) {
key = note.create(key || 'C');
ch
|
javascript
|
{
"resource": ""
}
|
|
q2604
|
train
|
function (mehegan, cache) {
if (mehegan instanceof Mehegan) return mehegan;
// If no cache is provided, return string as Mehegan symbol
if (!cache)
|
javascript
|
{
"resource": ""
}
|
|
q2605
|
train
|
function (interval) {
var quality;
var number;
if (interval instanceof Interval) return interval;
quality = interval.replace(/\d/g, ''); // Remove digits
number = parseInt(interval.replace(/\D/g, ''), 10); // Remove non-digits
if (!quality) { // No
|
javascript
|
{
"resource": ""
}
|
|
q2606
|
train
|
function (scale, note) {
return _.findIndex(scale.scale,
|
javascript
|
{
"resource": ""
}
|
|
q2607
|
train
|
function (chord) {
var noteRegex = '[A-Ga-g][#b]{0,2}';
var root = chord.match(new RegExp('^' + noteRegex))[0];
var bass = null;
var symbol;
root = note.create(root);
// Strip note, strip spaces, strip bass
symbol = chord.replace(/[\s]/g, '')
.replace(new RegExp('^' + noteRegex), '')
|
javascript
|
{
"resource": ""
}
|
|
q2608
|
train
|
function (interval) {
return _.find(notes, function (n) {
return
|
javascript
|
{
"resource": ""
}
|
|
q2609
|
train
|
function (root, bass, intervals) {
var chord = _.chain(intervals)
.map(function (quality, number) {
var int;
if (quality) {
// #9 is stored as b10, so special case this
if (number === 10 && quality === 'm') {
int = interval.create(9, 'aug');
}
else {
int = interval.create(number, quality);
|
javascript
|
{
"resource": ""
}
|
|
q2610
|
train
|
function (root, symbol, bass) {
var name = root.name + symbol;
var octave = bass ? bass.octave : root.octave;
|
javascript
|
{
"resource": ""
}
|
|
q2611
|
train
|
function (scales, chord) {
// Exclude scales with a particular interval
var exclude = function (int) {
scales = _.filter(scales, function (scale) {
return !scale.hasInterval(int);
});
};
// Add a scale at a particular index
var include = function (index, scaleId) {
scales.splice(index, 0, scale.create(chord.root, scaleId));
};
if (_.includes(['m', 'm6', 'm7', 'm9', 'm11', 'm13'], chord.formattedSymbol)) {
exclude('M3');
}
if (_.includes(['7', '9', '11', '13', 'm7', 'm9', 'm11', 'm13'], chord.formattedSymbol)) {
exclude('M7');
}
|
javascript
|
{
"resource": ""
}
|
|
q2612
|
train
|
function (index, scaleId) {
scales.splice(index,
|
javascript
|
{
"resource": ""
}
|
|
q2613
|
train
|
function (obj, octave) {
var lastNote = obj.chord[0];
obj.chord = _.map(obj.chord, function (n) {
// Every time a note is "lower" than the last note, we're in a new octave
if (n.lowerThan(lastNote)) octave += 1;
// As a side-effect, update the octaves for root and bass
if (n.enharmonic(obj.root)) {
obj.root = obj.root.inOctave(octave);
|
javascript
|
{
"resource": ""
}
|
|
q2614
|
train
|
function (num, totalBytes) {
var numBytes = Math.floor(Math.log(num) / Math.log(0xff)) + 1;
var buffer = new Buffer(totalBytes);
|
javascript
|
{
"resource": ""
}
|
|
q2615
|
train
|
function (format, numTracks) {
var chunklen = padNumber(6, 4); // MIDI header is always 6 bytes long
var ntracks = padNumber(numTracks, 2);
var tickdiv = padNumber(ticksPerBeat, 2);
format = padNumber(format, 2); // Usually format 1 MIDI
|
javascript
|
{
"resource": ""
}
|
|
q2616
|
train
|
function (settings) {
var tempo = 60e6 / settings.tempo; // Microseconds per beat
var setTempo = Buffer.concat([new Buffer([0, 0xFF, 0x51, 0x03]), padNumber(tempo, 3)]);
var length
|
javascript
|
{
"resource": ""
}
|
|
q2617
|
train
|
function (deltaTime, on, channel, note, velocity) {
var status = on ? 0x90 : 0x80;
status += channel;
deltaTime = makeVLQ(deltaTime);
|
javascript
|
{
"resource": ""
}
|
|
q2618
|
train
|
function (deltaTime, on, firstChannel, chord, velocity) {
var arr = [];
// Make note event for first note after appropriate time
arr.push(makeNoteEvent(deltaTime, on, firstChannel, noteValue(_.first(chord)), velocity));
// Make note event for rest of the notes
_.each(_.rest(chord),
|
javascript
|
{
"resource": ""
}
|
|
q2619
|
train
|
function (duration, settings) {
// If there's no swing ratio, assume straight eighths
|
javascript
|
{
"resource": ""
}
|
|
q2620
|
train
|
function (notes, settings) {
var restBuffer = 0;
var events = _.reduce(notes, function (arr, obj) {
var time = noteLength(obj.duration, settings);
if (obj.note) {
arr.push(makeNoteEvent(restBuffer, true,
|
javascript
|
{
"resource": ""
}
|
|
q2621
|
train
|
function (chords, settings) {
var events = _.reduce(chords, function (arr, obj) {
var time = noteLength(obj.duration, settings);
var chord = obj.chord.inOctave(settings.chordOctave).chord;
|
javascript
|
{
"resource": ""
}
|
|
q2622
|
train
|
function (notes, settings) {
var noteEvents = makeNoteEvents(notes, settings);
var setPatch = makePatchEvent(0, settings.melodyPatch);
var length = setPatch.length + noteEvents.length +
|
javascript
|
{
"resource": ""
}
|
|
q2623
|
train
|
function (chords, settings) {
var chordEvents = makeChordEvents(chords, settings);
// Set all channels
var setPatches = _.reduce(_.range(0xf), function (buffer, channel) {
return Buffer.concat([buffer,
|
javascript
|
{
"resource": ""
}
|
|
q2624
|
getAxesPosition
|
train
|
function getAxesPosition(axes, buttons) {
if (axes.length === 10) {
return Math.round(axes[9] / (2 / 7) + 3.5);
}
const [right, left, down, up] = [...buttons].reverse();
const buttonValues = [up, right, down, left]
|
javascript
|
{
"resource": ""
}
|
q2625
|
Unswitch
|
train
|
function Unswitch(settings) {
const buttonState = {};
let axesPosition = 8;
for (let i = buttonMappings.length - 1; i >= 0; i -= 1) {
buttonState[buttonMappings[i]] = { pressed: false };
}
this.update = () => {
const gamepads = navigator.getGamepads();
for (let i = Object.keys(gamepads).length - 1; i >= 0; i -= 1) {
if (gamepads[i] && gamepads[i].id && gamepads[i].id.indexOf(settings.side) !== -1) {
this.observe(gamepads[i]);
break;
}
}
};
this.observe = (pad) => {
const { buttons, axes } = pad;
for (let j = buttonMappings.length - 1; j >= 0; j -= 1) {
const button = buttonMappings[j];
if (buttonState[button].pressed !== buttons[j].pressed) {
buttonState[button].pressed
|
javascript
|
{
"resource": ""
}
|
q2626
|
createHandler
|
train
|
function createHandler(to, except, pathFunc, protocol) {
return function(req, res, next) {
var host = req.hostname || '';
var url = req.url;
if (host in except) {
next();
} else {
|
javascript
|
{
"resource": ""
}
|
q2627
|
CDNUp
|
train
|
function CDNUp(bucket, options) {
options = options || {};
this.sharding = !!options.sharding;
this.urls = arrayify(options.url || options.urls);
this.mime = options.mime || {};
this.check = options.check;
this.bucket = bucket;
|
javascript
|
{
"resource": ""
}
|
q2628
|
arrayify
|
train
|
function arrayify(urls) {
var tmp = Array.isArray(urls) ? urls : [urls];
|
javascript
|
{
"resource": ""
}
|
q2629
|
generateMakefile
|
train
|
function generateMakefile(testFiles, targetPath, callback) {
var template = new templates.Template('Makefile.magic');
var fullPath = path.join(targetPath, 'Makefile');
var context = {
test_files: testFiles.join(' \\\n ')
};
if (path.existsSync(fullPath)) {
|
javascript
|
{
"resource": ""
}
|
q2630
|
checkSavedData
|
train
|
function checkSavedData(dbName, objStore, data) {
const keyValueContainer = Object.prototype.isPrototypeOf.call(skladKeyValueContainer, data);
const value = keyValueContainer ? data.value : data;
const objStoreMeta = objStoresMeta.get(dbName).get(objStore.name);
let key = keyValueContainer ? data.key : undefined;
const keyPath = objStore.keyPath || objStoreMeta.keyPath;
const autoIncrement = objStore.autoIncrement || objStoreMeta.autoIncrement;
if (keyPath === null) {
if (!autoIncrement && key === undefined) {
key = uuid();
}
} else {
|
javascript
|
{
"resource": ""
}
|
q2631
|
checkContainingStores
|
train
|
function checkContainingStores(objStoreNames) {
return objStoreNames.every(function (storeName) {
|
javascript
|
{
"resource": ""
}
|
q2632
|
getObjStoresMeta
|
train
|
function getObjStoresMeta(db, objStoreNames) {
const dbMeta = objStoresMeta.get(db.name);
const promises = [];
objStoreNames.forEach(objStoreName => {
if (dbMeta.has(objStoreName)) {
return;
}
const promise = new Promise(resolve => {
const transaction = db.transaction([objStoreName], TRANSACTION_READWRITE);
transaction.oncomplete = resolve;
transaction.onabort = resolve;
const objStore = transaction.objectStore(objStoreName);
if (objStore.autoIncrement !== undefined) {
dbMeta.set(objStoreName, {
autoIncrement: objStore.autoIncrement,
keyPath: objStore.keyPath
});
return;
}
let autoIncrement;
if (objStore.keyPath !== null) {
// if key path is defined it's possible to insert only objects
// but if key generator (autoIncrement) is not defined the inserted objects
// must contain field(s) described in keyPath value otherwise IDBObjectStore.add op fails
// so if we run ODBObjectStore.add with an empty object and it fails, this means that
// autoIncrement property was false. Otherwise - true
// if key path is array autoIncrement property can't be true
if (Array.isArray(objStore.keyPath)) {
autoIncrement = false;
} else {
try {
objStore.add({});
autoIncrement = true;
} catch (ex) {
autoIncrement = false;
|
javascript
|
{
"resource": ""
}
|
q2633
|
createProgram
|
train
|
function createProgram(
gl, shaders, opt_attribs, opt_locations, opt_errorCallback) {
var errFn = opt_errorCallback || error;
var program = gl.createProgram();
shaders.forEach(function(shader) {
gl.attachShader(program, shader);
});
if (opt_attribs) {
opt_attribs.forEach(function(attrib, ndx) {
gl.bindAttribLocation(
program,
opt_locations ? opt_locations[ndx] : ndx,
attrib);
});
}
gl.linkProgram(program);
// Check the link status
|
javascript
|
{
"resource": ""
}
|
q2634
|
getBindPointForSamplerType
|
train
|
function getBindPointForSamplerType(gl, type) {
if (type === gl.SAMPLER_2D) return gl.TEXTURE_2D;
|
javascript
|
{
"resource": ""
}
|
q2635
|
getExtensionWithKnownPrefixes
|
train
|
function getExtensionWithKnownPrefixes(gl, name) {
for (var ii = 0; ii < browserPrefixes.length; ++ii) {
var
|
javascript
|
{
"resource": ""
}
|
q2636
|
resizeCanvasToDisplaySize
|
train
|
function resizeCanvasToDisplaySize(canvas, multiplier) {
multiplier = multiplier || 1;
var width = canvas.clientWidth * multiplier | 0;
var height = canvas.clientHeight * multiplier | 0;
if (canvas.width !== width
|
javascript
|
{
"resource": ""
}
|
q2637
|
getNumElementsFromNonIndexedArrays
|
train
|
function getNumElementsFromNonIndexedArrays(arrays) {
var key = Object.keys(arrays)[0];
var array =
|
javascript
|
{
"resource": ""
}
|
q2638
|
createBuffersFromArrays
|
train
|
function createBuffersFromArrays(gl, arrays) {
var buffers = { };
Object.keys(arrays).forEach(function(key) {
var type = key === "indices" ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER;
var array = makeTypedArray(arrays[key], name);
buffers[key] = createBufferFromTypedArray(gl, array, type);
});
// hrm
if (arrays.indices) {
|
javascript
|
{
"resource": ""
}
|
q2639
|
drawBufferInfo
|
train
|
function drawBufferInfo(gl, bufferInfo, primitiveType, count, offset) {
var indices = bufferInfo.indices;
primitiveType = primitiveType === undefined ? gl.TRIANGLES : primitiveType;
var numElements =
|
javascript
|
{
"resource": ""
}
|
q2640
|
getLogger
|
train
|
function getLogger(name) {
name = name || '';
if (!name)
|
javascript
|
{
"resource": ""
}
|
q2641
|
train
|
function(filename){
// resolve by symlink if possible
for (var from in this.symlinks)
if (filename.indexOf(from) === 0 && (filename === from || filename[from.length] === '/'))
return this.symlinks[from] +
|
javascript
|
{
"resource": ""
}
|
|
q2642
|
train
|
function(fileRef){
var filename;
var file;
if (fileRef instanceof File)
{
file = fileRef;
filename = file.filename;
}
else
{
filename = abspath(this.baseURI, fileRef);
file = this.map[filename];
if (!file)
{
this.flow.warn({
file: filename,
message: 'File `' + fileRef + '` not found in map'
});
return;
}
}
// remove links
for (var i = file.linkTo.length, linkTo; linkTo = file.linkTo[i]; i--)
file.unlink(linkTo);
|
javascript
|
{
"resource": ""
}
|
|
q2643
|
train
|
function(data, options) {
var configs = [];
if (_.isArray(data)) {
data.forEach(function(block) {
configs.push(new BlockConfig(block.name, block, options));
|
javascript
|
{
"resource": ""
}
|
|
q2644
|
ConsoleHandler
|
train
|
function ConsoleHandler(level, grouping, collapsed) {
grouping = typeof grouping !== 'undefined' ? grouping : true;
collapsed = typeof collapsed !== 'undefined' ? collapsed : false;
|
javascript
|
{
"resource": ""
}
|
q2645
|
ScrapinodeError
|
train
|
function ScrapinodeError(message){
Error.call(this);
Error.captureStackTrace(this,arguments.callee);
|
javascript
|
{
"resource": ""
}
|
q2646
|
FileHandler
|
train
|
function FileHandler(filename, mode, encoding, delay) {
mode = mode || 'a';
encoding = typeof encoding !== 'undefined' ? encoding : 'utf8';
delay = typeof delay !== 'undefined' ? delay : false;
/**
* @private
* @type {string}
*/
this._filename = filename;
/**
* @private
* @type {string}
*/
this._mode = mode;
/**
|
javascript
|
{
"resource": ""
}
|
q2647
|
RotatingFileHandler
|
train
|
function RotatingFileHandler(filename, mode, maxBytes, backupCount,
encoding, delay) {
mode = mode || 'a';
maxBytes = typeof maxBytes !== 'undefined' ? maxBytes : 0;
backupCount = typeof backupCount !== 'undefined' ? backupCount : 0;
encoding = typeof encoding !== 'undefined' ? encoding : 'utf8';
delay = typeof delay !== 'undefined' ? delay : false;
if (maxBytes > 0) {
mode = 'a';
}
FileHandler.call(this, filename,
|
javascript
|
{
"resource": ""
}
|
q2648
|
accepts
|
train
|
function accepts(func, validator, message) {
message = messageBuilder(message || 'vet/utils/accepts error!');
return function wrapper(){
|
javascript
|
{
"resource": ""
}
|
q2649
|
toRepoUrl
|
train
|
function toRepoUrl(url) {
if (url.startsWith('git@')) {
if (argv.useSSH) {
return url;
}
// have an ssh url need an http url
const m = url.match(/(https?:\/\/([^/]+)\/|git@(.+):)([\w\d-_/]+)(.git)?/);
return `https://${m[3]}/${m[4]}.git`;
}
if (url.startsWith('http')) {
if (!argv.useSSH) {
return url;
}
// have a http url need an ssh url
|
javascript
|
{
"resource": ""
}
|
q2650
|
guessUserName
|
train
|
function guessUserName(repo) {
// extract the host
const host = repo.match(/:\/\/([^/]+)/)[1];
const hostClean = host.replace(/\./g, '_').toUpperCase();
// e.g. GITHUB_COM_CREDENTIALS
const
|
javascript
|
{
"resource": ""
}
|
q2651
|
spawn
|
train
|
function spawn(cmd, args, opts) {
const spawn = require('child_process').spawn;
const _ = require('lodash');
return new Promise((resolve, reject) => {
const p = spawn(cmd, typeof args === 'string' ? args.split(' ') : args, _.merge({stdio: argv.quiet ? ['ignore', 'pipe', 'pipe'] : ['ignore', 1, 2]}, opts));
const out = [];
if (p.stdout) {
p.stdout.on('data', (chunk) => out.push(chunk));
}
if (p.stderr) {
p.stderr.on('data', (chunk) => out.push(chunk));
}
p.on('close', (code, signal) => {
if (code === 0) {
console.info(cmd, 'ok status code', code, signal);
resolve(code);
|
javascript
|
{
"resource": ""
}
|
q2652
|
npm
|
train
|
function npm(cwd, cmd) {
console.log(cwd, chalk.blue('running npm', cmd));
const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
javascript
|
{
"resource": ""
}
|
q2653
|
docker
|
train
|
function docker(cwd, cmd) {
console.log(cwd, chalk.blue('running docker', cmd));
|
javascript
|
{
"resource": ""
}
|
q2654
|
yo
|
train
|
function yo(generator, options, cwd) {
const yeoman = require('yeoman-environment');
// call yo internally
const yeomanEnv = yeoman.createEnv([], {cwd, env}, quiet ? createQuietTerminalAdapter() : undefined);
yeomanEnv.register(require.resolve('generator-phovea/generators/' + generator), 'phovea:' + generator);
return new Promise((resolve, reject) => {
try
|
javascript
|
{
"resource": ""
}
|
q2655
|
train
|
function (job, config, callback) {
var task = {
job: job,
config: config,
callback: callback || function () {
}
};
task.id = task.job._id;
// Tasks with identical keys will be prevented from being scheduled concurrently.
|
javascript
|
{
"resource": ""
}
|
|
q2656
|
train
|
function () {
var self = this;
// See how much capacity we have left to fill.
var launchCount = this.concurrency - Object.keys(this.active).length;
// Identify up to launchCount eligible tasks, giving priority to those earlier in the queue.
var offset = 0;
var launchTasks = [];
while (launchTasks.length < launchCount && this.tasks.length > offset) {
var task = this.tasks[offset];
if (task.key in this.active) {
// This task cannot run right now, so skip it.
offset += 1;
} else {
// This task is eligible to run. Remove it from the queue and prepare it to launch.
this.tasks.splice(offset, 1);
|
javascript
|
{
"resource": ""
}
|
|
q2657
|
train
|
function (id) {
for (var key in this.active) {
if (this.active.hasOwnProperty(key)
|
javascript
|
{
"resource": ""
}
|
|
q2658
|
train
|
function (opts) {
var paths = es.through();
var files = es.through();
paths.pipe(es.writeArray(function
|
javascript
|
{
"resource": ""
}
|
|
q2659
|
train
|
function (block) {
es.readArray([
'<!--',
' processed by htmlbuild',
'-->'
|
javascript
|
{
"resource": ""
}
|
|
q2660
|
train
|
function (template) {
var pattern = _.template(template)(fileReplace);
pattern = pattern.replace(/\//g, '\\/');
pattern = pattern.replace(/\s+/g, '\\s*');
|
javascript
|
{
"resource": ""
}
|
|
q2661
|
train
|
function (line, block) {
if (!block.template) {
return;
}
var regex = getRegExp(block.template);
|
javascript
|
{
"resource": ""
}
|
|
q2662
|
scrapDescription
|
train
|
function scrapDescription(window){
var $ = window.$;
var descriptions = [];
// Open Graph protocol by Facebook <meta property="og:description" content="(*)"/>
$('meta[property="og:description"]').each(function(){
var content = $(this).attr('content');
if(content) descriptions.push(content);
});
// Schema.org : <* itemprop="description">(*)</*>
$('[itemprop="description"]').each(function(){
var text = $(this).text();
if(text) descriptions.push(text);
});
|
javascript
|
{
"resource": ""
}
|
q2663
|
isValidExtension
|
train
|
function isValidExtension(src){
var extension = src.split('.').pop();
var
|
javascript
|
{
"resource": ""
}
|
q2664
|
scrapImage
|
train
|
function scrapImage(window){
var $ = window.$;
var url = window.url;
var thumbs = [];
var thumbsRejected = [];
var title = scrapTitle(window);
var addToThumbs = function(image,beginning){
var src = $(image).attr('src');
if(src && isValidExtension(src) ){
src = utils.toURL(src,url);
if(beginning){
thumbs.unshift(src);
}else{
thumbs.push(src);
}
}else if(src){
thumbsRejected.push(src);
}
};
// Open Graph protocol by Facebook: <meta property="og:image" content="(*)"/>
$('meta[property="og:image"]').each(function(){
var content = $(this).attr('content');
if(content) thumbs.push(utils.toURL(content));
});
|
javascript
|
{
"resource": ""
}
|
q2665
|
scrapTitle
|
train
|
function scrapTitle(window){
var $ = window.$;
var url = window.location.href;
// Tags or attributes whom can contain a nice title for the page
var titleTag = $('title').text().trim();
var metaTitleTag = $('meta[name="title"]').attr('content');
var openGraphTitle = $('meta[property="og:title"]').attr('content');
var h1Tag = $('h1').eq(0).text().trim();
var itempropNameTag = $('[itemprop="name"]').text().trim();
var titles = [titleTag, metaTitleTag, openGraphTitle, h1Tag, itempropNameTag];
// Regex of the web site name
var nameWebsite = utils.getWebsiteName(url);
var regex
|
javascript
|
{
"resource": ""
}
|
q2666
|
scrapVideo
|
train
|
function scrapVideo(window){
var $ = window.$;
var url = window.location.href;
var thumbs = [];
// Open Graph protocol by Facebook: <meta property="og:video" content="(*)"/>
$('meta').each(function(){
var property =
|
javascript
|
{
"resource": ""
}
|
q2667
|
parseRequirements
|
train
|
function parseRequirements(file) {
if (!file) {
return {};
}
file = file.trim();
if (file === '') {
return {};
}
const versions = {};
file.split('\n').forEach((line) => {
line = line.trim();
if (line.startsWith('-e')) {
// editable special dependency
const branchSeparator = line.indexOf('@');
const name = line.slice(0, branchSeparator).trim();
versions[name] = line.slice(branchSeparator).trim();
return;
}
|
javascript
|
{
"resource": ""
}
|
q2668
|
train
|
function(func, context, args, callback) {
try {
func.apply(context,
|
javascript
|
{
"resource": ""
}
|
|
q2669
|
fireOnce
|
train
|
function fireOnce(fn) {
var fired = false;
return function wrapped() {
|
javascript
|
{
"resource": ""
}
|
q2670
|
handleClientLoad
|
train
|
function handleClientLoad() {
(async ()=> {
await config.load()
await config.api.google.load()
|
javascript
|
{
"resource": ""
}
|
q2671
|
initClient
|
train
|
function initClient() {
gapi.client.init({
apiKey: config.api.google.web.key,
clientId: config.api.google.web.client_id,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the
|
javascript
|
{
"resource": ""
}
|
q2672
|
updateSigninStatus
|
train
|
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listFiles();
|
javascript
|
{
"resource": ""
}
|
q2673
|
appendPre
|
train
|
function appendPre(message) {
var pre = document.getElementById('content');
var textContent =
|
javascript
|
{
"resource": ""
}
|
q2674
|
listFiles
|
train
|
function listFiles() {
gapi.client.drive.files.list({
'pageSize': 10,
'fields': "nextPageToken, files(id, name)"
}).then(function(response) {
appendPre('Files:');
|
javascript
|
{
"resource": ""
}
|
q2675
|
Formatter
|
train
|
function Formatter(format, timeFormat) {
format = format || '%(message)';
timeFormat = timeFormat || '%Y-%m-%d %H:%M:%S';
/**
* @private
* @type {string}
*/
this._format
|
javascript
|
{
"resource": ""
}
|
q2676
|
stringifyString
|
train
|
function stringifyString( v , runtime , isTemplateSentence ) {
var maybeDollar = '' ;
if ( isTemplateSentence ) {
if ( v.key ) {
v = v.key ;
maybeDollar = '$' ;
}
else {
|
javascript
|
{
"resource": ""
}
|
q2677
|
t
|
train
|
function t(time, done) {
if (arguments.length === 1) {
done = time;
time = 2000;
}
var error = new Error(`Callback took too long (max: ${time})`);
var waiting = true;
var timeout = setTimeout(function () {
if (!waiting) return;
waiting = false;
done(error);
}, time);
function
|
javascript
|
{
"resource": ""
}
|
q2678
|
getRequest
|
train
|
function getRequest(options,callback){
var destroyed = false;
var req = request.get(options.url)
.set(options.headers)
.timeout(options.timeout)
.redirects(options.redirects)
.buffer(false)
.end(function(err,res){
if(err && !err.status) return onError(err);
// Check HTTP status code
var isHTTPError = isRedirect(res.status) || isClientError(res.status) || isServerError(res.status);
if(isHTTPError) {
var reqFormated = req.req;
var resFormated = err.response.res;
return onError(new HTTPError(reqFormated, resFormated));
}
// Attach event handlers and build the body
var body = '';
res.on('data',function(chunk){
body += chunk;
});
res.on('end',function(){
if(destroyed) return;
// Check if a HTTP refresh/redirection is present into the HTML page, if yes refreshes/redirects.
var matches = body.match(/<meta[ ]*http-equiv="REFRESH"[ ]*content="[0-9]{1,};[ ]*URL=(.*?)"[ ]*\/?>/i);
if(matches && matches[1]){
|
javascript
|
{
"resource": ""
}
|
q2679
|
buildDOM
|
train
|
function buildDOM(body,engine,url,callback){
if(!body){
return callback(new ScrapinodeError('The HTTP response contains an empty body: "' + body +'"'));
}
if(engine === 'jsdom' || engine === 'jsdom+zepto'){
var library = engine === 'jsdom+zepto' ? zepto : jquery;
try{
jsdom.env({
html: body,
src : [library],
done : function(err,window){
if(err) return callback(err);
if(!window) return callback(new ScrapinodeError('The "window" provides by JSDOM is falsy: ' + window));
window.location.href = url;
callback(err,window);
window.close();
}
});
}catch(err){
callback(err);
}
}else if(engine === 'cheerio'){
|
javascript
|
{
"resource": ""
}
|
q2680
|
isImage
|
train
|
function isImage(headers){
var regexImage = /image\//i;
var contentType = headers ?
|
javascript
|
{
"resource": ""
}
|
q2681
|
Schema
|
train
|
function Schema(options) {
this.options = options || {};
this.data = new Data();
this.isSchema = true;
this.utils = utils;
this.initSchema();
this.addFields(this.options);
|
javascript
|
{
"resource": ""
}
|
q2682
|
rewriteDockerCompose
|
train
|
function rewriteDockerCompose(compose) {
const services = compose.services;
if (!services) {
return compose;
}
const host
|
javascript
|
{
"resource": ""
}
|
q2683
|
train
|
function(token, this_, args, scope){
//fconsole.log('extend', arguments);
if (this.file.jsScope == basisScope)
{
var arg0 = token.arguments[0];
if (arg0 && arg0.type == 'Identifier' && arg0.name == 'Object')
|
javascript
|
{
"resource": ""
}
|
|
q2684
|
train
|
function(token, this_, args){
//fconsole.log('getNamespace', arguments);
var namespace = args[0];
if (namespace && namespace.type == 'Literal')
{
var ns = getNamespace(namespace.value);
token.obj = ns.obj;
|
javascript
|
{
"resource": ""
}
|
|
q2685
|
getReferenceIndexedByCSS
|
train
|
function getReferenceIndexedByCSS(ref) {
var newRef = {};
for (var symb in ref.symbolizers) {
for (var
|
javascript
|
{
"resource": ""
}
|
q2686
|
getOpacityOverride
|
train
|
function getOpacityOverride(sceneDrawGroup, isFill) {
var opacity;
if (isFill) {
opacity = sceneDrawGroup._hidden['opacity:fill'];
} else {
opacity = sceneDrawGroup._hidden['opacity:outline'];
}
|
javascript
|
{
"resource": ""
}
|
q2687
|
getFunctionFromDefaultAndShaderValue
|
train
|
function getFunctionFromDefaultAndShaderValue(sceneDrawGroup, ccssProperty, defaultValue, shaderValue) {
if (referenceCSS[ccssProperty].type === 'color') {
defaultValue = `'${color.normalize(defaultValue, tangramReference)}'`;
}
var fn = `var _value=${defaultValue};`;
shaderValue.js.forEach(function (code) {
|
javascript
|
{
"resource": ""
}
|
q2688
|
translateValue
|
train
|
function translateValue(sceneDrawGroup, ccssProperty, ccssValue) {
if (ccssProperty.indexOf('comp-op') >= 0) {
switch (ccssValue) {
case 'src-over':
return 'overlay';
case 'plus':
return 'add';
default:
return ccssValue;
}
}
|
javascript
|
{
"resource": ""
}
|
q2689
|
getFilterFn
|
train
|
function getFilterFn(layer, symbolizer) {
const symbolizers = Object.keys(layer.shader)
.filter(property => layer.shader[property].symbolizer === symbolizer);
//No need to set a callback when at least one property is not filtered (i.e. it always activates the symbolizer)
const alwaysActive = symbolizers
.reduce((a, property) => a || !layer.shader[property].filtered, false);
if (alwaysActive) {
|
javascript
|
{
"resource": ""
}
|
q2690
|
getGlob
|
train
|
function getGlob() {
if (isNode) {
return loader.import("@node-require", { name: module.id
|
javascript
|
{
"resource": ""
}
|
q2691
|
getModuleName
|
train
|
function getModuleName(nameWithConditional, variation) {
var modName;
var conditionIndex = nameWithConditional.search(conditionalRegEx);
// look for any "/" after the condition
var lastSlashIndex = nameWithConditional.indexOf("/",
nameWithConditional.indexOf("}"));
// substitution of a folder name
|
javascript
|
{
"resource": ""
}
|
q2692
|
train
|
function(m) {
var conditionValue = (typeof m === "object") ?
readMemberExpression(conditionExport, m) : m;
if (substitution) {
if (typeof conditionValue !== "string") {
throw new TypeError(
"The condition value for " +
conditionalMatch[0] +
" doesn't resolve to a string."
);
}
name = name.replace(conditionalRegEx, conditionValue);
}
else {
if (typeof conditionValue !== "boolean") {
throw new TypeError(
|
javascript
|
{
"resource": ""
}
|
|
q2693
|
Handler
|
train
|
function Handler(level) {
level = level || Logger.NOTSET;
if (Logger.getLevelName(level) === '') {
throw new Error('Argument 1 of Handler.constructor has unsupported'
+ ' value \'' + level + '\'');
}
Filterer.call(this);
|
javascript
|
{
"resource": ""
}
|
q2694
|
baseParse
|
train
|
function baseParse(text, strict) {
const lines = String(text).replace(/(?:\r?\n)+$/, '').split(/\r?\n/);
const records = [];
for (let i = 0, len = lines.length; i
|
javascript
|
{
"resource": ""
}
|
q2695
|
baseParseLine
|
train
|
function baseParseLine(line, strict) {
const fields = String(line).replace(/(?:\r?\n)+$/, '').split('\t');
const record = {};
for (let i = 0, len = fields.length; i < len; ++i) {
const _splitField = splitField(fields[i], strict),
|
javascript
|
{
"resource": ""
}
|
q2696
|
train
|
function(params) {
const order = this;
if (!params) {
params = {};
}
// the standards attributes
this.id = params.id;
this.dateCreated = params.dateCreated;
this.lastUpdated = params.lastUpdated;
this.version = params.version;
this.customer = params.customer;
this.orderDate = params.orderDate;
this.total = params.total;
this.items = params.items;
|
javascript
|
{
"resource": ""
}
|
|
q2697
|
customOverrider
|
train
|
function customOverrider (a, b, propertyName) {
if (b == null) {
return a
}
if (a == null) {
// Invoke default overrider
return undefined
}
// Some objects have custom overriders
if (b._customize_custom_overrider && b._customize_custom_overrider instanceof Function) {
return b._customize_custom_overrider(a, b, propertyName)
}
// Arrays should be concatenated
if (Array.isArray(a)) {
return a.concat(b)
}
// Merge values resolving promises, if
|
javascript
|
{
"resource": ""
}
|
q2698
|
MultiLine
|
train
|
function MultiLine( type , fold , applicable , options ) {
this.type = type ;
this.fold = !! fold ;
this.applicable
|
javascript
|
{
"resource": ""
}
|
q2699
|
train
|
function(callback) {
self._getConnection(function(err, connection) {
if (err) {
callback(new Error('Unable to establish connection with the master ' +
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.