_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q50700
|
nonRecord
|
train
|
function nonRecord(buffer, variable) {
// variable type
const type = types.str2num(variable.type);
// size of the data
var size = variable.size / types.num2bytes(type);
// iterates over the data
var data = new Array(size);
for (var i = 0; i < size; i++) {
data[i] = types.readType(buffer, type, 1);
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
q50701
|
record
|
train
|
function record(buffer, variable, recordDimension) {
// variable type
const type = types.str2num(variable.type);
const width = variable.size ? variable.size / types.num2bytes(type) : 1;
// size of the data
// TODO streaming data
var size = recordDimension.length;
// iterates over the data
var data = new Array(size);
const step = recordDimension.recordStep;
for (var i = 0; i < size; i++) {
var currentOffset = buffer.offset;
data[i] = types.readType(buffer, type, width);
buffer.seek(currentOffset + step);
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
q50702
|
header
|
train
|
function header(buffer, version) {
// Length of record dimension
// sum of the varSize's of all the record variables.
var header = { recordDimension: { length: buffer.readUint32() } };
// Version
header.version = version;
// List of dimensions
var dimList = dimensionsList(buffer);
header.recordDimension.id = dimList.recordId; // id of the unlimited dimension
header.recordDimension.name = dimList.recordName; // name of the unlimited dimension
header.dimensions = dimList.dimensions;
// List of global attributes
header.globalAttributes = attributesList(buffer);
// List of variables
var variables = variablesList(buffer, dimList.recordId, version);
header.variables = variables.variables;
header.recordDimension.recordStep = variables.recordStep;
return header;
}
|
javascript
|
{
"resource": ""
}
|
q50703
|
dimensionsList
|
train
|
function dimensionsList(buffer) {
var recordId, recordName;
const dimList = buffer.readUint32();
if (dimList === ZERO) {
utils.notNetcdf((buffer.readUint32() !== ZERO), 'wrong empty tag for list of dimensions');
return [];
} else {
utils.notNetcdf((dimList !== NC_DIMENSION), 'wrong tag for list of dimensions');
// Length of dimensions
const dimensionSize = buffer.readUint32();
var dimensions = new Array(dimensionSize);
for (var dim = 0; dim < dimensionSize; dim++) {
// Read name
var name = utils.readName(buffer);
// Read dimension size
const size = buffer.readUint32();
if (size === NC_UNLIMITED) { // in netcdf 3 one field can be of size unlimmited
recordId = dim;
recordName = name;
}
dimensions[dim] = {
name: name,
size: size
};
}
}
return {
dimensions: dimensions,
recordId: recordId,
recordName: recordName
};
}
|
javascript
|
{
"resource": ""
}
|
q50704
|
attributesList
|
train
|
function attributesList(buffer) {
const gAttList = buffer.readUint32();
if (gAttList === ZERO) {
utils.notNetcdf((buffer.readUint32() !== ZERO), 'wrong empty tag for list of attributes');
return [];
} else {
utils.notNetcdf((gAttList !== NC_ATTRIBUTE), 'wrong tag for list of attributes');
// Length of attributes
const attributeSize = buffer.readUint32();
var attributes = new Array(attributeSize);
for (var gAtt = 0; gAtt < attributeSize; gAtt++) {
// Read name
var name = utils.readName(buffer);
// Read type
var type = buffer.readUint32();
utils.notNetcdf(((type < 1) || (type > 6)), `non valid type ${type}`);
// Read attribute
var size = buffer.readUint32();
var value = types.readType(buffer, type, size);
// Apply padding
utils.padding(buffer);
attributes[gAtt] = {
name: name,
type: types.num2str(type),
value: value
};
}
}
return attributes;
}
|
javascript
|
{
"resource": ""
}
|
q50705
|
variablesList
|
train
|
function variablesList(buffer, recordId, version) {
const varList = buffer.readUint32();
var recordStep = 0;
if (varList === ZERO) {
utils.notNetcdf((buffer.readUint32() !== ZERO), 'wrong empty tag for list of variables');
return [];
} else {
utils.notNetcdf((varList !== NC_VARIABLE), 'wrong tag for list of variables');
// Length of variables
const variableSize = buffer.readUint32();
var variables = new Array(variableSize);
for (var v = 0; v < variableSize; v++) {
// Read name
var name = utils.readName(buffer);
// Read dimensionality of the variable
const dimensionality = buffer.readUint32();
// Index into the list of dimensions
var dimensionsIds = new Array(dimensionality);
for (var dim = 0; dim < dimensionality; dim++) {
dimensionsIds[dim] = buffer.readUint32();
}
// Read variables size
var attributes = attributesList(buffer);
// Read type
var type = buffer.readUint32();
utils.notNetcdf(((type < 1) && (type > 6)), `non valid type ${type}`);
// Read variable size
// The 32-bit varSize field is not large enough to contain the size of variables that require
// more than 2^32 - 4 bytes, so 2^32 - 1 is used in the varSize field for such variables.
const varSize = buffer.readUint32();
// Read offset
var offset = buffer.readUint32();
if (version === 2) {
utils.notNetcdf((offset > 0), 'offsets larger than 4GB not supported');
offset = buffer.readUint32();
}
let record = false;
// Count amount of record variables
if ((typeof recordId !== 'undefined') && (dimensionsIds[0] === recordId)) {
recordStep += varSize;
record = true;
}
variables[v] = {
name: name,
dimensions: dimensionsIds,
attributes,
type: types.num2str(type),
size: varSize,
offset,
record
};
}
}
return {
variables: variables,
recordStep: recordStep
};
}
|
javascript
|
{
"resource": ""
}
|
q50706
|
num2str
|
train
|
function num2str(type) {
switch (Number(type)) {
case types.BYTE:
return 'byte';
case types.CHAR:
return 'char';
case types.SHORT:
return 'short';
case types.INT:
return 'int';
case types.FLOAT:
return 'float';
case types.DOUBLE:
return 'double';
/* istanbul ignore next */
default:
return 'undefined';
}
}
|
javascript
|
{
"resource": ""
}
|
q50707
|
str2num
|
train
|
function str2num(type) {
switch (String(type)) {
case 'byte':
return types.BYTE;
case 'char':
return types.CHAR;
case 'short':
return types.SHORT;
case 'int':
return types.INT;
case 'float':
return types.FLOAT;
case 'double':
return types.DOUBLE;
/* istanbul ignore next */
default:
return -1;
}
}
|
javascript
|
{
"resource": ""
}
|
q50708
|
readNumber
|
train
|
function readNumber(size, bufferReader) {
if (size !== 1) {
var numbers = new Array(size);
for (var i = 0; i < size; i++) {
numbers[i] = bufferReader();
}
return numbers;
} else {
return bufferReader();
}
}
|
javascript
|
{
"resource": ""
}
|
q50709
|
readType
|
train
|
function readType(buffer, type, size) {
switch (type) {
case types.BYTE:
return buffer.readBytes(size);
case types.CHAR:
return trimNull(buffer.readChars(size));
case types.SHORT:
return readNumber(size, buffer.readInt16.bind(buffer));
case types.INT:
return readNumber(size, buffer.readInt32.bind(buffer));
case types.FLOAT:
return readNumber(size, buffer.readFloat32.bind(buffer));
case types.DOUBLE:
return readNumber(size, buffer.readFloat64.bind(buffer));
/* istanbul ignore next */
default:
notNetcdf(true, `non valid type ${type}`);
return undefined;
}
}
|
javascript
|
{
"resource": ""
}
|
q50710
|
trimNull
|
train
|
function trimNull(value) {
if (value.charCodeAt(value.length - 1) === 0) {
return value.substring(0, value.length - 1);
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q50711
|
readName
|
train
|
function readName(buffer) {
// Read name
var nameLength = buffer.readUint32();
var name = buffer.readChars(nameLength);
// validate name
// TODO
// Apply padding
padding(buffer);
return name;
}
|
javascript
|
{
"resource": ""
}
|
q50712
|
exif2css
|
train
|
function exif2css(orientation) {
const s = `${orientation}`
const transforms = transformsMap[s]
const transform = expandTransform(transforms)
const transformOrigin = transformOriginMap[s]
const allTransforms = expandTransforms(transforms)
const allTransformStrings = expandTransformStrings(transforms)
const css = {}
if (transform) {
css['transform'] = transform
}
if (transformOrigin) {
css['transform-origin'] = transformOrigin
}
if (allTransforms) {
css['transforms'] = allTransforms
}
if (allTransformStrings) {
css['transformStrings'] = allTransformStrings
}
return css
}
|
javascript
|
{
"resource": ""
}
|
q50713
|
defaultMockFilename
|
train
|
function defaultMockFilename(config, req) {
var reqData = prismUtils.filterUrl(config, req.url);
// include request body in hash
if (config.hashFullRequest(config, req)) {
reqData = req.body + reqData;
}
var shasum = crypto.createHash('sha1');
shasum.update(reqData);
return shasum.digest('hex') + '.json';
}
|
javascript
|
{
"resource": ""
}
|
q50714
|
isExternalLinkTarget
|
train
|
function isExternalLinkTarget(target) {
return target === "_blank" ||
(target === "_parent" && window.parent !== window.self) ||
(target === "_top" && window.top !== window.self) ||
(typeof target === "string" && target !== "_self");
}
|
javascript
|
{
"resource": ""
}
|
q50715
|
train
|
function(escape) {
var pairs = this.pairs;
var type = this.type;
var names = Object.keys(pairs);
var html = "";
var escapeHtml = escape || IDENTITY;
var name;
var computedType;
for (var i = 0, len = names.length; i < len; i++) {
name = names[i];
computedType = typeof type === "function" ? type(name) : type;
html += asHtml(computedType, name, escapeHtml(pairs[name]));
}
return html;
}
|
javascript
|
{
"resource": ""
}
|
|
q50716
|
addIntegerSeparators
|
train
|
function addIntegerSeparators(x, separator) {
x += '';
if (!separator) return x;
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x)) {
x = x.replace(rgx, '$1' + separator + '$2');
}
return x;
}
|
javascript
|
{
"resource": ""
}
|
q50717
|
addDecimalSeparators
|
train
|
function addDecimalSeparators(x, separator) {
x += '';
if (!separator) return x;
var rgx = /(\d{3})(\d+)/;
while (rgx.test(x)) {
x = x.replace(rgx, '$1' + separator + '$2');
}
return x;
}
|
javascript
|
{
"resource": ""
}
|
q50718
|
padLeft
|
train
|
function padLeft(x, padding) {
x = x + '';
var buf = [];
while (buf.length + x.length < padding) {
buf.push('0');
}
return buf.join('') + x;
}
|
javascript
|
{
"resource": ""
}
|
q50719
|
padRight
|
train
|
function padRight(x, padding) {
if (x) {
x += '';
} else {
x = '';
}
var buf = [];
while (buf.length + x.length < padding) {
buf.push('0');
}
return x + buf.join('');
}
|
javascript
|
{
"resource": ""
}
|
q50720
|
schematize
|
train
|
function schematize(content, name) {
return content
.replace(new RegExp(`${name}`, 'g'), '<%= dasherize(name) %>', 'g')
.replace(new RegExp(`${classify(name)}`, 'g'), '<%= classify(name) %>', 'g')
.replace(new RegExp(`${camelize(name)}`, 'g'), '<%= camelize(name) %>', 'g')
.replace(new RegExp(`${classify(name)}`, 'g'), '<%= classify(name) %>', 'g');
}
|
javascript
|
{
"resource": ""
}
|
q50721
|
setSearchTerm
|
train
|
function setSearchTerm(searchTerm, currentParams) {
let newParams = {
...currentParams,
page: undefined, //set page undefined to return the table to page 1
searchTerm: searchTerm === defaults.searchTerm ? undefined : searchTerm
};
setNewParams(newParams);
updateSearch(searchTerm);
onlyOneFilter && clearFilters();
}
|
javascript
|
{
"resource": ""
}
|
q50722
|
cleanupFilter
|
train
|
function cleanupFilter(filter) {
let filterToUse = filter;
if (
filterToUse.selectedFilter === "inList" &&
typeof filterToUse.filterValue === "number"
) {
filterToUse = {
...filterToUse,
filterValue: filterToUse.filterValue.toString()
};
}
if (filterToUse.selectedFilter === "inList") {
filterToUse = {
...filterToUse,
filterValue: filterToUse.filterValue.replace(/, |,/g, ".")
};
}
return filterToUse;
}
|
javascript
|
{
"resource": ""
}
|
q50723
|
processTag
|
train
|
function processTag(tag, targets) {
if (tag.description) {
tag.description = replaceLink(tag.description, targets);
}
if (tag.params) {
tag.params.forEach(function (param) {
if (param.description) {
param.description = replaceLink(param.description, targets);
}
});
}
if (tag.members) {
tag.members.forEach(function (member) {
processTag(member, targets);
});
}
if (tag.methods) {
tag.methods.forEach(function (method) {
processTag(method, targets);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q50724
|
setPipedTypesString
|
train
|
function setPipedTypesString(node) {
if (!node.type) { return ''; }
node.typesString = node.type.names.join(' | ');
}
|
javascript
|
{
"resource": ""
}
|
q50725
|
addListenersToStream
|
train
|
function addListenersToStream(listeners, stream) {
var evt, callback;
if (listeners) {
for (evt in listeners) {
if (listeners.hasOwnProperty(evt)) {
callback = listeners[evt];
stream.on(evt, callback);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q50726
|
chain
|
train
|
function chain(a, b) {
var prop, descriptor = {};
for (prop in a) {
if (a.hasOwnProperty(prop)) {
descriptor[prop] = Object.getOwnPropertyDescriptor(a, prop);
}
}
return Object.create(b, descriptor);
}
|
javascript
|
{
"resource": ""
}
|
q50727
|
getRootCerts
|
train
|
function getRootCerts(callback) {
return request(certUrl, function(err, res, body) {
if (err) return callback(err);
// Delete preprocesor macros
body = body.replace(/#[^\n]+/g, '');
// Delete the trailing comma
body = body.replace(/,\s*$/, '');
// Make sure each C string is concatenated
body = body.replace(/"\r?\n"/g, '');
// Make sue we turn the cert names into property names
body = body.replace(/\/\*([^*]+)\*\/\n(?=")/g, function(_, name) {
var key = name.trim();
return '"' + key + '":\n';
});
// Delete Comments
body = body.replace(/\/\* tools\/\.\.\/src[^\0]+?\*\//, '');
body = body.replace(/\/\* @\(#\)[^\n]+/, '');
// \xff -> \u00ff
body = body.replace(/\\x([0-9a-fA-F]{2})/g, '\\u00$1');
// Trim Whitespace
body = body.trim();
// Wrap into a JSON Object
body = '{\n' + body + '\n}\n';
// Ensure JSON parses properly
try {
body = JSON.stringify(JSON.parse(body), null, 2);
} catch (e) {
return callback(e);
}
return callback(null, body);
});
}
|
javascript
|
{
"resource": ""
}
|
q50728
|
interpretTwoDigitYear
|
train
|
function interpretTwoDigitYear(year) {
const thisYear = new Date().getFullYear();
const thisCentury = thisYear - (thisYear % 100);
const centuries = [thisCentury, thisCentury - 100, thisCentury + 100].sort(function(a, b) {
return Math.abs(thisYear - (year + a)) - Math.abs(thisYear - (year + b));
});
return year + centuries[0];
}
|
javascript
|
{
"resource": ""
}
|
q50729
|
get
|
train
|
function get(object, key, ...args) {
if (object) {
const value = object[key];
if (typeof value === 'function') {
return value(...args);
} else {
return value;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q50730
|
setContainerProperties
|
train
|
function setContainerProperties(blobSvc, options, result, callback) {
blobSvc.getServiceProperties(function(error, result, response) {
if (error) {
return callback(error);
}
var serviceProperties = result;
var allowedOrigins = options.allowedOrigins || ['*'];
var allowedMethods = options.allowedMethods || ['GET', 'PUT', 'POST'];
var allowedHeaders = options.allowedHeaders || ['*'];
var exposedHeaders = options.exposedHeaders || ['*'];
var maxAgeInSeconds = options.maxAgeInSeconds || DEFAULT_MAX_AGE_IN_SECONDS;
serviceProperties.Cors = {
CorsRule: [
{
AllowedOrigins: allowedOrigins,
AllowedMethods: allowedMethods,
AllowedHeaders: allowedHeaders,
ExposedHeaders: exposedHeaders,
MaxAgeInSeconds: maxAgeInSeconds
}
]
};
blobSvc.setServiceProperties(serviceProperties, function(error, result, response) {
if (error) {
return callback(error);
}
return callback(null, blobSvc);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q50731
|
initializeContainer
|
train
|
function initializeContainer(blobSvc, container, options, callback) {
blobSvc.setContainerAcl(container, null, { publicAccessLevel: 'container' }, function(error, result, response) {
if (error) {
return callback(error);
}
return setContainerProperties(blobSvc, options, result, callback);
});
}
|
javascript
|
{
"resource": ""
}
|
q50732
|
createContainer
|
train
|
function createContainer(cluster, options, callback) {
var blobSvc = azure.createBlobService(cluster.account, cluster.key);
var container = cluster.container || options.container;
blobSvc.createContainerIfNotExists(container, function(error, result, response) {
if (error) {
return callback(error);
}
return initializeContainer(blobSvc, container, options, callback);
});
}
|
javascript
|
{
"resource": ""
}
|
q50733
|
createContainerBlob
|
train
|
function createContainerBlob(blob, path, localPath, _gzip, callback) {
// Draw the extension from uploadfs, where we know they will be using
// reasonable extensions, not from what could be a temporary file
// that came from the gzip code. -Tom
var extension = extname(path).substring(1);
var contentSettings = {
cacheControl: `max-age=${DEFAULT_MAX_CACHE}, public`,
// contentEncoding: _gzip ? 'gzip' : 'deflate',
contentType: contentTypes[extension] || 'application/octet-stream'
};
if (_gzip) {
contentSettings.contentEncoding = 'gzip';
}
blob.svc.createBlockBlobFromLocalFile(
blob.container,
path,
localPath,
{
contentSettings: contentSettings
},
function(error, result, response) {
return callback(error);
}
);
}
|
javascript
|
{
"resource": ""
}
|
q50734
|
removeContainerBlob
|
train
|
function removeContainerBlob(blob, path, callback) {
blob.svc.deleteBlobIfExists(blob.container, path, function(error, result, response) {
if (error) {
__log('Cannot delete ' + path + 'on container ' + blob.container);
}
return callback(error);
});
}
|
javascript
|
{
"resource": ""
}
|
q50735
|
train
|
function(gzipEncoding) {
var gzipSettings = gzipEncoding || {};
var { whitelist, blacklist } = Object.keys(gzipSettings).reduce((prev, key) => {
if (gzipSettings[key]) {
prev['whitelist'].push(key);
} else {
prev['blacklist'].push(key);
}
return prev;
}, { whitelist: [], blacklist: [] });
// @NOTE - we REMOVE whitelisted types from the blacklist array
var gzipBlacklist = defaultGzipBlacklist.concat(blacklist).filter(el => whitelist.indexOf(el));
return _.uniq(gzipBlacklist);
}
|
javascript
|
{
"resource": ""
}
|
|
q50736
|
some
|
train
|
function some(array, predict) {
for (let i = 0; i < array.length; i++) {
if (predict(array[i])) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q50737
|
train
|
function(path, disabledFileKey) {
var hmac = crypto.createHmac('sha256', disabledFileKey);
hmac.update(path);
var disabledPath = path + '-disabled-' + hmac.digest('hex');
return disabledPath;
}
|
javascript
|
{
"resource": ""
}
|
|
q50738
|
train
|
function (callback) {
if (!imageSizes.length) {
return callback();
}
tempPath = options.tempPath;
if (!fs.existsSync(options.tempPath)) {
fs.mkdirSync(options.tempPath);
}
return callback(null);
}
|
javascript
|
{
"resource": ""
}
|
|
q50739
|
train
|
function (callback) {
if (!self._image) {
var paths = (process.env.PATH || '').split(delimiter);
if (!_.find(paths, function(p) {
if (fs.existsSync(p + '/imagecrunch')) {
self._image = require('./lib/image/imagecrunch.js')();
return true;
}
// Allow for Windows and Unix filenames for identify. Silly oversight
// after getting delimiter right (:
if (fs.existsSync(p + '/identify') || fs.existsSync(p + '/identify.exe')) {
self._image = require('./lib/image/imagemagick.js')();
return true;
}
})) {
// Fall back to jimp, no need for an error
self._image = require('./lib/image/jimp.js')();
}
}
return callback(null);
}
|
javascript
|
{
"resource": ""
}
|
|
q50740
|
identify
|
train
|
function identify(path, callback) {
return self.identifyLocalImage(path, function(err, info) {
if (err) {
return callback(err);
}
context.info = info;
context.extension = info.extension;
return callback(null);
});
}
|
javascript
|
{
"resource": ""
}
|
q50741
|
train
|
function (callback) {
// Name the destination folder
context.tempName = generateId();
// Create destination folder
if (imageSizes.length) {
context.tempFolder = tempPath + '/' + context.tempName;
return fs.mkdir(context.tempFolder, callback);
} else {
return callback(null);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50742
|
train
|
function (callback) {
context.basePath = path.replace(/\.\w+$/, '');
context.workingPath = localPath;
// Indulge their wild claims about the extension the original
// should have if any, otherwise provide the truth from identify
if (path.match(/\.\w+$/)) {
originalPath = path;
} else {
originalPath = path + '.' + context.extension;
}
return callback(null);
}
|
javascript
|
{
"resource": ""
}
|
|
q50743
|
train
|
function(callback) {
if (!context.copyOriginal) {
return callback(null);
}
var suffix = 'original.' + context.extension;
var tempFile = context.tempFolder + '/' + suffix;
if (context.extension !== 'jpg') {
// Don't forget to tell the caller that we did the work,
// even if it was just a copy
context.adjustedOriginal = tempFile;
return copyFile(context.workingPath, tempFile, callback);
}
var args = [ context.workingPath ];
if (context.crop) {
args.push('-crop');
args.push(context.crop.left);
args.push(context.crop.top);
args.push(context.crop.width);
args.push(context.crop.height);
}
args.push('-write');
args.push(tempFile);
context.adjustedOriginal = tempFile;
var proc = childProcess.spawn('imagecrunch', args);
proc.on('close', function(code) {
if (code !== 0) {
return callback(code);
}
return callback(null);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q50744
|
mapValueCast
|
train
|
function mapValueCast (value) {
index++
parameters.push(inputValue(value))
let cast = ''
if (Buffer.isBuffer(value))
cast = '::bytea'
else if (typeof value === 'number' && value % 1 === 0)
cast = '::int'
return `$${index}${cast}`
}
|
javascript
|
{
"resource": ""
}
|
q50745
|
generateIndex
|
train
|
function generateIndex (playbook, pages) {
let siteUrl = playbook.site.url
if (!siteUrl) {
// Uses relative links when site URL is not set
siteUrl = '';
}
if (siteUrl.charAt(siteUrl.length - 1) === '/') siteUrl = siteUrl.substr(0, siteUrl.length - 1)
if (!pages.length) return {}
// Map of Lunr ref to document
const documentsStore = {}
const documents = pages.map((page) => {
const html = page.contents.toString()
const $ = cheerio.load(html)
const $h1 = $('h1')
const documentTitle = $h1.text()
$h1.remove()
const titles = []
$('h2,h3,h4,h5,h6').each(function () {
let $title = $(this)
// If the title does not have an Id then Lunr will throw a TypeError
// cannot read property 'text' of undefined.
if ($title.attr('id')) {
titles.push({
text: $title.text(),
id: $title.attr('id'),
})
}
$title.remove()
})
// HTML document as text
let text = $('article').text()
// Decode HTML
text = entities.decode(text)
// Strip HTML tags
text = text.replace(/(<([^>]+)>)/ig, '')
.replace(/\n/g, ' ')
.replace(/\r/g, ' ')
.replace(/\s+/g, ' ')
.trim()
return {
text: text,
title: documentTitle,
component: page.src.component,
version: page.src.version,
name: page.src.stem,
url: siteUrl + page.pub.url,
titles: titles, // TODO get title id to be able to use fragment identifier
}
})
const index = lunr(function () {
const self = this
self.ref('url')
self.field('title', {boost: 10})
self.field('name')
self.field('text')
self.field('component')
self.metadataWhitelist = ['position']
documents.forEach(function (doc) {
self.add(doc)
doc.titles.forEach(function (title) {
self.add({
title: title.text,
url: `${doc.url}#${title.id}`,
})
}, self)
}, self)
})
documents.forEach(function (doc) {
documentsStore[doc.url] = doc
})
return {
index: index,
store: documentsStore,
}
}
|
javascript
|
{
"resource": ""
}
|
q50746
|
_translate
|
train
|
function _translate(duration, ease = '', x = false) {
slidesDOMEl.style.cssText = getTranslationCSS(duration, ease, index, x)
}
|
javascript
|
{
"resource": ""
}
|
q50747
|
slide
|
train
|
function slide(direction) {
const movement = direction === true ? 1 : -1
let duration = slideSpeed
// calculate the nextIndex according to the movement
let nextIndex = index + 1 * movement
// nextIndex should be between 0 and items minus 1
nextIndex = clampNumber(nextIndex, 0, items - 1)
// if the nextIndex and the current is the same, we don't need to do the slide
if (nextIndex === index) return
// if the nextIndex is possible according to number of items, then use it
if (nextIndex <= items) {
// execute the callback from the options before sliding
doBeforeSlide({currentSlide: index, nextSlide: nextIndex})
// execute the internal callback
direction ? onNext(nextIndex) : onPrev(nextIndex)
index = nextIndex
}
// translate to the next index by a defined duration and ease function
_translate(duration, ease)
// execute the callback from the options after sliding
slidesDOMEl.addEventListener(TRANSITION_END, function cb(e) {
doAfterSlide({currentSlide: index})
e.currentTarget.removeEventListener(e.type, cb)
})
}
|
javascript
|
{
"resource": ""
}
|
q50748
|
_setup
|
train
|
function _setup() {
slidesDOMEl.addEventListener(TRANSITION_END, onTransitionEnd)
containerDOMEl.addEventListener('touchstart', onTouchstart, EVENT_OPTIONS)
containerDOMEl.addEventListener('touchmove', onTouchmove, EVENT_OPTIONS)
containerDOMEl.addEventListener('touchend', onTouchend, EVENT_OPTIONS)
if (index !== 0) {
_translate(0)
}
}
|
javascript
|
{
"resource": ""
}
|
q50749
|
train
|
function(options) {
return {
element: options.element,
name: 'Do not use ' + options.element + ' element',
message: 'Please remove the ' + options.element + ' element',
ruleUrl: options.ruleUrl,
level: options.level,
template: true,
callback: createGenericCallback(options.element)
};
}
|
javascript
|
{
"resource": ""
}
|
|
q50750
|
train
|
function(element) {
'use strict';
return function(dom, reporter) {
var that = this;
dom.$(element).each(function(index, item){
reporter.error(that.message, 0, that.name);
throw dom.$(item).parent().html();
});
};
}
|
javascript
|
{
"resource": ""
}
|
|
q50751
|
customLogic
|
train
|
function customLogic (os, name, file, cb) {
var logic = './logic/' + name + '.js'
try { require(logic)(os, file, cb) } catch (e) { cb(null, os) }
}
|
javascript
|
{
"resource": ""
}
|
q50752
|
RestrictedInput
|
train
|
function RestrictedInput(options) {
options = options || {};
if (!isValidElement(options.element)) {
throw new Error(constants.errors.INVALID_ELEMENT);
}
if (!options.pattern) {
throw new Error(constants.errors.PATTERN_MISSING);
}
if (!RestrictedInput.supportsFormatting()) {
this.strategy = new NoopStrategy(options);
} else if (device.isIos()) {
this.strategy = new IosStrategy(options);
} else if (device.isKitKatWebview()) {
this.strategy = new KitKatChromiumBasedWebViewStrategy(options);
} else if (device.isAndroidChrome()) {
this.strategy = new AndroidChromeStrategy(options);
} else if (device.isIE9()) {
this.strategy = new IE9Strategy(options);
} else {
this.strategy = new BaseStrategy(options);
}
}
|
javascript
|
{
"resource": ""
}
|
q50753
|
Sticky
|
train
|
function Sticky(head, title, toc, page, gradientBit) {
page.style.paddingTop = maxHeadHeight;
head.style.height = maxHeadHeight + "px";
var padding = minHeadPadding + ((maxHeadPadding - minHeadPadding) * ((maxHeadHeight - minHeadHeight) / (maxHeadHeight - minHeadHeight)));
head.style.padding = padding + "px 0px";
title.style.fontSize = (maxHeadHeight - (padding * 2)) * 0.7;
var pageScroll = Derivable.atom(window.scrollY);
var tocScroll = Derivable.atom(toc.scrollTop);
window.addEventListener('scroll', function () { pageScroll.set(window.scrollY); });
toc.addEventListener('scroll', function () { tocScroll.set(this.scrollTop); });
var headHeight = pageScroll.derive(function (scroll) {
return Math.max(maxHeadHeight - scroll, minHeadHeight);
});
headHeight.react(function (headHeight) {
spacer.style.height = headHeight + "px";
gradientBit.style.marginTop = headHeight + "px";
var scale = headHeight / maxHeadHeight;
head.style.transform = "scale("+scale+","+scale+")";
});
var gradientOpacity = tocScroll.derive(function (scroll) {
return Math.min(scroll / 20, 1);
});
gradientOpacity.react(function (opacity) {
gradientBit.style.opacity = opacity;
});
}
|
javascript
|
{
"resource": ""
}
|
q50754
|
cm2feetInches
|
train
|
function cm2feetInches (cm) {
const totalInches = (cm * 0.393701);
let feet = Math.floor(totalInches / 12);
let inches = Math.round(totalInches - (feet * 12));
if (inches === 12) {
feet += 1;
inches = 0;
}
return { feet, inches };
}
|
javascript
|
{
"resource": ""
}
|
q50755
|
PCRE
|
train
|
function PCRE (pattern, namedCaptures) {
pattern = String(pattern || '').trim();
var originalPattern = pattern;
var delim;
var flags = '';
// A delimiter can be any non-alphanumeric, non-backslash,
// non-whitespace character.
var hasDelim = /^[^a-zA-Z\\\s]/.test(pattern);
if (hasDelim) {
delim = pattern[0];
var lastDelimIndex = pattern.lastIndexOf(delim);
// pull out the flags in the pattern
flags += pattern.substring(lastDelimIndex + 1);
// strip the delims from the pattern
pattern = pattern.substring(1, lastDelimIndex);
}
// populate namedCaptures array and removed named captures from the `pattern`
var numGroups = 0;
pattern = replaceCaptureGroups(pattern, function (group) {
if (/^\(\?[P<']/.test(group)) {
// PCRE-style "named capture"
// It is possible to name a subpattern using the syntax (?P<name>pattern).
// This subpattern will then be indexed in the matches array by its normal
// numeric position and also by name. PHP 5.2.2 introduced two alternative
// syntaxes (?<name>pattern) and (?'name'pattern).
var match = /^\(\?P?[<']([^>']+)[>']/.exec(group);
var capture = group.substring(match[0].length, group.length - 1);
if (namedCaptures) {
namedCaptures[numGroups] = match[1];
}
numGroups++;
return '(' + capture + ')';
} else if ('(?:' === group.substring(0, 3)) {
// non-capture group, leave untouched
return group;
} else {
// regular capture, leave untouched
numGroups++;
return group;
}
});
// replace "character classes" with their raw RegExp equivalent
pattern = pattern.replace(/\[\:([^\:]+)\:\]/g, function (characterClass, name) {
return exports.characterClasses[name] || characterClass;
});
// TODO: convert PCRE-only flags to JS
// TODO: handle lots more stuff....
// http://www.php.net/manual/en/reference.pcre.pattern.syntax.php
var regexp = new RegExp(pattern, flags);
regexp.delimiter = delim;
regexp.pcrePattern = originalPattern;
regexp.pcreFlags = flags;
return regexp;
}
|
javascript
|
{
"resource": ""
}
|
q50756
|
replaceCaptureGroups
|
train
|
function replaceCaptureGroups (pattern, fn) {
var start;
var depth = 0;
var escaped = false;
for (var i = 0; i < pattern.length; i++) {
var cur = pattern[i];
if (escaped) {
// skip this letter, it's been escaped
escaped = false;
continue;
}
switch (cur) {
case '(':
// we're only interested in groups when the depth reaches 0
if (0 === depth) {
start = i;
}
depth++;
break;
case ')':
if (depth > 0) {
depth--;
// we're only interested in groups when the depth reaches 0
if (0 === depth) {
var end = i + 1;
var l = start === 0 ? '' : pattern.substring(0, start);
var r = pattern.substring(end);
var v = String(fn(pattern.substring(start, end)));
pattern = l + v + r;
i = start;
}
}
break;
case '\\':
escaped = true;
break;
}
}
return pattern;
}
|
javascript
|
{
"resource": ""
}
|
q50757
|
renderPick
|
train
|
function renderPick() {
if(checkContextLoss()) {
return
}
gl.colorMask(true, true, true, true)
gl.depthMask(true)
gl.disable(gl.BLEND)
gl.enable(gl.DEPTH_TEST)
var numObjs = objects.length
var numPick = pickBuffers.length
for(var j=0; j<numPick; ++j) {
var buf = pickBuffers[j]
buf.shape = pickShape
buf.begin()
for(var i=0; i<numObjs; ++i) {
if(pickBufferIds[i] !== j) {
continue
}
var obj = objects[i]
if(obj.drawPick) {
obj.pixelRatio = 1
obj.drawPick(cameraParams)
}
}
buf.end()
}
}
|
javascript
|
{
"resource": ""
}
|
q50758
|
walkDepthFirst
|
train
|
function walkDepthFirst (tree, visitor) {
const val = walkDepthFirstRecursive(tree, visitor)
if (val !== undefined) {
return val
} else {
return visitor(null)
}
}
|
javascript
|
{
"resource": ""
}
|
q50759
|
newPosId
|
train
|
function newPosId (p, f) {
const pPath = p && p[0]
const fPath = f && f[0]
let path
let uid
if (pPath && fPath && isSibling(pPath, fPath)) {
path = [pPath[0], pPath[1]]
if (f[1].length > p[1].length) {
const difference = f[1].substring(p[1].length)
uid = p[1] + halfOf(difference) + cuid()
} else {
uid = p[1] + cuid()
}
} else {
path = newPath(pPath, fPath)
uid = cuid()
}
return [path, uid]
}
|
javascript
|
{
"resource": ""
}
|
q50760
|
color
|
train
|
function color(c, group) {
if (c == null) c = Scatter.defaults.color;
c = _this3.updateColor(c);
hasColor++;
return c;
}
|
javascript
|
{
"resource": ""
}
|
q50761
|
marker
|
train
|
function marker(markers, group, options) {
var activation = group.activation; // reset marker elements
activation.forEach(function (buffer) {
return buffer && buffer.destroy && buffer.destroy();
});
activation.length = 0; // single sdf marker
if (!markers || typeof markers[0] === 'number') {
var id = _this3.addMarker(markers);
activation[id] = true;
} // per-point markers use mask buffers to enable markers in vert shader
else {
var markerMasks = [];
for (var _i = 0, l = Math.min(markers.length, group.count); _i < l; _i++) {
var _id = _this3.addMarker(markers[_i]);
if (!markerMasks[_id]) markerMasks[_id] = new Uint8Array(group.count); // enable marker by default
markerMasks[_id][_i] = 1;
}
for (var _id2 = 0; _id2 < markerMasks.length; _id2++) {
if (!markerMasks[_id2]) continue;
var opts = {
data: markerMasks[_id2],
type: 'uint8',
usage: 'static'
};
if (!activation[_id2]) {
activation[_id2] = regl.buffer(opts);
} else {
activation[_id2](opts);
}
activation[_id2].data = markerMasks[_id2];
}
}
return markers;
}
|
javascript
|
{
"resource": ""
}
|
q50762
|
jql
|
train
|
function jql(queryChunks, ...injects) {
try {
let res = '';
for (let i = 0; i < injects.length; i++) {
let value = injects[i];
let q = queryChunks[i];
if (typeof value === 'string') {
//make string value safe
value = cleanString(value);
}
else if (Array.isArray(value)) {
//We do not support nested arrays or objects
value = value.map((it) => {
if (Array.isArray(it))
throw new Error('JQL: Nested arrays not supported . Consider using a nativeFunction for that query instead.')
if (typeof it === 'string') {
//make string value safe
it = cleanString(it);
}
return it;
})
value = "(" + value.join(', ') + ")";
}
res += q + value;
}
res += queryChunks[queryChunks.length - 1];
//console.log('query:', res);
return res;
} catch (err) {
throw new Boom.badRequest('Bad JQL:', err)
}
}
|
javascript
|
{
"resource": ""
}
|
q50763
|
Ca
|
train
|
function Ca (A, B, M0, M1) {
this.A = A
this.B = B
this.M0 = M0
this.M1 = M1
}
|
javascript
|
{
"resource": ""
}
|
q50764
|
identifyRefsInSchemaFields
|
train
|
function identifyRefsInSchemaFields(structure, prefix) {
_.each(structure.schema, (fieldStructure, fieldName) => {
const name = prefix ? prefix + '.' + fieldName : fieldName;
//If field has a schema, then it is a collection
if (fieldStructure.schema) {
// is this an object or an array?
if (fieldStructure.meta && fieldStructure.meta.type === 'Array') {
//array
identifyRefsInSchemaFields(fieldStructure, name + '.*')
} else {
//object. loop through schema.fields
identifyRefsInSchemaFields(fieldStructure, name)
}
} else if (fieldStructure.meta && fieldStructure.meta.ref) {
//ref field found!
refFields[name] = 1;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q50765
|
train
|
function (str) {
return str.replace
(/(^[a-z]+)|[0-9]+|[A-Z][a-z]+|[A-Z]+(?=[A-Z][a-z]|[0-9])/g
, function (match, first) {
if (first) match = match[0].toUpperCase() + match.substr(1);
return match + ' ';
}
)
}
|
javascript
|
{
"resource": ""
}
|
|
q50766
|
modf
|
train
|
function modf (float) {
const i = Math.trunc(float)
const f = Math.abs(float - i)
return [i, f]
}
|
javascript
|
{
"resource": ""
}
|
q50767
|
round
|
train
|
function round (float, precision) {
precision = (precision === undefined ? 10 : precision)
return parseFloat(float.toFixed(precision), 10)
}
|
javascript
|
{
"resource": ""
}
|
q50768
|
_compatibility
|
train
|
function _compatibility (rs) {
const _rs = [rs.rise, rs.transit, rs.set]
_rs.rise = rs.rise
_rs.transit = rs.transit
_rs.set = rs.set
return _rs
}
|
javascript
|
{
"resource": ""
}
|
q50769
|
interpolate
|
train
|
function interpolate (dyear, data) {
const d3 = interp.len3ForInterpolateX(dyear,
data.first, data.last, data.table
)
return d3.interpolateX(dyear)
}
|
javascript
|
{
"resource": ""
}
|
q50770
|
interpolateData
|
train
|
function interpolateData (dyear, data) {
const [fyear, fmonth] = data.firstYM
const {year, month, first, last} = monthOfYear(dyear)
const pos = 12 * (year - fyear) + (month - fmonth)
const table = data.table.slice(pos, pos + 3)
const d3 = new interp.Len3(first, last, table)
return d3.interpolateX(dyear)
}
|
javascript
|
{
"resource": ""
}
|
q50771
|
monthOfYear
|
train
|
function monthOfYear (dyear) {
if (!monthOfYear.data) { // memoize yearly fractions per month
monthOfYear.data = {0: [], 1: []}
for (let m = 0; m <= 12; m++) {
monthOfYear.data[0][m] = new Calendar(1999, m, 1).toYear() - 1999 // non leap year
monthOfYear.data[1][m] = new Calendar(2000, m, 1).toYear() - 2000 // leap year
}
}
const year = dyear | 0
const f = dyear - year
const d = LeapYearGregorian(year) ? 1 : 0
const data = monthOfYear.data[d]
let month = 12 // TODO loop could be improved
while (month > 0 && data[month] > f) {
month--
}
const first = year + data[month]
const last = month < 11 ? year + data[month + 2] : year + 1 + data[(month + 2) % 12]
return {year, month, first, last}
}
|
javascript
|
{
"resource": ""
}
|
q50772
|
appendRecursively
|
train
|
function appendRecursively(formData, collection, parentkey, parentIsArray) {
//console.log(...arguments)
for (let k in collection) {
const val = collection[k];
if (val === undefined) continue;
if (val instanceof File) {
let mkey = (parentkey ? parentkey + '.' : '') + k;
// if(parentIsArray)
// mkey = parentkey
// else
// mkey = k
val.foo = 'bar'
formData.append(mkey, val)
}
else if (Array.isArray(val)) {
let mkey = '';
if (parentIsArray) {
mkey = parentkey; //parentKey can/should never be empty if parentISarray
} else {
mkey = (parentkey ? parentkey + '.' + k : k);
}
appendRecursively(formData, val, mkey, true);
}
else if (typeof val === 'object') {
let mkey = (parentkey ? parentkey + '.' : '') + k;
appendRecursively(formData, val, mkey, false);
}
else {
let mkey = (parentkey ? parentkey + '.' : '') + k;
formData.append(mkey, val)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q50773
|
snap
|
train
|
function snap (y, q) {
const k = (y - 2000) * 12.3685 // (49.2) p. 350
return Math.floor(k - q + 0.5) + q
}
|
javascript
|
{
"resource": ""
}
|
q50774
|
read
|
train
|
function read (value) {
if (value instanceof RegExp) {
var chars = source.slice(index)
var match = chars.match(value)
if (match) {
index += match[0].length
return match[0]
}
} else {
if (source.indexOf(value, index) === index) {
index += value.length
return value
}
}
}
|
javascript
|
{
"resource": ""
}
|
q50775
|
parse
|
train
|
function parse(string) {
var match = isoDateExpression.exec(string);
if (match) {
// parse months, days, hours, minutes, seconds, and milliseconds
// provide default values if necessary
// parse the UTC offset component
var year = $Number(match[1]),
month = $Number(match[2] || 1) - 1,
day = $Number(match[3] || 1) - 1,
hour = $Number(match[4] || 0),
minute = $Number(match[5] || 0),
second = $Number(match[6] || 0),
millisecond = Math.floor($Number(match[7] || 0) * 1000),
// When time zone is missed, local offset should be used
// (ES 5.1 bug)
// see https://bugs.ecmascript.org/show_bug.cgi?id=112
isLocalTime = Boolean(match[4] && !match[8]),
signOffset = match[9] === '-' ? 1 : -1,
hourOffset = $Number(match[10] || 0),
minuteOffset = $Number(match[11] || 0),
result;
var hasMinutesOrSecondsOrMilliseconds = minute > 0 || second > 0 || millisecond > 0;
if (
hour < (hasMinutesOrSecondsOrMilliseconds ? 24 : 25) &&
minute < 60 && second < 60 && millisecond < 1000 &&
month > -1 && month < 12 && hourOffset < 24 &&
minuteOffset < 60 && // detect invalid offsets
day > -1 &&
day < (dayFromMonth(year, month + 1) - dayFromMonth(year, month))
) {
result = (
(dayFromMonth(year, month) + day) * 24 +
hour +
hourOffset * signOffset
) * 60;
result = (
(result + minute + minuteOffset * signOffset) * 60 +
second
) * 1000 + millisecond;
if (isLocalTime) {
result = toUTC(result);
}
if (-8.64e15 <= result && result <= 8.64e15) {
return result;
}
}
return NaN;
}
return NativeDate.parse.apply(this, arguments);
}
|
javascript
|
{
"resource": ""
}
|
q50776
|
sameLength
|
train
|
function sameLength(a, b) {
return typeof a === typeof b &&
a && b &&
a.length === b.length;
}
|
javascript
|
{
"resource": ""
}
|
q50777
|
allSame
|
train
|
function allSame(arr) {
if (!check.array(arr)) {
return false;
}
if (!arr.length) {
return true;
}
var first = arr[0];
return arr.every(function (item) {
return item === first;
});
}
|
javascript
|
{
"resource": ""
}
|
q50778
|
oneOf
|
train
|
function oneOf(arr, x) {
check.verify.array(arr, 'expected an array');
return arr.indexOf(x) !== -1;
}
|
javascript
|
{
"resource": ""
}
|
q50779
|
has
|
train
|
function has(o, property) {
if (arguments.length !== 2) {
throw new Error('Expected two arguments to check.has, got only ' + arguments.length);
}
return Boolean(o && property &&
typeof property === 'string' &&
typeof o[property] !== 'undefined');
}
|
javascript
|
{
"resource": ""
}
|
q50780
|
badItems
|
train
|
function badItems(rule, a) {
check.verify.array(a, 'expected array to find bad items');
return a.filter(notModifier(rule));
}
|
javascript
|
{
"resource": ""
}
|
q50781
|
arrayOfStrings
|
train
|
function arrayOfStrings(a, checkLowerCase) {
var v = check.array(a) && a.every(check.string);
if (v && check.bool(checkLowerCase) && checkLowerCase) {
return a.every(check.lowerCase);
}
return v;
}
|
javascript
|
{
"resource": ""
}
|
q50782
|
arrayOfArraysOfStrings
|
train
|
function arrayOfArraysOfStrings(a, checkLowerCase) {
return check.array(a) && a.every(function (arr) {
return check.arrayOfStrings(arr, checkLowerCase);
});
}
|
javascript
|
{
"resource": ""
}
|
q50783
|
all
|
train
|
function all(obj, predicates) {
check.verify.fn(check.every, 'missing check.every method');
check.verify.fn(check.map, 'missing check.map method');
check.verify.object(obj, 'missing object to check');
check.verify.object(predicates, 'missing predicates object');
Object.keys(predicates).forEach(function (property) {
if (!check.fn(predicates[property])) {
throw new Error('not a predicate function for ' + property + ' but ' + predicates[property]);
}
});
return check.every(check.map(obj, predicates));
}
|
javascript
|
{
"resource": ""
}
|
q50784
|
raises
|
train
|
function raises(fn, errorValidator) {
check.verify.fn(fn, 'expected function that raises');
try {
fn();
} catch (err) {
if (typeof errorValidator === 'undefined') {
return true;
}
if (typeof errorValidator === 'function') {
return errorValidator(err);
}
return false;
}
// error has not been raised
return false;
}
|
javascript
|
{
"resource": ""
}
|
q50785
|
unempty
|
train
|
function unempty(a) {
var hasLength = typeof a === 'string' ||
Array.isArray(a);
if (hasLength) {
return a.length;
}
if (a instanceof Object) {
return Object.keys(a).length;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q50786
|
commitId
|
train
|
function commitId(id) {
return check.string(id) &&
id.length === 40 &&
shaReg.test(id);
}
|
javascript
|
{
"resource": ""
}
|
q50787
|
shortCommitId
|
train
|
function shortCommitId(id) {
return check.string(id) &&
id.length === 7 &&
shortShaReg.test(id);
}
|
javascript
|
{
"resource": ""
}
|
q50788
|
or
|
train
|
function or() {
var predicates = Array.prototype.slice.call(arguments, 0);
if (!predicates.length) {
throw new Error('empty list of arguments to or');
}
return function orCheck() {
var values = Array.prototype.slice.call(arguments, 0);
return predicates.some(function (predicate) {
try {
return check.fn(predicate) ?
predicate.apply(null, values) : Boolean(predicate);
} catch (err) {
// treat exceptions as false
return false;
}
});
};
}
|
javascript
|
{
"resource": ""
}
|
q50789
|
and
|
train
|
function and() {
var predicates = Array.prototype.slice.call(arguments, 0);
if (!predicates.length) {
throw new Error('empty list of arguments to or');
}
return function orCheck() {
var values = Array.prototype.slice.call(arguments, 0);
return predicates.every(function (predicate) {
return check.fn(predicate) ?
predicate.apply(null, values) : Boolean(predicate);
});
};
}
|
javascript
|
{
"resource": ""
}
|
q50790
|
verifyModifier
|
train
|
function verifyModifier(predicate, defaultMessage) {
return function () {
var message;
if (predicate.apply(null, arguments) === false) {
message = arguments[arguments.length - 1];
throw new Error(check.unemptyString(message) ? message : defaultMessage);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q50791
|
getLegacyRepo
|
train
|
function getLegacyRepo(env) {
// default to process.env if no argument provided
if (!env) { env = process.env }
// bail if neither variable exists
let remote = env.DRONE_REMOTE || env.CI_REMOTE
if (!remote) { return '' }
// parse out the org and repo name from the git URL
let parts = remote.split('/').slice(-2)
let org = parts[0]
let reponame = parts[1].replace(/\.git$/, '')
let repo = '' + org + '/' + reponame
return repo
}
|
javascript
|
{
"resource": ""
}
|
q50792
|
getStreams
|
train
|
function getStreams(config) {
// Any passed in streams
const streams = Array.isArray(config.streams)
? [...config.streams]
: [];
// Nice console output
if (config.stdout) {
streams.push({
name: 'stdout',
level: config.level,
stream: new ClientConsoleLogger(),
type: 'raw',
});
}
// Rollbar Transport
// Messages at the warn level or higher are transported to Rollbar
// Detects presence of global Rollbar and passed in token
if (isGlobalRollbarConfigured()) {
if (config.rollbarToken) {
streams.push({
name: 'rollbar',
level: 'warn',
stream: new ClientRollbarLogger({
token: config.rollbarToken,
environment: config.environment,
codeVersion: config.codeVersion,
}),
type: 'raw',
});
}
} else {
/* eslint-disable no-console */
console.warn('Client rollbar is not correctly configured');
/* eslint-enable */
}
// Transport client logs
if (config.logentriesToken) {
streams.push({
name: 'logentries',
level: config.level,
stream: new ClientLogentriesLogger({
name: config.name,
token: config.logentriesToken,
}),
type: 'raw',
});
}
return streams;
}
|
javascript
|
{
"resource": ""
}
|
q50793
|
getStreams
|
train
|
function getStreams(config) {
const streams = Array.isArray(config.streams)
? [...config.streams]
: [];
// Nice output to stdout
if (config.stdout) {
streams.push({
name: 'stdout',
level: config.level,
stream: bunyanFormat({ outputMode: 'short' }),
type: 'stream',
});
}
// Rollbar Transport
// Messages at the warn level or higher are transported to Rollbar
// Messages with an `err` and/or `req` data params are handled specially
if (config.rollbarToken) {
streams.push({
name: 'rollbar',
level: 'warn',
stream: new ServerRollbarLogger({
token: config.rollbarToken,
environment: config.environment,
codeVersion: config.codeVersion,
}),
type: 'raw',
});
}
// Transport server logs
if (config.logentriesToken) {
streams.push(new ServerLogentriesLogger({
name: config.name,
token: config.logentriesToken,
level: config.level,
}));
}
return streams;
}
|
javascript
|
{
"resource": ""
}
|
q50794
|
getDependents
|
train
|
function getDependents(dependencyName) {
return Object.values(allPackages).filter(({info: pkg}) => {
return (
pkg.dependencies &&
Object.keys(pkg.dependencies).indexOf(dependencyName) !== -1
);
});
}
|
javascript
|
{
"resource": ""
}
|
q50795
|
train
|
function(key, success, error) {
success = success || noop;
error = error || noop;
exec(success, error, "CordovaStripe", "setPublishableKey", [key]);
}
|
javascript
|
{
"resource": ""
}
|
|
q50796
|
train
|
function(creditCard, success, error) {
success = success || noop;
error = error || noop;
exec(success, error, "CordovaStripe", "createCardToken", [creditCard]);
}
|
javascript
|
{
"resource": ""
}
|
|
q50797
|
train
|
function(bankAccount, success, error) {
success = success || noop;
error = error || noop;
exec(success, error, "CordovaStripe", "createBankAccountToken", [bankAccount]);
}
|
javascript
|
{
"resource": ""
}
|
|
q50798
|
train
|
function(cardNumber, success, error) {
success = success || noop;
error = error || noop;
exec(success, error, "CordovaStripe", "validateCardNumber", [cardNumber]);
}
|
javascript
|
{
"resource": ""
}
|
|
q50799
|
train
|
function(expMonth, expYear, success, error) {
success = success || noop;
error = error || noop;
exec(success, error, "CordovaStripe", "validateExpiryDate", [expMonth, expYear]);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.