_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q47600
|
createBakedElement
|
train
|
function createBakedElement(parentElem, element3d) {
// we might have a scene that has no baked level
if (!element3d.bakedModelUrl && !element3d.bakePreviewStatusFileKey) {
console.warn('Level without bakedModelUrl: ', element3d)
return
}
// set data3d.buffer file key
var attributes = {
'io3d-data3d': 'key: ' + element3d.bakedModelUrl,
shadow: 'cast: false; receive: true'
}
// set lightmap settings
if (element3d.lightMapIntensity) {
attributes['io3d-data3d'] += '; lightMapIntensity: ' + element3d.lightMapIntensity + '; lightMapExposure: ' + element3d.lightMapCenter
}
var bakedElem = addEntity({
attributes: attributes,
parent: parentElem
})
if (element3d.bakeRegularStatusFileKey || element3d.bakePreviewStatusFileKey) {
updateOnBake(bakedElem, element3d)
}
}
|
javascript
|
{
"resource": ""
}
|
q47601
|
GBlockLoader
|
train
|
function GBlockLoader () {
this.manager = THREE.DefaultLoadingManager
this.path = THREE.Loader.prototype.extractUrlBase( url )
}
|
javascript
|
{
"resource": ""
}
|
q47602
|
getElementPos
|
train
|
function getElementPos(pos) {
var l = 0
for (var i = 0; i < pos - 1; i++) { l += elements[i] }
return l
}
|
javascript
|
{
"resource": ""
}
|
q47603
|
normaliseScale
|
train
|
function normaliseScale(s) {
if (s>1) throw('s must be <1');
s = 0 | (1/s);
var l = log2(s);
var mask = 1 << l;
var accuracy = 4;
while(accuracy && l) { l--; mask |= 1<<l; accuracy--; }
return 1 / ( s & mask );
}
|
javascript
|
{
"resource": ""
}
|
q47604
|
fromCache
|
train
|
function fromCache(request) {
return caches.open(CACHE).then(function (cache) {
return cache.match(request).then(function (matching) {
return matching || Promise.reject('no-match');
});
});
}
|
javascript
|
{
"resource": ""
}
|
q47605
|
update
|
train
|
function update(request) {
// don't automatically put 3D models in the cache
if(request.url.match(/https:\/\/storage.3d.io/)) return fetch(request);
return caches.open(CACHE).then(function (cache) {
return fetch(request).then(function (response) {
return cache.put(request, response);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q47606
|
getNormalizeRotations
|
train
|
function getNormalizeRotations(start, end) {
// normalize both rotations
var normStart = normalizeRotation(start)
var normEnd = normalizeRotation(end)
// find the shortest arc for each rotation
Object.keys(start).forEach(function(axis) {
if (normEnd[axis] - normStart[axis] > 180) normEnd[axis] -= 360
})
return { start: normStart, end: normEnd }
}
|
javascript
|
{
"resource": ""
}
|
q47607
|
eliminateHoles
|
train
|
function eliminateHoles (data, holeIndices, outerNode, dim) {
var queue = [],
i, len, start, end, list
for (i = 0, len = holeIndices.length; i < len; i++) {
start = holeIndices[i] * dim
end = i < len - 1 ? holeIndices[i + 1] * dim : data.length
list = linkedList(data, start, end, dim, false)
if (list === list.next) {
list.steiner = true
}
list = filterPoints(data, list)
if (list) {
queue.push(getLeftmost(data, list))
}
}
queue.sort(function (a, b) {
return data[a.i] - data[b.i]
})
// process holes from left to right
for (i = 0; i < queue.length; i++) {
eliminateHole(data, queue[i], outerNode)
outerNode = filterPoints(data, outerNode, outerNode.next)
}
return outerNode
}
|
javascript
|
{
"resource": ""
}
|
q47608
|
orient
|
train
|
function orient (data, p, q, r) {
var o = (data[q + 1] - data[p + 1]) * (data[r] - data[q]) - (data[q] - data[p]) * (data[r + 1] - data[q + 1])
return o > 0 ? 1 : o < 0 ? -1 : 0
}
|
javascript
|
{
"resource": ""
}
|
q47609
|
equals
|
train
|
function equals (data, p1, p2) {
return data[p1] === data[p2] && data[p1 + 1] === data[p2 + 1]
}
|
javascript
|
{
"resource": ""
}
|
q47610
|
getOffset
|
train
|
function getOffset(a, b) {
// for elements that are aligned at the wall we want to compute the offset accordingly
var edgeAligned = config.edgeAligned
var tags = a.tags
a = a.boundingPoints
b = b.boundingPoints
if (!a || !b) return { x: 0, y: 0, z: 0 }
// check if the furniture's virtual origin should be center or edge
var isEdgeAligned = edgeAligned.some(function(t) {
return tags.includes(t)
})
var zOffset
// compute offset between edges or centers
if (isEdgeAligned) zOffset = a.min[2] - b.min[2]
else zOffset = (a.max[2] + a.min[2]) / 2 - (b.max[2] + b.min[2]) / 2
var offset = {
// compute offset between centers
x: (a.max[0] + a.min[0]) / 2 - (b.max[0] + b.min[0]) / 2,
y: 0,
z: zOffset
}
return offset
}
|
javascript
|
{
"resource": ""
}
|
q47611
|
updateElementsById
|
train
|
function updateElementsById(sceneStructure, id, replacement) {
var isArray = Array.isArray(sceneStructure)
sceneStructure = isArray ? sceneStructure : [sceneStructure]
sceneStructure = sceneStructure.map(function(element3d) {
// furniture id is stored in src param
if (element3d.type === 'interior' && element3d.src.substring(1) === id && replacement.furniture) {
// apply new id
element3d.src = '!' + replacement.furniture.id
// compute new position for items that differ in size and mesh origin
var newPosition = getNewPosition(element3d, replacement.offset)
// apply new position
element3d.x = newPosition.x
element3d.y = newPosition.y
element3d.z = newPosition.z
}
// recursivley search tree
if (element3d.children && element3d.children.length) {
element3d.children = updateElementsById(element3d.children, id, replacement)
}
return element3d
})
return isArray ? sceneStructure : sceneStructure[0]
}
|
javascript
|
{
"resource": ""
}
|
q47612
|
getNewPosition
|
train
|
function getNewPosition(element3d, offset) {
var s = Math.sin(element3d.ry / 180 * Math.PI)
var c = Math.cos(element3d.ry / 180 * Math.PI)
var newPosition = {
x: element3d.x + offset.x * c + offset.z * s,
y: element3d.y + offset.y,
z: element3d.z - offset.x * s + offset.z * c
}
return newPosition
}
|
javascript
|
{
"resource": ""
}
|
q47613
|
pollTexture
|
train
|
function pollTexture(storageId) {
var url = getNoCdnUrlFromStorageId(storageId)
return poll(function (resolve, reject, next) {
checkIfFileExists(url).then(function(exists){
exists ? resolve() : next()
})
})
}
|
javascript
|
{
"resource": ""
}
|
q47614
|
populateStatusesMap
|
train
|
function populateStatusesMap (statuses, codes) {
var arr = []
Object.keys(codes).forEach(function forEachCode (code) {
var message = codes[code]
var status = Number(code)
// Populate properties
statuses[status] = message
statuses[message] = status
statuses[message.toLowerCase()] = status
// Add to array
arr.push(status)
})
return arr
}
|
javascript
|
{
"resource": ""
}
|
q47615
|
status
|
train
|
function status (code) {
if (typeof code === 'number') {
if (!status[code]) throw new Error('invalid status code: ' + code)
return code
}
if (typeof code !== 'string') {
throw new TypeError('code must be a number or string')
}
// '403'
var n = parseInt(code, 10)
if (!isNaN(n)) {
if (!status[n]) throw new Error('invalid status code: ' + n)
return n
}
n = status[code.toLowerCase()]
if (!n) throw new Error('invalid status message: "' + code + '"')
return n
}
|
javascript
|
{
"resource": ""
}
|
q47616
|
fetchProvisionedInfo
|
train
|
function fetchProvisionedInfo (heroku, addon) {
return heroku.request({
host: host(addon),
method: 'get',
path: `/data/kafka/v0/clusters/${addon.id}`
}).catch(err => {
if (err.statusCode !== 404) throw err
cli.exit(1, `${cli.color.addon(addon.name)} is not yet provisioned.\nRun ${cli.color.cmd('heroku kafka:wait')} to wait until the cluster is provisioned.`)
})
}
|
javascript
|
{
"resource": ""
}
|
q47617
|
jenkinsHash
|
train
|
function jenkinsHash(key) {
var hash, i;
for(hash = i = 0; i < key.length; ++i) {
hash += key.charCodeAt(i);
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return hash;
}
|
javascript
|
{
"resource": ""
}
|
q47618
|
match
|
train
|
function match(pathA, pathB) {
var minCurves = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100;
var shapesA = pathToShapes(pathA.path);
var shapesB = pathToShapes(pathB.path);
var lenA = shapesA.length,
lenB = shapesB.length;
if (lenA > lenB) {
_subShapes(shapesB, lenA - lenB);
} else if (lenA < lenB) {
_upShapes(shapesA, lenB - lenA);
}
shapesA = (0, _sort.sort)(shapesA, shapesB);
shapesA.forEach(function (curves, index) {
var lenA = curves.length,
lenB = shapesB[index].length;
if (lenA > lenB) {
if (lenA < minCurves) {
_splitCurves(curves, minCurves - lenA);
_splitCurves(shapesB[index], minCurves - lenB);
} else {
_splitCurves(shapesB[index], lenA - lenB);
}
} else if (lenA < lenB) {
if (lenB < minCurves) {
_splitCurves(curves, minCurves - lenA);
_splitCurves(shapesB[index], minCurves - lenB);
} else {
_splitCurves(curves, lenB - lenA);
}
}
});
shapesA.forEach(function (curves, index) {
shapesA[index] = (0, _sort.sortCurves)(curves, shapesB[index]);
});
return [shapesA, shapesB];
}
|
javascript
|
{
"resource": ""
}
|
q47619
|
absolute
|
train
|
function absolute(elementDescriptor) {
if (arguments.length === 3) {
elementDescriptor = polyfillLegacy.apply(this, arguments);
}
var _elementDescriptor7 = elementDescriptor,
descriptor = _elementDescriptor7.descriptor;
if (descriptor.get) {
var _getter = descriptor.get;
descriptor.get = function () {
this[_attrAbsolute] = true;
var ret = _getter.call(this);
this[_attrAbsolute] = false;
return ret;
};
}
if (arguments.length === 3) return elementDescriptor.descriptor;
return elementDescriptor;
}
|
javascript
|
{
"resource": ""
}
|
q47620
|
decorators
|
train
|
function decorators() {
for (var _len3 = arguments.length, funcs = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
funcs[_key3] = arguments[_key3];
}
return function (key, value, descriptor) {
var elementDescriptor;
if (!descriptor) {
elementDescriptor = key;
} else {
elementDescriptor = {
key: key,
descriptor: descriptor,
value: value
};
}
var ret = funcs.reduceRight(function (a, b) {
return b.call(this, a);
}, elementDescriptor);
return ret && ret.descriptor;
};
}
|
javascript
|
{
"resource": ""
}
|
q47621
|
generateComponentMethods
|
train
|
function generateComponentMethods(componentMethods) {
if (componentMethods.length === 0) {
return ''
}
return componentMethods.reduce((acc, method) => {
const methods = `${acc}\n\xa0\xa0\xa0\xa0${method}(){}\n`
return methods
}, '')
}
|
javascript
|
{
"resource": ""
}
|
q47622
|
generateQuestionsCustom
|
train
|
function generateQuestionsCustom(config, questions) {
const mandatoryQuestions = [questions.name, questions.path]
return mandatoryQuestions.filter((question) => {
if (config[question.name]) {
return false
}
return true
})
}
|
javascript
|
{
"resource": ""
}
|
q47623
|
generateQuestions
|
train
|
function generateQuestions(config = {}, questions = {}) {
const questionKeys = Object.keys(questions)
if (!config) {
return questionKeys.map(question => questions[question])
}
// If type is custom, filter question mandatory to work
if (config.type === 'custom') {
return generateQuestionsCustom(config, questions)
}
// filter questions from config object
const filteredQuestions = []
questionKeys.forEach((question) => {
if (!(question in config)) {
filteredQuestions.push(questions[question])
}
})
return filteredQuestions
}
|
javascript
|
{
"resource": ""
}
|
q47624
|
createListOfDirectories
|
train
|
function createListOfDirectories(prev, dir) {
return {
...prev,
[dir.split(path.sep).pop()]: dir,
}
}
|
javascript
|
{
"resource": ""
}
|
q47625
|
getTemplatesList
|
train
|
function getTemplatesList(customPath = null) {
const predefined = getDirectories(DEFAULT_PATH_TEMPLATES).reduce(createListOfDirectories, {})
try {
const custom = customPath ? getDirectories(customPath).reduce(createListOfDirectories, {}) : []
return { ...predefined, ...custom }
} catch (error) {
Logger.warn('The custom templates path that you supply is unreachable')
Logger.warn('falling back to defaults templates')
return predefined
}
}
|
javascript
|
{
"resource": ""
}
|
q47626
|
getConfig
|
train
|
function getConfig(configPath, searchPath = process.cwd(), stopDir = homedir()) {
const useCustomPath = !!configPath
const explorer = cosmiconfig('cca', { sync: true, stopDir })
try {
const searchPathAbsolute = !useCustomPath && searchPath
const configPathAbsolute = useCustomPath && path.join(process.cwd(), configPath)
// search from the root of the process if the user didnt specify a config file,
// or use the custom path if a file is passed.
const result = explorer.load(searchPathAbsolute, configPathAbsolute)
// dont throw if the explorer didnt find a configfile,
// instead use default config
const config = result ? result.config : {}
const filepath = result ? result.filepath : {}
if (!result) Logger.log('No config file detected, using defaults.')
return { ...config, filepath }
} catch (error) {
Logger.error('An error occured while parsing your config file. Using defaults...\n\n', error.message)
}
return {}
}
|
javascript
|
{
"resource": ""
}
|
q47627
|
getDirectories
|
train
|
function getDirectories(source) {
const isDirectory = sourcePath => lstatSync(sourcePath).isDirectory()
return readdirSync(source)
.map(name => join(source, name))
.filter(isDirectory)
}
|
javascript
|
{
"resource": ""
}
|
q47628
|
readFile
|
train
|
function readFile(path, fileName) {
return new Promise((resolve, reject) => {
fs.readFile(`${path}/${fileName}`, 'utf8', (err, content) => {
if (err) {
return reject(err)
}
return resolve(content)
})
})
}
|
javascript
|
{
"resource": ""
}
|
q47629
|
replaceKeys
|
train
|
function replaceKeys(searchString, replacement) {
const replacementKeys = {
COMPONENT_NAME: replacement,
component_name: replacement.toLowerCase(),
COMPONENT_CAP_NAME: replacement.toUpperCase(),
cOMPONENT_NAME: replacement[0].toLowerCase() + replacement.substr(1),
}
return Object.keys(replacementKeys).reduce(
(acc, curr) => {
if (acc.includes(curr)) {
const regEx = new RegExp(curr, 'g')
return acc.replace(regEx, replacementKeys[curr])
}
return acc
},
searchString
)
}
|
javascript
|
{
"resource": ""
}
|
q47630
|
generateFilesFromTemplate
|
train
|
async function generateFilesFromTemplate({ name, path, templatesPath }) {
try {
const files = glob.sync('**/*', { cwd: templatesPath, nodir: true })
const config = getConfig(null, templatesPath, templatesPath)
const outputPath = config.noMkdir ? `${path}` : `${path}/${name}`
files.map(async (templateFileName) => {
// Get the template content
const content = await readFile(templatesPath, templateFileName)
const replaced = replaceKeys(content, name)
// Exist ?
const newFileName = replaceKeys(templateFileName, name)
// Write the new file with the new content
fs.outputFile(`${outputPath}/${newFileName}`, replaced)
})
} catch (e) {
Logger.error(e.message)
}
}
|
javascript
|
{
"resource": ""
}
|
q47631
|
getFileNames
|
train
|
function getFileNames(fileNames = [], componentName) {
const defaultFileNames = {
testFileName: `${defaultOptions.testFileName}.${componentName}`,
componentFileName: componentName,
styleFileName: componentName,
}
const formattedFileNames = Object.keys(fileNames).reduce(
(acc, curr) => {
acc[curr] = replaceKeys(fileNames[curr], componentName)
return acc
},
{ ...defaultFileNames }
)
return formattedFileNames
}
|
javascript
|
{
"resource": ""
}
|
q47632
|
generateFiles
|
train
|
function generateFiles(params) {
const {
type,
name,
fileNames,
path,
indexFile,
cssExtension,
componentMethods,
jsExtension,
connected,
includeStories,
includeTests,
} = params
const destination = `${path}/${name}`
const { testFileName, componentFileName, styleFileName } = getFileNames(fileNames, name)
if (indexFile || connected) {
fs.outputFile(`${destination}/index.js`, generateIndexFile(componentFileName, connected))
}
if (includeStories) {
fs.outputFile(`${destination}/${name}.stories.${jsExtension}`, generateStorybookTemplate(name))
}
if (includeTests) {
fs.outputFile(`${destination}/${testFileName}.${jsExtension}`, generateTestTemplate(name))
}
// Create js file
fs.outputFile(
`${destination}/${componentFileName}.${jsExtension}`,
generateComponentTemplate(type, componentFileName, {
cssExtension,
componentMethods,
styleFileName,
})
)
// Create css file
if (cssExtension) {
fs.outputFile(
`${destination}/${styleFileName}.${cssExtension}`,
generateStyleFile(styleFileName)
)
}
}
|
javascript
|
{
"resource": ""
}
|
q47633
|
HeartbeatController
|
train
|
function HeartbeatController(client, sourceId, destinationId) {
JsonController.call(this, client, sourceId, destinationId, 'urn:x-cast:com.google.cast.tp.heartbeat');
this.pingTimer = null;
this.timeout = null;
this.intervalValue = DEFAULT_INTERVAL;
this.on('message', onmessage);
this.once('close', onclose);
var self = this;
function onmessage(data, broadcast) {
if(data.type === 'PONG') {
self.emit('pong');
}
}
function onclose() {
self.removeListener('message', onmessage);
self.stop();
}
}
|
javascript
|
{
"resource": ""
}
|
q47634
|
train
|
function(key, type, validKeys, raw) {
return {
title: 'Annotation ' + chalk.underline('@' + key) +
' not allowed for type ' + type + ' of ' + chalk.underline(raw.descriptor) + ' in ' + raw.file,
text: 'Valid annotations are @' + validKeys.join(', @') + '. This element will not appear in the final StyleGuide until you fix this error.'
};
}
|
javascript
|
{
"resource": ""
}
|
|
q47635
|
fixList
|
train
|
function fixList(str) {
str = str.replace(/([ ]{1,4}[+-] \[?[^)]+\)?)\n\n\* /gm, '$1\n* ');
str = str.split('__{_}_*').join('**{*}**');
return str;
}
|
javascript
|
{
"resource": ""
}
|
q47636
|
noformat
|
train
|
function noformat(app, file, locals, argv) {
return app.isTrue('noformat') || app.isFalse('format')
|| file.noformat === true || file.format === false
|| locals.noformat === true || locals.format === false
|| argv.noformat === true || argv.format === false;
}
|
javascript
|
{
"resource": ""
}
|
q47637
|
gitignore
|
train
|
function gitignore(cwd, fp, arr) {
fp = path.resolve(cwd, fp);
if (!fs.existsSync(fp)) {
return utils.defaultIgnores;
}
var str = fs.readFileSync(fp, 'utf8');
return parse(str, arr);
}
|
javascript
|
{
"resource": ""
}
|
q47638
|
createStack
|
train
|
function createStack(app, plugins) {
if (app.enabled('minimal config')) {
return es.pipe.apply(es, []);
}
function enabled(acc, plugin, name) {
if (plugin == null) {
acc.push(through.obj());
}
if (app.enabled(name + ' plugin')) {
acc.push(plugin);
}
return acc;
}
var arr = _.reduce(plugins, enabled, []);
return es.pipe.apply(es, arr);
}
|
javascript
|
{
"resource": ""
}
|
q47639
|
enabled
|
train
|
function enabled(app, file, options, argv) {
var template = extend({}, file.locals, file.options, file.data);
return isTrue(argv, 'reflinks')
|| isTrue(template, 'reflinks')
|| isTrue(options, 'reflinks')
|| isTrue(app.options, 'reflinks');
}
|
javascript
|
{
"resource": ""
}
|
q47640
|
JSONReporter
|
train
|
function JSONReporter(detector) {
BaseReporter.call(this, detector);
detector.on('start', function() {
process.stdout.write('[');
});
detector.on('end', function() {
process.stdout.write("]\n");
});
}
|
javascript
|
{
"resource": ""
}
|
q47641
|
train
|
function(db, opt_err) {
if (df.hasFired()) {
goog.log.warning(me.logger, 'database already set.');
} else if (goog.isDef(opt_err)) {
goog.log.warning(me.logger, opt_err ? opt_err.message : 'Error received.');
me.idx_db_ = null;
df.errback(opt_err);
} else {
goog.asserts.assertObject(db, 'db');
me.idx_db_ = db;
me.idx_db_.onabort = function(e) {
goog.log.finest(me.logger, me + ': abort');
var request = /** @type {IDBRequest} */ (e.target);
me.onError(request.error);
};
me.idx_db_.onerror = function(e) {
if (ydn.db.con.IndexedDb.DEBUG) {
goog.global.console.log(e);
}
goog.log.finest(me.logger, me + ': error');
var request = /** @type {IDBRequest} */ (e.target);
me.onError(request.error);
};
/**
* @this {null}
* @param {IDBVersionChangeEvent} event event.
*/
me.idx_db_.onversionchange = function(event) {
// Handle version changes while a web app is open in another tab
// https://developer.mozilla.org/en-US/docs/IndexedDB/Using_IndexedDB#
// Version_changes_while_a_web_app_is_open_in_another_tab
//
if (ydn.db.con.IndexedDb.DEBUG) {
goog.global.console.log([this, event]);
}
goog.log.finest(me.logger, me + ' closing connection for onversionchange to: ' +
event.version);
if (me.idx_db_) {
me.idx_db_.onabort = null;
me.idx_db_.onblocked = null;
me.idx_db_.onerror = null;
me.idx_db_.onversionchange = null;
me.onVersionChange(event);
if (!event.defaultPrevented) {
me.idx_db_.close();
me.idx_db_ = null;
var e = new Error();
e.name = event.type;
me.onFail(e);
}
}
};
df.callback(parseFloat(old_version));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47642
|
train
|
function(db, trans, is_caller_setversion) {
var action = is_caller_setversion ? 'changing' : 'upgrading';
goog.log.finer(me.logger, action + ' version to ' + db.version +
' from ' + old_version);
// create store that we don't have previously
for (var i = 0; i < schema.stores.length; i++) {
// this is sync process.
me.update_store_(db, trans, schema.stores[i]);
}
// delete stores
var storeNames = /** @type {DOMStringList} */ (db.objectStoreNames);
for (var n = storeNames.length, i = 0; i < n; i++) {
if (!schema.hasStore(storeNames[i])) {
db.deleteObjectStore(storeNames[i]);
goog.log.finer(me.logger, 'store: ' + storeNames[i] + ' deleted.');
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47643
|
train
|
function(db_schema) {
var diff_msg = schema.difference(db_schema, false, true);
if (diff_msg.length > 0) {
goog.log.log(me.logger, goog.log.Level.FINER, diff_msg);
setDb(null, new ydn.error.ConstraintError('different schema: ' +
diff_msg));
} else {
setDb(db);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47644
|
train
|
function(i, opt_key) {
if (done) {
if (ydn.db.core.DbOperator.DEBUG) {
goog.global.console.log('iterator ' + i + ' done');
}
// calling next to a terminated iterator
throw new ydn.error.InternalError();
}
result_count++;
var is_result_ready = result_count === total;
var idx = idx2iterator[i];
/**
* @type {!ydn.db.Iterator}
*/
var iterator = iterators[idx];
/**
* @type {!ydn.db.core.req.ICursor}
*/
var cursor = cursors[idx];
var primary_key = cursor.getPrimaryKey();
var value = cursor.getValue();
if (ydn.db.core.DbOperator.DEBUG) {
var key_str = opt_key +
(goog.isDefAndNotNull(primary_key) ? ', ' + primary_key : '');
var ready_str = is_result_ready ? ' (all result done)' : '';
goog.global.console.log(cursor + ' new position ' + key_str + ready_str);
}
keys[i] = opt_key;
if (iterator.isIndexIterator()) {
if (iterator.isKeyIterator()) {
values[i] = primary_key;
} else {
values[i] = value;
}
} else {
if (iterator.isKeyIterator()) {
values[i] = opt_key;
} else {
values[i] = value;
}
}
if (is_result_ready) { // receive all results
on_result_ready();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47645
|
train
|
function(index, value) {
var idx_name = ydn.db.base.PREFIX_MULTIENTRY +
table.getName() + ':' + index.getName();
var idx_sql = insert_statement + goog.string.quote(idx_name) + ' (' +
table.getSQLKeyColumnNameQuoted() + ', ' +
index.getSQLIndexColumnNameQuoted() + ') VALUES (?, ?)';
var idx_params = [ydn.db.schema.Index.js2sql(key, table.getType()),
ydn.db.schema.Index.js2sql(value, index.getType())];
/**
* @param {SQLTransaction} tx transaction.
* @param {SQLResultSet} rs results.
*/
var idx_success = function(tx, rs) {
};
/**
* @param {SQLTransaction} tr transaction.
* @param {SQLError} error error.
* @return {boolean} true to roll back.
*/
var idx_error = function(tr, error) {
goog.log.warning(me.logger, 'multiEntry index insert error: ' + error.message);
return false;
};
goog.log.finest(me.logger, req.getLabel() + ' multiEntry ' + idx_sql +
' ' + idx_params);
tx.executeSql(idx_sql, idx_params, idx_success, idx_error);
}
|
javascript
|
{
"resource": ""
}
|
|
q47646
|
buildExampleScripts
|
train
|
function buildExampleScripts(dev) {
var dest = EXAMPLE_DIST_PATH;
var opts = dev ? watchify.args : {};
opts.debug = dev ? true : false;
opts.hasExports = true;
return function() {
var common = browserify(opts),
bundle = browserify(opts).require('./' + SRC_PATH + '/' + PACKAGE_FILE, { expose: PACKAGE_NAME }),
example = browserify(opts).exclude(PACKAGE_NAME).add('./' + EXAMPLE_SRC_PATH + '/' + EXAMPLE_APP);
DEPENDENCIES.forEach(function(pkg) {
common.require(pkg);
bundle.exclude(pkg);
example.exclude(pkg);
});
if (dev) {
watchBundle(common, 'common.js', dest);
watchBundle(bundle, 'bundle.js', dest);
watchBundle(example, 'app.js', dest);
}
return merge(
doBundle(common, 'common.js', dest),
doBundle(bundle, 'bundle.js', dest),
doBundle(example, 'app.js', dest)
);
}
}
|
javascript
|
{
"resource": ""
}
|
q47647
|
addTemplate
|
train
|
function addTemplate (poet, data) {
if (!data.ext || !data.fn)
throw new Error('Template must have both an extension and formatter function');
[].concat(data.ext).map(function (ext) {
poet.templates[ext] = data.fn;
});
return poet;
}
|
javascript
|
{
"resource": ""
}
|
q47648
|
watch
|
train
|
function watch (poet, callback) {
var watcher = fs.watch(poet.options.posts, function (event, filename) {
poet.init().then(callback);
});
poet.watchers.push({
'watcher': watcher,
'callback': callback
});
return poet;
}
|
javascript
|
{
"resource": ""
}
|
q47649
|
unwatch
|
train
|
function unwatch (poet) {
poet.watchers.forEach(function (watcher) {
watcher.watcher.close();
});
poet.futures.forEach(function (future) {
clearTimeout(future);
});
poet.watchers = [];
poet.futures = [];
return poet;
}
|
javascript
|
{
"resource": ""
}
|
q47650
|
scheduleFutures
|
train
|
function scheduleFutures (poet, allPosts) {
var now = Date.now();
var extraTime = 5 * 1000; // 10 seconds buffer
var min = now - extraTime;
allPosts.forEach(function (post, i) {
if (!post) return;
var postTime = post.date.getTime();
// if post is in the future
if (postTime - min > 0) {
// Prevent setTimeout overflow when scheduling more than 24 days out. See https://github.com/jsantell/poet/issues/119
var delay = Math.min(postTime - min, Math.pow(2, 31) - 1);
var future = setTimeout(function () {
poet.watchers.forEach(function (watcher) {
poet.init().then(watcher.callback);
});
}, delay);
poet.futures.push(future);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q47651
|
getPostPaths
|
train
|
function getPostPaths (dir) {
return fs.readdir(dir).then(function (files) {
return all(files.map(function (file) {
var path = pathify(dir, file);
return fs.stat(path).then(function (stats) {
return stats.isDirectory() ?
getPostPaths(path) :
path;
});
}));
}).then(function (files) {
return _.flatten(files);
});
}
|
javascript
|
{
"resource": ""
}
|
q47652
|
getPreview
|
train
|
function getPreview (post, body, options) {
var readMoreTag = options.readMoreTag || post.readMoreTag;
var preview;
if (post.preview) {
preview = post.preview;
} else if (post.previewLength) {
preview = body.trim().substr(0, post.previewLength);
} else if (~body.indexOf(readMoreTag)) {
preview = body.split(readMoreTag)[0];
} else {
preview = body.trim().replace(/\n.*/g, '');
}
return preview;
}
|
javascript
|
{
"resource": ""
}
|
q47653
|
method
|
train
|
function method (lambda) {
return function () {
return lambda.apply(null, [this].concat(Array.prototype.slice.call(arguments, 0)));
};
}
|
javascript
|
{
"resource": ""
}
|
q47654
|
getTemplate
|
train
|
function getTemplate (templates, fileName) {
var extMatch = fileName.match(/\.([^\.]*)$/);
if (extMatch && extMatch.length > 1)
return templates[extMatch[1]];
return null;
}
|
javascript
|
{
"resource": ""
}
|
q47655
|
createPost
|
train
|
function createPost (filePath, options) {
var fileName = path.basename(filePath);
return fs.readFile(filePath, 'utf-8').then(function (data) {
var parsed = (options.metaFormat === 'yaml' ? yamlFm : jsonFm)(data);
var body = parsed.body;
var post = parsed.attributes;
// If no date defined, create one for current date
post.date = new Date(post.date);
post.content = body;
// url slug for post
post.slug = convertStringToSlug(post.slug || post.title);
post.url = createURL(getRoute(options.routes, 'post'), post.slug);
post.preview = getPreview(post, body, options);
return post;
});
}
|
javascript
|
{
"resource": ""
}
|
q47656
|
sortPosts
|
train
|
function sortPosts (posts) {
return Object.keys(posts).map(function (post) { return posts[post]; })
.sort(function (a,b) {
if ( a.date < b.date ) return 1;
if ( a.date > b.date ) return -1;
return 0;
});
}
|
javascript
|
{
"resource": ""
}
|
q47657
|
getTags
|
train
|
function getTags (posts) {
var tags = posts.reduce(function (tags, post) {
if (!post.tags || !Array.isArray(post.tags)) return tags;
return tags.concat(post.tags);
}, []);
return _.unique(tags).sort();
}
|
javascript
|
{
"resource": ""
}
|
q47658
|
getCategories
|
train
|
function getCategories (posts) {
var categories = posts.reduce(function (categories, post) {
if (!post.category) return categories;
return categories.concat(post.category);
}, []);
return _.unique(categories).sort();
}
|
javascript
|
{
"resource": ""
}
|
q47659
|
pathify
|
train
|
function pathify (dir, file) {
if (file)
return path.normalize(path.join(dir, file));
else
return path.normalize(dir);
}
|
javascript
|
{
"resource": ""
}
|
q47660
|
bindRoutes
|
train
|
function bindRoutes (poet) {
var app = poet.app;
var routes = poet.options.routes;
// If no routes specified, abort
if (!routes) return;
Object.keys(routes).map(function (route) {
var type = utils.getRouteType(route);
if (!type) return;
app.get(route, routeMap[type](poet, routes[route]));
});
}
|
javascript
|
{
"resource": ""
}
|
q47661
|
getPosts
|
train
|
function getPosts (poet) {
if (poet.cache.posts)
return poet.cache.posts;
var posts = utils.sortPosts(poet.posts).filter(function (post) {
// Filter out draft posts if showDrafts is false
return (poet.options.showDrafts || !post.draft) &&
// Filter out posts in the future if showFuture is false
(poet.options.showFuture || post.date < Date.now());
});
return poet.cache.posts = posts;
}
|
javascript
|
{
"resource": ""
}
|
q47662
|
getTags
|
train
|
function getTags (poet) {
return poet.cache.tags || (poet.cache.tags = utils.getTags(getPosts(poet)));
}
|
javascript
|
{
"resource": ""
}
|
q47663
|
getCategories
|
train
|
function getCategories (poet) {
return poet.cache.categories ||
(poet.cache.categories = utils.getCategories(getPosts(poet)));
}
|
javascript
|
{
"resource": ""
}
|
q47664
|
createDefaults
|
train
|
function createDefaults () {
return {
postsPerPage: 5,
posts: './_posts/',
showDrafts: process.env.NODE_ENV !== 'production',
showFuture: process.env.NODE_ENV !== 'production',
metaFormat: 'json',
readMoreLink: readMoreLink,
readMoreTag: '<!--more-->',
routes: {
'/post/:post': 'post',
'/page/:page': 'page',
'/tag/:tag': 'tag',
'/category/:category': 'category'
}
};
}
|
javascript
|
{
"resource": ""
}
|
q47665
|
createServer
|
train
|
function createServer(opts) {
opts.webpackConfigPath = path.resolve(process.cwd(), opts.webpackConfigPath);
if (fs.existsSync(opts.webpackConfigPath)) {
opts.webpackConfig = require(path.resolve(process.cwd(), opts.webpackConfigPath));
} else {
throw new Error('Must specify webpackConfigPath or create ./webpack.config.js');
}
delete opts.webpackConfigPath;
const server = new Server(opts);
return server;
}
|
javascript
|
{
"resource": ""
}
|
q47666
|
commonOptions
|
train
|
function commonOptions(program) {
return program
.option(
'-H, --hostname [hostname]',
'Hostname on which the server will listen. [localhost]',
'localhost'
)
.option(
'-P, --port [port]',
'Port on which the server will listen. [8080]',
8080
)
.option(
'-p, --packagerPort [port]',
'Port on which the react-native packager will listen. [8081]',
8081
)
.option(
'-w, --webpackPort [port]',
'Port on which the webpack dev server will listen. [8082]',
8082
)
.option(
'-c, --webpackConfigPath [path]',
'Path to the webpack configuration file. [webpack.config.js]',
'webpack.config.js'
)
.option(
'--no-android',
'Disable support for Android. [false]',
false
)
.option(
'--no-ios',
'Disable support for iOS. [false]',
false
)
.option(
'-A, --androidEntry [name]',
'Android entry module name. Has no effect if \'--no-android\' is passed. [index.android]',
'index.android'
)
.option(
'-I, --iosEntry [name]',
'iOS entry module name. Has no effect if \'--no-ios\' is passed. [index.ios]',
'index.ios'
)
.option(
'--projectRoots [projectRoots]',
'List of comma-separated paths for the react-native packager to consider as project root directories',
null
)
.option(
'--root [root]',
'List of comma-separated paths for the react-native packager to consider as additional directories. If provided, these paths must include react-native and its dependencies.',
null
)
.option(
'--assetRoots [assetRoots]',
'List of comma-separated paths for the react-native packager to consider as asset root directories',
null
)
.option(
'-r, --resetCache',
'Remove cached react-native packager files [false]',
false
)
.option(
'--hasteExternals',
// React Native 0.23 rewrites `require('HasteModule')` calls to
// `require(42)` where 42 is an internal module id. That breaks
// treating Haste modules simply as commonjs modules and leaving
// the `require()` call in the source. So for now this feature
// only works with React Native <0.23.
'Allow direct import of React Native\'s (<0.23) internal Haste modules [false]',
false
);
}
|
javascript
|
{
"resource": ""
}
|
q47667
|
getReactNativeExternals
|
train
|
function getReactNativeExternals(options) {
return Promise.all(options.platforms.map(
(platform) => getReactNativeDependencyNames({
projectRoots: options.projectRoots || [process.cwd()],
assetRoots: options.assetRoots || [process.cwd()],
platform: platform,
})
)).then((moduleNamesGroupedByPlatform) => {
const allReactNativeModules = Array.prototype.concat.apply([], moduleNamesGroupedByPlatform);
return makeWebpackExternalsConfig(allReactNativeModules);
});
}
|
javascript
|
{
"resource": ""
}
|
q47668
|
makeWebpackExternalsConfig
|
train
|
function makeWebpackExternalsConfig(moduleNames) {
return moduleNames.reduce((externals, moduleName) => Object.assign(externals, {
[moduleName]: `commonjs ${moduleName}`,
}), {});
}
|
javascript
|
{
"resource": ""
}
|
q47669
|
getReactNativeDependencyNames
|
train
|
function getReactNativeDependencyNames(options) {
const blacklist = require('react-native/packager/blacklist');
const ReactPackager = require('react-native/packager/react-packager');
const rnEntryPoint = require.resolve('react-native');
return ReactPackager.getDependencies({
blacklistRE: blacklist(false /* don't blacklist any platform */),
projectRoots: options.projectRoots,
assetRoots: options.assetRoots,
transformModulePath: require.resolve('react-native/packager/transformer'),
}, {
entryFile: rnEntryPoint,
dev: true,
platform: options.platform,
}).then(dependencies =>
dependencies.filter(dependency => !dependency.isPolyfill())
).then(dependencies =>
Promise.all(dependencies.map(dependency => dependency.getName()))
);
}
|
javascript
|
{
"resource": ""
}
|
q47670
|
_hasOwnProperty
|
train
|
function _hasOwnProperty(obj) {
var key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q47671
|
sendHostname
|
train
|
function sendHostname(appName, trackingId) {
var url = 'https://www.google-analytics.com/collect';
var hostname = location.hostname;
var hitType = 'event';
var eventCategory = 'use';
var applicationKeyForStorage = 'TOAST UI ' + appName + ' for ' + hostname + ': Statistics';
var date = window.localStorage.getItem(applicationKeyForStorage);
// skip if the flag is defined and is set to false explicitly
if (!type.isUndefined(window.tui) && window.tui.usageStatistics === false) {
return;
}
// skip if not pass seven days old
if (date && !isExpired(date)) {
return;
}
window.localStorage.setItem(applicationKeyForStorage, new Date().getTime());
setTimeout(function() {
if (document.readyState === 'interactive' || document.readyState === 'complete') {
imagePing(url, {
v: 1,
t: hitType,
tid: trackingId,
cid: hostname,
dp: hostname,
dh: appName,
el: appName,
ec: eventCategory
});
}
}, 1000);
}
|
javascript
|
{
"resource": ""
}
|
q47672
|
setConfig
|
train
|
function setConfig(defaultConfig, server) {
if (server === 'ne') {
defaultConfig.customLaunchers = {
'IE8': {
base: 'WebDriver',
config: webdriverConfig,
browserName: 'internet explorer',
version: '8'
},
'IE9': {
base: 'WebDriver',
config: webdriverConfig,
browserName: 'internet explorer',
version: '9'
},
'IE10': {
base: 'WebDriver',
browserName: 'internet explorer',
config: webdriverConfig,
version: '10'
},
'IE11': {
base: 'WebDriver',
config: webdriverConfig,
browserName: 'internet explorer',
version: '11'
},
'Edge': {
base: 'WebDriver',
config: webdriverConfig,
browserName: 'MicrosoftEdge'
},
'Chrome-WebDriver': {
base: 'WebDriver',
config: webdriverConfig,
browserName: 'chrome'
},
'Firefox-WebDriver': {
base: 'WebDriver',
config: webdriverConfig,
browserName: 'firefox'
}
// 'Safari-WebDriver': {
// base: 'WebDriver',
// config: webdriverConfig,
// browserName: 'safari'
// }
};
defaultConfig.browsers = [
// @FIXME: localStorage mocking 버그. 이후 수정 필요
// 'IE8',
'IE9',
'IE10',
// 'IE11',
// 'Edge',
'Chrome-WebDriver',
'Firefox-WebDriver'
// 'Safari-WebDriver'
];
defaultConfig.reporters.push('coverage');
defaultConfig.reporters.push('junit');
defaultConfig.coverageReporter = {
dir: 'report/coverage/',
reporters: [{
type: 'html',
subdir: function(browser) {
return 'report-html/' + browser;
}
},
{
type: 'cobertura',
subdir: function(browser) {
return 'report-cobertura/' + browser;
},
file: 'cobertura.txt'
}
]
};
defaultConfig.junitReporter = {
outputDir: 'report/junit',
suite: ''
};
} else {
defaultConfig.browsers = [
'ChromeHeadless'
];
}
}
|
javascript
|
{
"resource": ""
}
|
q47673
|
isValidDate
|
train
|
function isValidDate(year, month, date) { // eslint-disable-line complexity
var isValidYear, isValidMonth, isValid, lastDayInMonth;
year = Number(year);
month = Number(month);
date = Number(date);
isValidYear = (year > -1 && year < 100) || ((year > 1969) && (year < 2070));
isValidMonth = (month > 0) && (month < 13);
if (!isValidYear || !isValidMonth) {
return false;
}
lastDayInMonth = MONTH_DAYS[month];
if (month === 2 && year % 4 === 0) {
if (year % 100 !== 0 || year % 400 === 0) {
lastDayInMonth = 29;
}
}
isValid = (date > 0) && (date <= lastDayInMonth);
return isValid;
}
|
javascript
|
{
"resource": ""
}
|
q47674
|
throttle
|
train
|
function throttle(fn, interval) {
var base;
var isLeading = true;
var tick = function(_args) {
fn.apply(null, _args);
base = null;
};
var debounced, stamp, args;
/* istanbul ignore next */
interval = interval || 0;
debounced = tricks.debounce(tick, interval);
function throttled() { // eslint-disable-line require-jsdoc
args = aps.call(arguments);
if (isLeading) {
tick(args);
isLeading = false;
return;
}
stamp = tricks.timestamp();
base = base || stamp;
// pass array directly because `debounce()`, `tick()` are already use
// `apply()` method to invoke developer's `fn` handler.
//
// also, this `debounced` line invoked every time for implements
// `trailing` features.
debounced(args);
if ((stamp - base) >= interval) {
tick(args);
}
}
function reset() { // eslint-disable-line require-jsdoc
isLeading = true;
base = null;
}
throttled.reset = reset;
return throttled;
}
|
javascript
|
{
"resource": ""
}
|
q47675
|
extend
|
train
|
function extend(target, objects) { // eslint-disable-line no-unused-vars
var hasOwnProp = Object.prototype.hasOwnProperty;
var source, prop, i, len;
for (i = 1, len = arguments.length; i < len; i += 1) {
source = arguments[i];
for (prop in source) {
if (hasOwnProp.call(source, prop)) {
target[prop] = source[prop];
}
}
}
return target;
}
|
javascript
|
{
"resource": ""
}
|
q47676
|
stamp
|
train
|
function stamp(obj) {
if (!obj.__fe_id) {
lastId += 1;
obj.__fe_id = lastId; // eslint-disable-line camelcase
}
return obj.__fe_id;
}
|
javascript
|
{
"resource": ""
}
|
q47677
|
mixin
|
train
|
function mixin(sources, opts = {}) {
const { override, promisify = true } = opts;
Object.getOwnPropertyNames(sources).forEach(key => {
const func = sources[key];
if (typeof func !== 'function' || (Aigle[key] && !override)) {
return;
}
// check lodash chain
if (key === 'chain') {
const obj = func();
if (obj && obj.__chain__) {
Aigle.chain = _resolve;
Aigle.prototype.value = function() {
return this;
};
return;
}
}
const Proxy = createProxy(func, promisify);
Aigle[key] = function(value, arg1, arg2, arg3) {
return new Proxy(value, arg1, arg2, arg3)._execute();
};
Aigle.prototype[key] = function(arg1, arg2, arg3) {
return addProxy(this, Proxy, arg1, arg2, arg3);
};
});
return Aigle;
}
|
javascript
|
{
"resource": ""
}
|
q47678
|
baseGet
|
train
|
function baseGet (coll, path) {
return (path || []).reduce((curr, key) => {
if (!curr) { return }
return curr[key]
}, coll)
}
|
javascript
|
{
"resource": ""
}
|
q47679
|
train
|
function (number, model) {
if (_.isNull(number) || _.isUndefined(number)) return '';
number = parseFloat(number).toFixed(~~this.decimals);
var parts = number.split('.');
var integerPart = parts[0];
var decimalPart = parts[1] ? (this.decimalSeparator || '.') + parts[1] : '';
return integerPart.replace(this.HUMANIZED_NUM_RE, '$1' + this.orderSeparator) + decimalPart;
}
|
javascript
|
{
"resource": ""
}
|
|
q47680
|
train
|
function (rawData, model) {
if (_.isNull(rawData) || _.isUndefined(rawData)) return '';
return this._convert(rawData);
}
|
javascript
|
{
"resource": ""
}
|
|
q47681
|
train
|
function () {
if (!this.has("label")) {
this.set({ label: this.get("name") }, { silent: true });
}
var headerCell = Backgrid.resolveNameToClass(this.get("headerCell"), "HeaderCell");
var cell = Backgrid.resolveNameToClass(this.get("cell"), "Cell");
this.set({cell: cell, headerCell: headerCell}, { silent: true });
}
|
javascript
|
{
"resource": ""
}
|
|
q47682
|
train
|
function () {
var sortValue = this.get("sortValue");
if (_.isString(sortValue)) return this[sortValue];
else if (_.isFunction(sortValue)) return sortValue;
return function (model, colName) {
return model.get(colName);
};
}
|
javascript
|
{
"resource": ""
}
|
|
q47683
|
loadData
|
train
|
function loadData (settings = {}, json = data) {
const dataSet = new DataSet(json, settings)
dataSet.processData()
return dataSet
}
|
javascript
|
{
"resource": ""
}
|
q47684
|
responseHandler
|
train
|
function responseHandler(resp) {
// Set response var to the response we got back
// This is so it remains accessable outside this scope
response = resp;
// Check for redirect
// @TODO Prevent looped redirects
if (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) {
// Change URL to the redirect location
settings.url = response.headers.location;
var url = Url.parse(settings.url);
// Set host var in case it's used later
host = url.hostname;
// Options for the new request
var newOptions = {
hostname: url.hostname,
port: url.port,
path: url.path,
method: response.statusCode === 303 ? "GET" : settings.method,
headers: headers,
withCredentials: self.withCredentials
};
// Issue the new request
request = doRequest(newOptions, responseHandler).on("error", errorHandler);
request.end();
// @TODO Check if an XHR event needs to be fired here
return;
}
response.setEncoding("utf8");
setState(self.HEADERS_RECEIVED);
self.status = response.statusCode;
response.on("data", function(chunk) {
// Make sure there's some data
if (chunk) {
self.responseText += chunk;
}
// Don't emit state changes if the connection has been aborted.
if (sendFlag) {
setState(self.LOADING);
}
});
response.on("end", function() {
if (sendFlag) {
// Discard the end event if the connection has been aborted
setState(self.DONE);
sendFlag = false;
}
});
response.on("error", function(error) {
self.handleError(error);
});
}
|
javascript
|
{
"resource": ""
}
|
q47685
|
_process
|
train
|
async function _process(args, { fetch }) {
const url = args[0]
try {
const res = await fetch(`https://noembed.com/embed?url=${url}`)
return await res.json()
} catch (e) {
return {
html: url
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47686
|
combineEmbedsText
|
train
|
function combineEmbedsText(embeds) {
return embeds
.sort((a, b) => a.index - b.index)
.map(({ content }) => content)
.join(" ")
}
|
javascript
|
{
"resource": ""
}
|
q47687
|
formatData
|
train
|
function formatData({ snippet, id }) {
return {
title: snippet.title,
thumbnail: snippet.thumbnails.medium.url,
description: snippet.description,
url: `${baseUrl}watch?v=${id}`,
embedUrl: `${baseUrl}embed/${id}`
}
}
|
javascript
|
{
"resource": ""
}
|
q47688
|
fetchDetails
|
train
|
async function fetchDetails(id, fetch, gAuthKey) {
try {
const res = await fetch(
`https://www.googleapis.com/youtube/v3/videos?id=${id}&key=${gAuthKey}&part=snippet,statistics`
)
const data = await res.json()
return data.items[0]
} catch (e) {
console.log(e)
return {}
}
}
|
javascript
|
{
"resource": ""
}
|
q47689
|
onLoad
|
train
|
function onLoad({ input }, { clickClass, onVideoShow, height }) {
if (!isDom(input)) {
throw new Error("input should be a DOM Element.")
}
let classes = document.getElementsByClassName(clickClass)
for (let i = 0; i < classes.length; i++) {
classes[i].onclick = function() {
let url = this.getAttribute("data-url")
onVideoShow(url)
url += "?autoplay=1"
this.parentNode.innerHTML = withoutDetailsTemplate(url, height, id)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47690
|
_process
|
train
|
async function _process(
args,
{ fetch },
{
_omitScript,
maxWidth,
hideMedia,
hideThread,
align,
lang,
theme,
linkColor,
widgetType
}
) {
const params = {
url: args[0],
omitScript: _omitScript,
maxWidth,
hideMedia,
hideThread,
align,
lang,
theme,
linkColor,
widgetType
}
try {
const apiUrl = `https://api.twitter.com/1/statuses/oembed.json?${getQuery(
params
)}`
const res = await (isBrowser ? jsonp : fetch)(apiUrl)
return await res.json()
} catch (e) {
return {
html: ""
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47691
|
isMatchPresent
|
train
|
function isMatchPresent(regex, text, test = false) {
return test ? regex.test(text) : text.match(regex)
}
|
javascript
|
{
"resource": ""
}
|
q47692
|
isAnchorTagApplied
|
train
|
function isAnchorTagApplied({ result, plugins = [] }, { regex }) {
return (
getAnchorRegex(regex).test(result) ||
plugins.filter(plugin => plugin.id === "url").length
)
}
|
javascript
|
{
"resource": ""
}
|
q47693
|
saveEmbedData
|
train
|
async function saveEmbedData(opts, pluginOptions) {
const { regex } = pluginOptions
let options = extend({}, opts)
if (isAnchorTagApplied(options, { regex })) {
await stringReplaceAsync(
options.result,
anchorRegex,
async (match, url, index) => {
if (!isMatchPresent(regex, match, true)) return match
saveServiceName(options, pluginOptions, match)
options = await pushEmbedContent(url, options, pluginOptions, index)
return match
}
)
} else {
options = pushEmbedContent(options.result, options, pluginOptions)
}
return options
}
|
javascript
|
{
"resource": ""
}
|
q47694
|
train
|
function ( freq, endFreq ) {
var sum = 0;
if ( endFreq !== undefined ) {
for ( var i = freq; i <= endFreq; i++ ) {
sum += this.getSpectrum()[ i ];
}
return sum / ( endFreq - freq + 1 );
} else {
return this.getSpectrum()[ freq ];
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47695
|
train
|
function ( source ) {
var _this = this;
this.path = source ? source.src : this.path;
this.isLoaded = false;
this.progress = 0;
!window.soundManager && !smLoading && loadSM.call( this );
if ( window.soundManager ) {
this.audio = soundManager.createSound({
id : 'dancer' + Math.random() + '',
url : this.path,
stream : true,
autoPlay : false,
autoLoad : true,
whileplaying : function () {
_this.update();
},
whileloading : function () {
_this.progress = this.bytesLoaded / this.bytesTotal;
},
onload : function () {
_this.fft = new FFT( SAMPLE_SIZE, SAMPLE_RATE );
_this.signal = new Float32Array( SAMPLE_SIZE );
_this.waveform = new Float32Array( SAMPLE_SIZE );
_this.isLoaded = true;
_this.progress = 1;
_this.dancer.trigger( 'loaded' );
}
});
this.dancer.audio = this.audio;
}
// Returns audio if SM already loaded -- otherwise,
// sets dancer instance's audio property after load
return this.audio;
}
|
javascript
|
{
"resource": ""
}
|
|
q47696
|
FFT
|
train
|
function FFT(bufferSize, sampleRate) {
FourierTransform.call(this, bufferSize, sampleRate);
this.reverseTable = new Uint32Array(bufferSize);
var limit = 1;
var bit = bufferSize >> 1;
var i;
while (limit < bufferSize) {
for (i = 0; i < limit; i++) {
this.reverseTable[i + limit] = this.reverseTable[i] + bit;
}
limit = limit << 1;
bit = bit >> 1;
}
this.sinTable = new Float32Array(bufferSize);
this.cosTable = new Float32Array(bufferSize);
for (i = 0; i < bufferSize; i++) {
this.sinTable[i] = Math.sin(-Math.PI/i);
this.cosTable[i] = Math.cos(-Math.PI/i);
}
}
|
javascript
|
{
"resource": ""
}
|
q47697
|
train
|
function(name){
var obj = -1;
try{
obj = new ActiveXObject(name);
}catch(err){
obj = {activeXError:true};
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q47698
|
train
|
function(str){
var descParts = str.split(/ +/);
var majorMinor = descParts[2].split(/\./);
var revisionStr = descParts[3];
return {
"raw":str,
"major":parseInt(majorMinor[0], 10),
"minor":parseInt(majorMinor[1], 10),
"revisionStr":revisionStr,
"revision":parseRevisionStrToInt(revisionStr)
};
}
|
javascript
|
{
"resource": ""
}
|
|
q47699
|
createParticleBuffers
|
train
|
function createParticleBuffers ( geometry ) {
geometry.__webglVertexBuffer = _gl.createBuffer();
geometry.__webglColorBuffer = _gl.createBuffer();
_this.info.geometries ++;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.