_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q28300 | log | train | function log(msg, level, config) {
// Don't log messages in quiet mode
if (config && config.quiet) return;
const logMethod = console[level] || console.log;
let out = msg;
if (typeof msg === 'object') {
out = stringify(msg, null, 2);
}
logMethod(`[${chalk.gray('mochawesome')}] ${out}\n`);
} | javascript | {
"resource": ""
} |
q28301 | cleanCode | train | function cleanCode(str) {
str = str
.replace(/\r\n|[\r\n\u2028\u2029]/g, '\n') // unify linebreaks
.replace(/^\uFEFF/, ''); // replace zero-width no-break space
str = stripFnStart(str) // replace function declaration
.replace(/\)\s*\)\s*$/, ')') // replace closing paren
.replace(/\s*};?\s*$/, ''); // replace closing bracket
// Preserve indentation by finding leading tabs/spaces
// and removing that amount of space from each line
const spaces = str.match(/^\n?( *)/)[1].length;
const tabs = str.match(/^\n?(\t*)/)[1].length;
/* istanbul ignore next */
const indentRegex = new RegExp(`^\n?${tabs ? '\t' : ' '}{${tabs || spaces}}`, 'gm');
str = str.replace(indentRegex, '').trim();
return str;
} | javascript | {
"resource": ""
} |
q28302 | createUnifiedDiff | train | function createUnifiedDiff({ actual, expected }) {
return diff.createPatch('string', actual, expected)
.split('\n')
.splice(4)
.map(line => {
if (line.match(/@@/)) {
return null;
}
if (line.match(/\\ No newline/)) {
return null;
}
return line.replace(/^(-|\+)/, '$1 ');
})
.filter(line => typeof line !== 'undefined' && line !== null)
.join('\n');
} | javascript | {
"resource": ""
} |
q28303 | normalizeErr | train | function normalizeErr(err, config) {
const { name, message, actual, expected, stack, showDiff } = err;
let errMessage;
let errDiff;
/**
* Check that a / b have the same type.
*/
function sameType(a, b) {
const objToString = Object.prototype.toString;
return objToString.call(a) === objToString.call(b);
}
// Format actual/expected for creating diff
if (showDiff !== false && sameType(actual, expected) && expected !== undefined) {
/* istanbul ignore if */
if (!(_.isString(actual) && _.isString(expected))) {
err.actual = mochaUtils.stringify(actual);
err.expected = mochaUtils.stringify(expected);
}
errDiff = config.useInlineDiffs ? createInlineDiff(err) : createUnifiedDiff(err);
}
// Assertion libraries do not output consitent error objects so in order to
// get a consistent message object we need to create it ourselves
if (name && message) {
errMessage = `${name}: ${stripAnsi(message)}`;
} else if (stack) {
errMessage = stack.replace(/\n.*/g, '');
}
return {
message: errMessage,
estack: stack && stripAnsi(stack),
diff: errDiff
};
} | javascript | {
"resource": ""
} |
q28304 | cleanSuite | train | function cleanSuite(suite, totalTestsRegistered, config) {
let duration = 0;
const passingTests = [];
const failingTests = [];
const pendingTests = [];
const skippedTests = [];
const beforeHooks = _.map(
[].concat(suite._beforeAll, suite._beforeEach),
test => cleanTest(test, config)
);
const afterHooks = _.map(
[].concat(suite._afterAll, suite._afterEach),
test => cleanTest(test, config)
);
const tests = _.map(
suite.tests,
test => {
const cleanedTest = cleanTest(test, config);
duration += test.duration || 0;
if (cleanedTest.state === 'passed') passingTests.push(cleanedTest.uuid);
if (cleanedTest.state === 'failed') failingTests.push(cleanedTest.uuid);
if (cleanedTest.pending) pendingTests.push(cleanedTest.uuid);
if (cleanedTest.skipped) skippedTests.push(cleanedTest.uuid);
return cleanedTest;
}
);
totalTestsRegistered.total += tests.length;
const cleaned = {
uuid: uuid.v4(),
title: stripAnsi(suite.title),
fullFile: suite.file || '',
file: suite.file ? suite.file.replace(process.cwd(), '') : '',
beforeHooks,
afterHooks,
tests,
suites: suite.suites,
passes: passingTests,
failures: failingTests,
pending: pendingTests,
skipped: skippedTests,
duration,
root: suite.root,
rootEmpty: suite.root && tests.length === 0,
_timeout: suite._timeout
};
const isEmptySuite = _.isEmpty(cleaned.suites)
&& _.isEmpty(cleaned.tests)
&& _.isEmpty(cleaned.beforeHooks)
&& _.isEmpty(cleaned.afterHooks);
return !isEmptySuite && cleaned;
} | javascript | {
"resource": ""
} |
q28305 | mapSuites | train | function mapSuites(suite, totalTestsReg, config) {
const suites = _.compact(_.map(suite.suites, subSuite => (
mapSuites(subSuite, totalTestsReg, config)
)));
const toBeCleaned = Object.assign({}, suite, { suites });
return cleanSuite(toBeCleaned, totalTestsReg, config);
} | javascript | {
"resource": ""
} |
q28306 | _getOption | train | function _getOption(optToGet, options, isBool, defaultValue) {
const envVar = `MOCHAWESOME_${optToGet.toUpperCase()}`;
if (options && typeof options[optToGet] !== 'undefined') {
return (isBool && typeof options[optToGet] === 'string')
? options[optToGet] === 'true'
: options[optToGet];
}
if (typeof process.env[envVar] !== 'undefined') {
return isBool
? process.env[envVar] === 'true'
: process.env[envVar];
}
return defaultValue;
} | javascript | {
"resource": ""
} |
q28307 | train | function (...args) {
// Check args to see if we should bother continuing
if ((args.length !== 2) || !isObject(args[0])) {
log(ERRORS.INVALID_ARGS, 'error');
return;
}
const ctx = args[1];
// Ensure that context meets the requirements
if (!_isValidContext(ctx)) {
log(ERRORS.INVALID_CONTEXT(ctx), 'error');
return;
}
/* Context is valid, now get the test object
* If `addContext` is called from inside a `beforeEach` or `afterEach`
* the test object will be `.currentTest`, otherwise just `.test`
*/
const test = args[0].currentTest || args[0].test;
if (!test) {
log(ERRORS.INVALID_TEST, 'error');
return;
}
/* If context is an object, and value is `undefined`
* change it to 'undefined' so it can be displayed
* correctly in the report
*/
if (ctx.title && ctx.value === undefined) {
ctx.value = 'undefined';
}
// Test doesn't already have context -> set it
if (!test.context) {
test.context = ctx;
} else if (Array.isArray(test.context)) {
// Test has context and context is an array -> push new context
test.context.push(ctx);
} else {
// Test has context and it is not an array -> make it an array, then push new context
test.context = [ test.context ];
test.context.push(ctx);
}
} | javascript | {
"resource": ""
} | |
q28308 | sendRequest | train | function sendRequest(type, options) {
// Both remove and removeAll use the type 'remove' in the protocol
const normalizedType = type === 'removeAll' ? 'remove' : type
return socket
.hzRequest({ type: normalizedType, options }) // send the raw request
.takeWhile(resp => resp.state !== 'complete')
} | javascript | {
"resource": ""
} |
q28309 | isPrimitive | train | function isPrimitive(value) {
if (value === null) {
return true
}
if (value === undefined) {
return false
}
if (typeof value === 'function') {
return false
}
if ([ 'boolean', 'number', 'string' ].indexOf(typeof value) !== -1) {
return true
}
if (value instanceof Date || value instanceof ArrayBuffer) {
return true
}
return false
} | javascript | {
"resource": ""
} |
q28310 | model | train | function model(inputValue$, messages$) {
return Rx.Observable.combineLatest(
inputValue$.startWith(null),
messages$.startWith([]),
(inputValue, messages) => ({ messages, inputValue })
)
} | javascript | {
"resource": ""
} |
q28311 | view | train | function view(state$) {
// Displayed for each chat message.
function chatMessage(msg) {
return li('.message', { key: msg.id }, [
img({
height: '50', width: '50',
src: `http://api.adorable.io/avatars/50/${msg.authorId}.png`,
}),
span('.text', msg.text),
])
}
return state$.map(
state =>
div([
div('.row',
ul(state.messages.map(chatMessage))),
div('#input.row',
input('.u-full-width', { value: state.inputValue, autoFocus: true })),
])
)
} | javascript | {
"resource": ""
} |
q28312 | chatMessage | train | function chatMessage(msg) {
return li('.message', { key: msg.id }, [
img({
height: '50', width: '50',
src: `http://api.adorable.io/avatars/50/${msg.authorId}.png`,
}),
span('.text', msg.text),
])
} | javascript | {
"resource": ""
} |
q28313 | main | train | function main(sources) {
const intents = intent(sources)
const state$ = model(intents.inputValue$, intents.messages$)
return {
// Send the virtual tree to the real DOM
DOM: view(state$),
// Send our messages to the horizon server
horizon: intents.writeOps$$,
}
} | javascript | {
"resource": ""
} |
q28314 | makePresentable | train | function makePresentable(observable, query) {
// Whether the entire data structure is in each change
const pointQuery = Boolean(query.find)
if (pointQuery) {
let hasEmitted = false
const seedVal = null
// Simplest case: just pass through new_val
return observable
.filter(change => !hasEmitted || change.type !== 'state')
.scan((previous, change) => {
hasEmitted = true
if (change.new_val != null) {
delete change.new_val.$hz_v$
}
if (change.old_val != null) {
delete change.old_val.$hz_v$
}
if (change.state === 'synced') {
return previous
} else {
return change.new_val
}
}, seedVal)
} else {
const seedVal = { emitted: false, val: [] }
return observable
.scan((state, change) => {
if (change.new_val != null) {
delete change.new_val.$hz_v$
}
if (change.old_val != null) {
delete change.old_val.$hz_v$
}
if (change.state === 'synced') {
state.emitted = true
}
state.val = applyChange(state.val.slice(), change)
return state
}, seedVal)
.filter(state => state.emitted)
.map(x => x.val)
}
} | javascript | {
"resource": ""
} |
q28315 | train | function(e){
if(e.keyCode === 9){
e.preventDefault();
var cursor = this.selectionStart;
var nv = this.value.substring(0,cursor),
bv = this.value.substring(cursor, this.value.length);;
this.value = nv + "\t" + bv;
this.setSelectionRange(cursor + 1, cursor + 1);
}
} | javascript | {
"resource": ""
} | |
q28316 | _match | train | function _match (rule, cmtData) {
var path = rule.subject.split('.');
var extracted = cmtData;
while (path.length > 0) {
var item = path.shift();
if (item === '') {
continue;
}
if (extracted.hasOwnProperty(item)) {
extracted = extracted[item];
}
if (extracted === null || typeof extracted === 'undefined') {
extracted = null;
break;
}
}
if (extracted === null) {
// Null precondition implies anything
return true;
}
switch (rule.op) {
case '<':
return extracted < rule.value;
case '>':
return extracted > rule.value;
case '~':
case 'regexp':
return (new RegExp(rule.value)).test(extracted.toString());
case '=':
case 'eq':
return rule.value ===
((typeof extracted === 'number') ?
extracted : extracted.toString());
case '!':
case 'not':
return !_match(rule.value, extracted);
case '&&':
case 'and':
if (Array.isArray(rule.value)) {
return rule.value.every(function (r) {
return _match(r, extracted);
});
} else {
return false;
}
case '||':
case 'or':
if (Array.isArray(rule.value)) {
return rule.value.some(function (r) {
return _match(r, extracted);
});
} else {
return false;
}
default:
return false;
}
} | javascript | {
"resource": ""
} |
q28317 | CommentFilter | train | function CommentFilter() {
this.rules = [];
this.modifiers = [];
this.allowUnknownTypes = true;
this.allowTypes = {
'1': true,
'2': true,
'4': true,
'5': true,
'6': true,
'7': true,
'8': true,
'17': true
};
} | javascript | {
"resource": ""
} |
q28318 | train | function (text) {
if (text.charAt(0) === '[') {
switch (text.charAt(text.length - 1)) {
case ']':
return text;
case '"':
return text + ']';
case ',':
return text.substring(0, text.length - 1) + '"]';
default:
return _formatmode7(text.substring(0, text.length - 1));
}
} else {
return text;
}
} | javascript | {
"resource": ""
} | |
q28319 | train | function (text) {
text = text.replace(new RegExp('</([^d])','g'), '</disabled $1');
text = text.replace(new RegExp('</(\S{2,})','g'), '</disabled $1');
text = text.replace(new RegExp('<([^d/]\W*?)','g'), '<disabled $1');
text = text.replace(new RegExp('<([^/ ]{2,}\W*?)','g'), '<disabled $1');
return text;
} | javascript | {
"resource": ""
} | |
q28320 | isNativeFunction | train | function isNativeFunction(f) {
if ((typeof f) !== 'function') {
return false;
}
var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i;
return exp.exec(Function.prototype.toString.call(f)) != null;
} | javascript | {
"resource": ""
} |
q28321 | PassThrough | train | function PassThrough() {
return {
buf: '',
write: function(b) {
this.buf += b;
},
end: function(b) {
this.buf += b;
},
read: function() {
return this.buf;
}
};
} | javascript | {
"resource": ""
} |
q28322 | lineInt | train | function lineInt(l1,l2,precision){
precision = precision || 0;
var i = [0,0]; // point
var a1, b1, c1, a2, b2, c2, det; // scalars
a1 = l1[1][1] - l1[0][1];
b1 = l1[0][0] - l1[1][0];
c1 = a1 * l1[0][0] + b1 * l1[0][1];
a2 = l2[1][1] - l2[0][1];
b2 = l2[0][0] - l2[1][0];
c2 = a2 * l2[0][0] + b2 * l2[0][1];
det = a1 * b2 - a2*b1;
if (!scalar_eq(det, 0, precision)) { // lines are not parallel
i[0] = (b2 * c1 - b1 * c2) / det;
i[1] = (a1 * c2 - a2 * c1) / det;
}
return i;
} | javascript | {
"resource": ""
} |
q28323 | lineSegmentsIntersect | train | function lineSegmentsIntersect(p1, p2, q1, q2){
var dx = p2[0] - p1[0];
var dy = p2[1] - p1[1];
var da = q2[0] - q1[0];
var db = q2[1] - q1[1];
// segments are parallel
if((da*dy - db*dx) === 0){
return false;
}
var s = (dx * (q1[1] - p1[1]) + dy * (p1[0] - q1[0])) / (da * dy - db * dx);
var t = (da * (p1[1] - q1[1]) + db * (q1[0] - p1[0])) / (db * dx - da * dy);
return (s>=0 && s<=1 && t>=0 && t<=1);
} | javascript | {
"resource": ""
} |
q28324 | triangleArea | train | function triangleArea(a,b,c){
return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1])));
} | javascript | {
"resource": ""
} |
q28325 | collinear | train | function collinear(a,b,c,thresholdAngle) {
if(!thresholdAngle){
return triangleArea(a, b, c) === 0;
} else {
var ab = tmpPoint1,
bc = tmpPoint2;
ab[0] = b[0]-a[0];
ab[1] = b[1]-a[1];
bc[0] = c[0]-b[0];
bc[1] = c[1]-b[1];
var dot = ab[0]*bc[0] + ab[1]*bc[1],
magA = Math.sqrt(ab[0]*ab[0] + ab[1]*ab[1]),
magB = Math.sqrt(bc[0]*bc[0] + bc[1]*bc[1]),
angle = Math.acos(dot/(magA*magB));
return angle < thresholdAngle;
}
} | javascript | {
"resource": ""
} |
q28326 | polygonAt | train | function polygonAt(polygon, i){
var s = polygon.length;
return polygon[i < 0 ? i % s + s : i % s];
} | javascript | {
"resource": ""
} |
q28327 | polygonAppend | train | function polygonAppend(polygon, poly, from, to){
for(var i=from; i<to; i++){
polygon.push(poly[i]);
}
} | javascript | {
"resource": ""
} |
q28328 | polygonMakeCCW | train | function polygonMakeCCW(polygon){
var br = 0,
v = polygon;
// find bottom right point
for (var i = 1; i < polygon.length; ++i) {
if (v[i][1] < v[br][1] || (v[i][1] === v[br][1] && v[i][0] > v[br][0])) {
br = i;
}
}
// reverse poly if clockwise
if (!isLeft(polygonAt(polygon, br - 1), polygonAt(polygon, br), polygonAt(polygon, br + 1))) {
polygonReverse(polygon);
return true;
} else {
return false;
}
} | javascript | {
"resource": ""
} |
q28329 | polygonReverse | train | function polygonReverse(polygon){
var tmp = [];
var N = polygon.length;
for(var i=0; i!==N; i++){
tmp.push(polygon.pop());
}
for(var i=0; i!==N; i++){
polygon[i] = tmp[i];
}
} | javascript | {
"resource": ""
} |
q28330 | polygonIsReflex | train | function polygonIsReflex(polygon, i){
return isRight(polygonAt(polygon, i - 1), polygonAt(polygon, i), polygonAt(polygon, i + 1));
} | javascript | {
"resource": ""
} |
q28331 | polygonCopy | train | function polygonCopy(polygon, i,j,targetPoly){
var p = targetPoly || [];
polygonClear(p);
if (i < j) {
// Insert all vertices from i to j
for(var k=i; k<=j; k++){
p.push(polygon[k]);
}
} else {
// Insert vertices 0 to j
for(var k=0; k<=j; k++){
p.push(polygon[k]);
}
// Insert vertices i to end
for(var k=i; k<polygon.length; k++){
p.push(polygon[k]);
}
}
return p;
} | javascript | {
"resource": ""
} |
q28332 | polygonDecomp | train | function polygonDecomp(polygon){
var edges = polygonGetCutEdges(polygon);
if(edges.length > 0){
return polygonSlice(polygon, edges);
} else {
return [polygon];
}
} | javascript | {
"resource": ""
} |
q28333 | polygonIsSimple | train | function polygonIsSimple(polygon){
var path = polygon, i;
// Check
for(i=0; i<path.length-1; i++){
for(var j=0; j<i-1; j++){
if(lineSegmentsIntersect(path[i], path[i+1], path[j], path[j+1] )){
return false;
}
}
}
// Check the segment between the last and the first point to all others
for(i=1; i<path.length-2; i++){
if(lineSegmentsIntersect(path[0], path[path.length-1], path[i], path[i+1] )){
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
q28334 | polygonRemoveCollinearPoints | train | function polygonRemoveCollinearPoints(polygon, precision){
var num = 0;
for(var i=polygon.length-1; polygon.length>3 && i>=0; --i){
if(collinear(polygonAt(polygon, i-1),polygonAt(polygon, i),polygonAt(polygon, i+1),precision)){
// Remove the middle point
polygon.splice(i%polygon.length,1);
num++;
}
}
return num;
} | javascript | {
"resource": ""
} |
q28335 | polygonRemoveDuplicatePoints | train | function polygonRemoveDuplicatePoints(polygon, precision){
for(var i=polygon.length-1; i>=1; --i){
var pi = polygon[i];
for(var j=i-1; j>=0; --j){
if(points_eq(pi, polygon[j], precision)){
polygon.splice(i,1);
continue;
}
}
}
} | javascript | {
"resource": ""
} |
q28336 | scalar_eq | train | function scalar_eq(a,b,precision){
precision = precision || 0;
return Math.abs(a-b) <= precision;
} | javascript | {
"resource": ""
} |
q28337 | points_eq | train | function points_eq(a,b,precision){
return scalar_eq(a[0],b[0],precision) && scalar_eq(a[1],b[1],precision);
} | javascript | {
"resource": ""
} |
q28338 | serialize | train | function serialize(model) {
var data = model.toJSON();
Object.keys(data).forEach(function serializeRecur(key) {
var value = data[key];
// if any value can be serialized toJSON() then do it
if (value && value.toJSON) {
data[key] = data[key].toJSON();
}
});
return data;
} | javascript | {
"resource": ""
} |
q28339 | listen | train | function listen(model, listener) {
model.on('change', listener);
model.values().forEach(function listenRecur(value) {
var isCollection = value && value._byId;
if (!isCollection) {
return;
}
// for each collection listen to it
// console.log('listenCollection')
listenCollection(value, listener);
});
} | javascript | {
"resource": ""
} |
q28340 | listenCollection | train | function listenCollection(collection, listener) {
collection.forEach(function listenModel(model) {
listen(model, listener);
});
collection.on('add', function onAdd(model) {
listen(model, listener);
listener();
});
} | javascript | {
"resource": ""
} |
q28341 | parseBabelThing | train | function parseBabelThing(babelThing) {
assert_usage([String, Array].includes(babelThing.constructor));
let name;
let options;
if( babelThing.constructor === Array ) {
name = babelThing[0];
options = babelThing[1];
} else {
name = babelThing;
}
assert_usage(name.constructor===String, babelThing);
spec = [name];
if( options ) {
spec.push(options);
}
return {name, options, spec};
} | javascript | {
"resource": ""
} |
q28342 | applyViewWrappers | train | function applyViewWrappers({reactElement, initialProps, viewWrappers=[]}) {
viewWrappers
.forEach(viewWrapper => {
reactElement = viewWrapper(reactElement, initialProps);
});
return reactElement;
} | javascript | {
"resource": ""
} |
q28343 | assemble_modifiers | train | function assemble_modifiers(modifier_name, configParts) {
const assert_usage = require('reassert/usage');
// `configParts` holds all globalConfig parts
// `config` holds a webpack config
let supra_modifier = ({config}) => config;
// We assemble all `configParts`'s config modifiers into one `supra_modifier`
configParts
.forEach(configPart => {
const modifier = configPart[modifier_name];
if( ! modifier ) {
return;
}
assert_usage(configPart[modifier_name] instanceof Function);
const previous_modifier = supra_modifier;
supra_modifier = (
args => {
const config = previous_modifier(args);
const config__new = modifier({...args, config});
assert_usage(
config__new,
(
configPart.$name ? (
"The `"+modifier_name+"` of `"+configPart.$name+"`"
) : (
"A `"+modifier_name+"`"
)
) + (
" is returning `"+config__new+"` but it should be returning a webpack config instead."
)
);
return config__new;
}
);
});
return supra_modifier;
} | javascript | {
"resource": ""
} |
q28344 | StreamFormatter | train | function StreamFormatter(loggerManager, options) {
if (!(this instanceof StreamFormatter)) {
return new StreamFormatter(loggerManager, options);
}
stream.Readable.call(this, options);
this._buffer = [];
this._pushable = false;
this._ended = false;
loggerManager.on("message", this._handleMessage.bind(this));
loggerManager.on("end", function () { this._handleMessage("END"); }.bind(this));
} | javascript | {
"resource": ""
} |
q28345 | logReadableStream | train | function logReadableStream(stream) {
var encoding = "utf8";
stream.setEncoding(encoding);
stream.on("data", function (chunk) {
writeToLog(chunk, encoding);
});
} | javascript | {
"resource": ""
} |
q28346 | logWriteableStream | train | function logWriteableStream(stream, colorFunction) {
var write = stream.write;
// The third parameter, callback, will be passed implicitely using arguments
stream.write = function (chunk, encoding) {
// Write to STDOUT right away
try {
write.apply(this, arguments);
} catch (streamWriteError) { }
writeToLog(chunk, encoding, colorFunction);
};
} | javascript | {
"resource": ""
} |
q28347 | getLogDirectoryElements | train | function getLogDirectoryElements(settings) {
var elements,
platform = process.platform;
if (settings.logRoot) {
elements = [settings.logRoot, settings.module];
} else if (platform === "darwin") {
elements = [process.env.HOME, "Library", "Logs", settings.vendor, settings.application, settings.module];
} else if (platform === "win32") {
elements = [process.env.APPDATA, settings.vendor, settings.application, settings.module, "logs"];
} else {
elements = [process.env.HOME, settings.vendor, settings.application, settings.module, "logs"];
}
return elements;
} | javascript | {
"resource": ""
} |
q28348 | extractStyleInfo | train | function extractStyleInfo(psd/*, opts*/) {
var SON = {};
var layers = psd.layers;
_classnames = [];
_psd = psd;
SON.layers = [];
layers.forEach(function (layer) {
var s = extractLayerStyleInfo(layer);
if (s !== undefined) {
SON.layers.push(s);
}
});
return SON;
} | javascript | {
"resource": ""
} |
q28349 | train | function (pixmapWidth, pixmapHeight) {
// Find out if the mask extends beyond the visible pixels
var paddingWanted;
["top", "left", "right", "bottom"].forEach(function (key) {
if (paddedInputBounds[key] !== visibleInputBounds[key]) {
paddingWanted = true;
return false;
}
});
// When Photoshop produces inaccurate results, the padding is adjusted to compensate
// When no padding is requested, this may be unwanted, so return a padding of 0px
if (!paddingWanted) {
return { left: 0, top: 0, right: 0, bottom: 0 };
}
var // How much padding is necessary in both dimensions
missingWidth = finalOutputWidth - pixmapWidth,
missingHeight = finalOutputHeight - pixmapHeight,
// How of the original padding was on which side (default 0)
leftRatio = paddingInputWidth === 0 ? 0 :
((visibleInputBounds.left - paddedInputBounds.left) / paddingInputWidth),
topRatio = paddingInputHeight === 0 ? 0 :
((visibleInputBounds.top - paddedInputBounds.top) / paddingInputHeight),
// Concrete padding size on one side so the other side can use the rest
leftPadding = Math.round(leftRatio * missingWidth),
topPadding = Math.round(topRatio * missingHeight);
// Padding: how many transparent pixels to add on which side
return {
left: Math.max(0, leftPadding),
top: Math.max(0, topPadding),
right: Math.max(0, missingWidth - leftPadding),
bottom: Math.max(0, missingHeight - topPadding)
};
} | javascript | {
"resource": ""
} | |
q28350 | Client | train | function Client (args, options) {
// Ensure Client instantiated with 'new'
if (!(this instanceof Client)) {
return new Client(args, options);
}
var servers = []
, weights = {}
, regular = 'localhost:11211'
, key;
// Parse down the connection arguments
switch (Object.prototype.toString.call(args)) {
case '[object Object]':
weights = args;
servers = Object.keys(args);
break;
case '[object Array]':
servers = args.length ? args : [regular];
break;
default:
servers.push(args || regular);
break;
}
if (!servers.length) {
throw new Error('No servers where supplied in the arguments');
}
// merge with global and user config
Utils.merge(this, Client.config);
Utils.merge(this, options);
this.servers = servers;
var compatibility = this.compatibility || this.compatiblity;
this.HashRing = new HashRing(args, this.algorithm, {
'compatibility': compatibility,
'default port': compatibility === 'ketama' ? 11211 : null
});
this.connections = {};
this.issues = [];
} | javascript | {
"resource": ""
} |
q28351 | stats | train | function stats(resultSet) {
var response = {};
if (resultSetIsEmpty(resultSet)) return response;
// add references to the retrieved server
response.server = this.serverAddress;
// Fill the object
resultSet.forEach(function each(statSet) {
if (statSet) response[statSet[0]] = statSet[1];
});
return response;
} | javascript | {
"resource": ""
} |
q28352 | handle | train | function handle(err, results) {
if (err) {
errors.push(err);
}
// add all responses to the array
(Array.isArray(results) ? results : [results]).forEach(function each(value) {
if (value && memcached.namespace.length) {
var ns_key = Object.keys(value)[0]
, newvalue = {};
newvalue[ns_key.replace(memcached.namespace, '')] = value[ns_key];
Utils.merge(responses, newvalue);
} else {
Utils.merge(responses, value);
}
});
if (!--calls){
callback(errors.length ? errors : undefined, responses);
}
} | javascript | {
"resource": ""
} |
q28353 | handle | train | function handle(err, results) {
if (err) {
errors = errors || [];
errors.push(err);
}
if (results) responses = responses.concat(results);
// multi calls should ALWAYS return an array!
if (!--calls) {
callback(errors && errors.length ? errors.pop() : undefined, responses);
}
} | javascript | {
"resource": ""
} |
q28354 | updateUserProfileWithToken | train | function updateUserProfileWithToken(messagingToken) {
const currentUserUid =
firebase.auth().currentUser && firebase.auth().currentUser.uid
if (!currentUserUid) {
return Promise.resolve();
}
return firebase
.firestore()
.collection('users')
.doc(currentUserUid)
.update({
messaging: {
mostRecentToken: messagingToken,
updatedAt: firebase.firestore.FieldValue.serverTimestamp()
}
})
} | javascript | {
"resource": ""
} |
q28355 | getMessagingToken | train | function getMessagingToken() {
return firebase
.messaging()
.getToken()
.catch(err => {
console.error('Unable to retrieve refreshed token ', err) // eslint-disable-line no-console
return Promise.reject(err)
})
} | javascript | {
"resource": ""
} |
q28356 | initStackdriverErrorReporter | train | function initStackdriverErrorReporter() {
if (typeof window.StackdriverErrorReporter === 'function') {
window.addEventListener('DOMContentLoaded', () => {
const errorHandler = new window.StackdriverErrorReporter()
errorHandler.start({
key: firebase.apiKey,
projectId: firebase.projectId,
service: 'react-firebase-redux-site',
version
})
})
}
return errorHandler
} | javascript | {
"resource": ""
} |
q28357 | initGA | train | function initGA() {
if (analyticsTrackingId) {
ReactGA.initialize(analyticsTrackingId)
ReactGA.set({
appName: environment || 'Production',
appVersion: version
})
}
} | javascript | {
"resource": ""
} |
q28358 | setGAUser | train | function setGAUser(auth) {
if (auth && auth.uid) {
ReactGA.set({ userId: auth.uid })
}
} | javascript | {
"resource": ""
} |
q28359 | MediaRecorder | train | function MediaRecorder (stream) {
/**
* The `MediaStream` passed into the constructor.
* @type {MediaStream}
*/
this.stream = stream
/**
* The current state of recording process.
* @type {"inactive"|"recording"|"paused"}
*/
this.state = 'inactive'
this.em = document.createDocumentFragment()
this.encoder = createWorker(MediaRecorder.encoder)
var recorder = this
this.encoder.addEventListener('message', function (e) {
var event = new Event('dataavailable')
event.data = new Blob([e.data], { type: recorder.mimeType })
recorder.em.dispatchEvent(event)
if (recorder.state === 'inactive') {
recorder.em.dispatchEvent(new Event('stop'))
}
})
} | javascript | {
"resource": ""
} |
q28360 | start | train | function start (timeslice) {
if (this.state !== 'inactive') {
return this.em.dispatchEvent(error('start'))
}
this.state = 'recording'
if (!context) {
context = new AudioContext()
}
this.clone = this.stream.clone()
var input = context.createMediaStreamSource(this.clone)
if (!processor) {
processor = context.createScriptProcessor(2048, 1, 1)
}
var recorder = this
processor.onaudioprocess = function (e) {
if (recorder.state === 'recording') {
recorder.encoder.postMessage([
'encode', e.inputBuffer.getChannelData(0)
])
}
}
input.connect(processor)
processor.connect(context.destination)
this.em.dispatchEvent(new Event('start'))
if (timeslice) {
this.slicing = setInterval(function () {
if (recorder.state === 'recording') recorder.requestData()
}, timeslice)
}
return undefined
} | javascript | {
"resource": ""
} |
q28361 | stop | train | function stop () {
if (this.state === 'inactive') {
return this.em.dispatchEvent(error('stop'))
}
this.requestData()
this.state = 'inactive'
this.clone.getTracks().forEach(function (track) {
track.stop()
})
return clearInterval(this.slicing)
} | javascript | {
"resource": ""
} |
q28362 | balance | train | function balance() {
binance.balance((error, balances) => {
if ( error ) console.error(error);
let btc = 0.00;
for ( let asset in balances ) {
let obj = balances[asset];
obj.available = parseFloat(obj.available);
//if ( !obj.available ) continue;
obj.onOrder = parseFloat(obj.onOrder);
obj.btcValue = 0;
obj.btcTotal = 0;
if ( asset == 'BTC' ) obj.btcValue = obj.available;
else if ( asset == 'USDT' ) obj.btcValue = obj.available / global.ticker.BTCUSDT;
else obj.btcValue = obj.available * global.ticker[asset+'BTC'];
if ( asset == 'BTC' ) obj.btcTotal = obj.available + obj.onOrder;
else if ( asset == 'USDT' ) obj.btcTotal = (obj.available + obj.onOrder) / global.ticker.BTCUSDT;
else obj.btcTotal = (obj.available + obj.onOrder) * global.ticker[asset+'BTC'];
if ( isNaN(obj.btcValue) ) obj.btcValue = 0;
if ( isNaN(obj.btcTotal) ) obj.btcTotal = 0;
btc+= obj.btcTotal;
global.balance[asset] = obj;
}
//fs.writeFile("json/balance.json", JSON.stringify(global.balance, null, 4), (err)=>{});
});
} | javascript | {
"resource": ""
} |
q28363 | getAllPropertyDescriptors | train | function getAllPropertyDescriptors(object) {
if (object === Object.prototype) {
return {};
} else {
let prototype = getPrototypeOf(object);
return assign(getAllPropertyDescriptors(prototype), getOwnPropertyDescriptors(object));
}
} | javascript | {
"resource": ""
} |
q28364 | toNodeStream | train | function toNodeStream (renderer) {
let sourceIsReady = true;
const read = () => {
// If source is not ready, defer any reads until the promise resolves.
if (!sourceIsReady) { return false; }
sourceIsReady = false;
const pull = pullBatch(renderer, stream);
return pull.then(result => {
sourceIsReady = true;
if (result === EXHAUSTED) {
return stream.push(null);
} else {
if (result !== INCOMPLETE) {
stream.push(result);
}
return read();
}
}).catch(err => {
return stream.emit("error", err);
});
};
const stream = new Readable({ read });
return stream;
} | javascript | {
"resource": ""
} |
q28365 | evalComponent | train | function evalComponent (seq, node, context) {
const Component = node.type;
const componentContext = getContext(Component, context);
const instance = constructComponent(Component, node.props, componentContext);
const renderedElement = renderComponentInstance(instance, node.props, componentContext);
const childContext = getChildContext(Component, instance, context);
traverse({
seq,
node: renderedElement,
context: childContext,
parent: node
});
} | javascript | {
"resource": ""
} |
q28366 | traverse | train | function traverse ({ seq, node, context, numChildren, parent }) {
if (node === undefined || node === true) {
return;
}
if (node === false) {
if (parent && isFunction(parent.type)) {
emitEmpty(seq);
return;
} else {
return;
}
}
if (node === null) {
emitEmpty(seq);
return;
}
switch (typeof node) {
case "string": {
// Text node.
emitText({
seq,
text: htmlStringEscape(node),
numChildren,
isNewlineEatingTag: Boolean(parent && newlineEatingTags[parent.type])
});
return;
}
case "number": {
emitText({
seq,
text: node.toString(),
numChildren
});
return;
}
case "object": {
if (node.__prerendered__) {
evalPreRendered(seq, node, context);
return;
} else if (typeof node.type === "string") {
// Plain-jane DOM element, not a React component.
seq.delegateCached(node, (_seq, _node) => renderNode(_seq, _node, context));
return;
} else if (node.$$typeof) {
// React component.
seq.delegateCached(node, (_seq, _node) => evalComponent(_seq, _node, context));
return;
}
}
}
throw new TypeError(`Unknown node of type: ${node.type}`);
} | javascript | {
"resource": ""
} |
q28367 | syncSetState | train | function syncSetState (newState) {
// Mutation is faster and should be safe here.
this.state = assign(
this.state,
isFunction(newState) ?
newState(this.state, this.props) :
newState
);
} | javascript | {
"resource": ""
} |
q28368 | toPromise | train | function toPromise (renderer) {
// this.sequence, this.batchSize, this.dataReactAttrs
const buffer = {
value: [],
push (segment) { this.value.push(segment); }
};
return new Promise((resolve, reject) =>
setImmediate(
asyncBatch,
renderer,
buffer,
resolve,
reject
)
)
.then(() => Promise.all(buffer.value))
.then(chunks => {
let html = chunks
.filter(chunk => typeof chunk === "string")
.join("");
if (renderer.dataReactAttrs && !COMMENT_START.test(html)) {
const checksum = renderer.checksum();
html = html.replace(TAG_END, ` data-react-checksum="${checksum}"$&`);
}
return html;
});
} | javascript | {
"resource": ""
} |
q28369 | getChildContext | train | function getChildContext (componentPrototype, instance, context) {
if (componentPrototype.childContextTypes) {
return assign(Object.create(null), context, instance.getChildContext());
}
return context;
} | javascript | {
"resource": ""
} |
q28370 | getContext | train | function getContext (componentPrototype, context) {
if (componentPrototype.contextTypes) {
const contextTypes = componentPrototype.contextTypes;
return keys(context).reduce(
(memo, contextKey) => {
if (contextKey in contextTypes) {
memo[contextKey] = context[contextKey];
}
return memo;
},
Object.create(null)
);
}
return EMPTY_CONTEXT;
} | javascript | {
"resource": ""
} |
q28371 | processErrors | train | function processErrors (errors, transformers) {
const transform = (error, transformer) => transformer(error);
const applyTransformations = (error) => transformers.reduce(transform, error);
return errors.map(extractError).map(applyTransformations);
} | javascript | {
"resource": ""
} |
q28372 | format | train | function format(errors, type) {
return errors
.filter(isDefaultError)
.reduce((accum, error) => (
accum.concat(displayError(type, error))
), []);
} | javascript | {
"resource": ""
} |
q28373 | formatErrors | train | function formatErrors(errors, formatters, errorType) {
const format = (formatter) => formatter(errors, errorType) || [];
const flatten = (accum, curr) => accum.concat(curr);
return formatters.map(format).reduce(flatten, [])
} | javascript | {
"resource": ""
} |
q28374 | doReveal | train | function doReveal(el) {
var orig = el.getAttribute('src') || false;
el.addEventListener('error', function handler(e) {
// on error put back the original image if available (usually a placeholder)
console.log('error loading image', e);
if (orig) {
el.setAttribute('src', orig);
}
el.removeEventListener('error', handler); // hate this.
});
var src = el.getAttribute('data-src');
if (src) {
el.setAttribute('src', src);
addClass(el);
return;
}
src = el.getAttribute('data-bkg');
if (src) {
el.style.backgroundImage = 'url("' + src + '")';
addClass(el);
return;
}
} | javascript | {
"resource": ""
} |
q28375 | reveal | train | function reveal(el) {
if (el.hasChildNodes()) {
// dealing with a container try and find children
var els = el.querySelectorAll('[data-src], [data-bkg]');
var elsl = els.length;
if (elsl === 0) {
// node has children, but none have the attributes, so reveal
// the node itself (use case: div with a background)
doReveal(el);
} else {
for (var j = 0; j < elsl; j++) {
doReveal(els[j]);
}
}
} else {
doReveal(el);
}
} | javascript | {
"resource": ""
} |
q28376 | init | train | function init() {
// find all elements with the class "appear"
var els = document.getElementsByClassName('appear');
var elsl = els.length;
// put html elements into an array object to work with
for (var i = 0; i < elsl; i += 1) {
// some images are revealed on a simple timeout, instead of
// viewport appears. These delays appears must have
// the appear class on them directly
var delay = els[i].getAttribute('data-delay');
if (delay) {
delayAppear(els[i], delay);
} else {
nodes.push(els[i]);
}
}
} | javascript | {
"resource": ""
} |
q28377 | debounce | train | function debounce(fn, delay) {
return function () {
var self = this, args = arguments;
clearTimeout(timer);
console.log('debounce()');
timer = setTimeout(function () {
fn.apply(self, args);
}, delay);
};
} | javascript | {
"resource": ""
} |
q28378 | checkAppear | train | function checkAppear() {
if(scroll.delta < opts.delta.speed) {
if(!deltaSet) {
deltaSet = true;
doCheckAppear();
setTimeout(function(){
deltaSet = false;
}, opts.delta.timeout);
}
}
(debounce(function() {
doCheckAppear();
}, opts.debounce)());
} | javascript | {
"resource": ""
} |
q28379 | poly2path | train | function poly2path(polygon) {
var pos = polygon.pos;
var points = polygon.calcPoints;
var result = 'M' + pos.x + ' ' + pos.y;
result += 'M' + (pos.x + points[0].x) + ' ' + (pos.y + points[0].y);
for (var i = 1; i < points.length; i++) {
var point = points[i];
result += 'L' + (pos.x + point.x) + ' ' + (pos.y + point.y);
}
result += 'Z';
return result;
} | javascript | {
"resource": ""
} |
q28380 | moveDrag | train | function moveDrag(entity, world) {
return function (dx, dy) {
// This position updating is fairly naive - it lets objects tunnel through each other, but it suffices for these examples.
entity.data.pos.x = this.ox + dx;
entity.data.pos.y = this.oy + dy;
world.simulate();
};
} | javascript | {
"resource": ""
} |
q28381 | train | function () {
if (this.data instanceof SAT.Circle) {
this.displayAttrs.cx = this.data.pos.x;
this.displayAttrs.cy = this.data.pos.y;
this.displayAttrs.r = this.data.r;
} else {
this.displayAttrs.path = poly2path(this.data);
}
this.display.attr(this.displayAttrs);
} | javascript | {
"resource": ""
} | |
q28382 | starToIndex | train | function starToIndex (pairs, data, i, out) {
if (!data) {
return []
}
i = i || 0
let curr = pairs[i++]
const next = pairs[i]
/**
* When out is not defined, then start
* with the current node
*/
if (!out) {
out = [curr]
curr = ''
}
/**
* Keep on adding to the out array. The reason we call reduce
* operation, as we have to modify the existing keys inside
* the `out` array.
*/
out = out.reduce((result, existingNode) => {
const nName = curr ? `${existingNode}.${curr}` : existingNode
/**
* We pull childs when `next` is not undefined, otherwise
* we assume the end of `*` expression
*/
if (next !== undefined) {
const value = prop(data, nName)
if (Array.isArray(value)) {
const dataLength = value.length
for (let i = 0; i < dataLength; i++) {
result.push(`${nName}.${i}`)
}
}
} else {
result.push(nName)
}
return result
}, [])
/**
* Recursively call this method until we loop through the entire
* array.
*/
return i === pairs.length ? out : starToIndex(pairs, data, i, out)
} | javascript | {
"resource": ""
} |
q28383 | onRejected | train | function onRejected (error) {
return {
fullFilled: false,
rejected: true,
value: null,
reason: error
}
} | javascript | {
"resource": ""
} |
q28384 | pSeries | train | function pSeries (iterable, bail) {
const result = []
const iterableLength = iterable.length
function noop (index, bail) {
/**
* End of promises
*/
if (index >= iterableLength) {
return Promise.resolve(result)
}
return iterable[index]
.then((output) => {
result.push(onResolved(output))
return noop(index + 1, bail)
})
.catch((error) => {
result.push(onRejected(error))
/**
*
* When bail is false, we continue after rejections
* too.
*/
if (!bail) {
return noop(index + 1, bail)
}
/**
* Otherwise we resolve the promise
*/
return Promise.resolve(result)
})
}
return noop(0, bail)
} | javascript | {
"resource": ""
} |
q28385 | start | train | async function start () {
let exitCode = 0
const port = process.env.PORT || 3000
console.log(chalk`{magenta creating app bundle}`)
/**
* Creating rollup bundle by bundling `test/qunit/index.js` file.
*/
const bundle = await rollup.rollup({
input: path.join(__dirname, '../test', 'qunit', 'index'),
plugins: require('../rollupPlugins')
})
const { code } = await bundle.generate({
file: path.join(__dirname, '../tmp', 'qunit.js'),
format: 'umd',
name: 'indicativeSpec'
})
const server = await sauceLabs.serve(qUnitTemplate(code), port)
console.log(chalk`started app server on {green http://localhost:${port}}`)
/**
* Starting the HTTP server. If `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY`
* env variables exists, we will run tests on sauce, otherwise
* we will run them on user machine.
*/
if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
console.log(chalk`{yellow pass SAUCE_USERNAME & SAUCE_ACCESS_KEY to run tests on saucelabs}`)
opn(`http://localhost:${port}`)
return
}
const ngrok = require('ngrok')
try {
/**
* Ngrok url
*/
const publicUrl = await sauceLabs.getPublicUrl(port)
console.log(chalk`started ngrok tunnel on {green ${publicUrl}}`)
/**
* Creating jobs with sauce labs
*/
const jobs = await sauceLabs.createTestsJob(browsers, publicUrl)
console.log(chalk`created {green ${jobs.length} jobs}`)
/**
* Monitoring jobs for results
*/
console.log(chalk`{magenta monitoring jobs}`)
const results = await sauceLabs.getJobsResult(jobs)
/**
* Got some results
*/
results.forEach((result) => {
console.log('')
console.log(chalk`{bold ${result.platform.join(' ')}}`)
console.log(chalk` {green Passed ${result.result.passed}}`)
console.log(chalk` {red Failed ${result.result.failed}}`)
console.log(` Total ${result.result.total}`)
})
/**
* Creating a new build to be annotated
*/
const buildId = `build-${new Date().getTime()}`
console.log('annotating jobs result')
for (let result of results) {
await sauceLabs.annotateJob(result.job_id, buildId, result.result.failed === 0)
}
console.log(chalk`{green done}`)
} catch (error) {
console.log(chalk` {red Reaceived error}`)
console.log(error)
exitCode = 1
}
/**
* Cleanup
*/
ngrok.kill()
server.close()
process.exit(exitCode)
} | javascript | {
"resource": ""
} |
q28386 | setConfig | train | function setConfig (options) {
Object.keys(options).forEach((option) => {
if (config[option] !== undefined) {
config[option] = options[option]
}
})
} | javascript | {
"resource": ""
} |
q28387 | validationFn | train | function validationFn (validations, {name, args}, field, data, messages, formatter) {
return new PLazy((resolve, reject) => {
const camelizedName = snakeToCamelCase(name)
const validation = validations[camelizedName]
if (typeof (validation) !== 'function') {
const error = new Error(`${camelizedName} is not defined as a validation rule`)
formatter.addError(error, field, camelizedName, args)
reject(error)
return
}
validation(data, field, getMessage(messages, field, name, args), args, prop)
.then(resolve)
.catch((error) => {
formatter.addError(error, field, camelizedName, args)
reject(error)
})
})
} | javascript | {
"resource": ""
} |
q28388 | getValidationsStack | train | function getValidationsStack (validations, fields, data, messages, formatter) {
return Object
.keys(fields)
.reduce((flatValidations, field) => {
fields[field].map((rule) => {
flatValidations.push(validationFn(validations, rule, field, data, messages, formatter))
})
return flatValidations
}, [])
} | javascript | {
"resource": ""
} |
q28389 | validate | train | function validate (validations, bail, data, fields, messages, formatter) {
return new Promise((resolve, reject) => {
messages = messages || {}
/**
* This is expanded form of fields and rules
* applied on them
*/
const parsedFields = parse(fields, data)
/**
* A flat validations stack, each node is a lazy promise
*/
const validationsStack = getValidationsStack(validations, parsedFields, data, messages, formatter)
pSeries(validationsStack, bail)
.then((response) => {
const errors = formatter.toJSON()
if (errors) {
return reject(errors)
}
resolve(data)
})
})
} | javascript | {
"resource": ""
} |
q28390 | sanitizeField | train | function sanitizeField (sanitizations, value, rules) {
let result = value
rules.forEach((rule) => {
const ruleFn = snakeToCamelCase(rule.name)
if (typeof (sanitizations[ruleFn]) !== 'function') {
throw new Error(`${ruleFn} is not a sanitization method`)
}
result = sanitizations[ruleFn](result, rule.args)
})
return result
} | javascript | {
"resource": ""
} |
q28391 | getFiles | train | function getFiles (location, filterFn) {
return new Promise((resolve, reject) => {
const files = []
klaw(location)
.on('data', (item) => {
if (!item.stats.isDirectory() && filterFn(item)) {
files.push(item.path)
}
})
.on('end', () => resolve(files))
.on('error', reject)
})
} | javascript | {
"resource": ""
} |
q28392 | readFiles | train | async function readFiles (locations) {
return Promise.all(locations.map((location) => {
return fs.readFile(location, 'utf-8')
}))
} | javascript | {
"resource": ""
} |
q28393 | extractComments | train | function extractComments (contents) {
let context = 'idle'
const lines = []
contents.split('\n').forEach((line) => {
if (line.trim() === '/**') {
context = 'in'
return
}
if (line.trim() === '*/') {
context = 'out'
return
}
if (context === 'in') {
lines.push(line.replace(/\*/g, '').replace(/^\s\s/, ''))
}
})
return lines.join('\n')
} | javascript | {
"resource": ""
} |
q28394 | writeDocs | train | async function writeDocs (basePath, nodes) {
Promise.all(nodes.map((node) => {
const location = path.join(basePath, node.location.replace(srcPath, '').replace(/\.js$/, '.adoc'))
return fs.outputFile(location, node.comments)
}))
} | javascript | {
"resource": ""
} |
q28395 | srcToDocs | train | async function srcToDocs (dir) {
const location = path.join(srcPath, dir)
const srcFiles = await getFiles(location, (item) => item.path.endsWith('.js') && !item.path.endsWith('index.js'))
const filesContents = await readFiles(srcFiles)
const filesComments = srcFiles.map((location, index) => {
const fnName = path.basename(location).replace(/\.js$/, '')
const matter = getMatter(fnName, dir)
const doc = matter.concat(extractComments(filesContents[index])).concat(getRuleImport(fnName))
return { comments: doc.join('\n'), location }
})
await writeDocs(docsDir, filesComments)
} | javascript | {
"resource": ""
} |
q28396 | parseRules | train | function parseRules (fields, data) {
data = data || {}
return Object.keys(fields).reduce((result, field) => {
let rules = fields[field]
/**
* Strings are passed to haye for further processing
* and if rules are not an array or a string, then
* we should blow.
*/
if (typeof (rules) === 'string') {
rules = Pipe(rules, new ArrayPresenter())
} else if (!Array.isArray(rules)) {
throw new Error('Rules must be defined as a string or an array')
}
/**
* When field name has a star in it, we need to do some heavy
* lifting and expand the field to dot properties based upon
* the available data inside the data object.
*/
if (field.indexOf('*') > -1) {
const nodes = field.split(/\.\*\.?/)
starToIndex(nodes, data).forEach((f) => { result[f] = rules })
} else {
result[field] = rules
}
return result
}, {})
} | javascript | {
"resource": ""
} |
q28397 | train | function (route, body, method = 'post') {
return got(`https://saucelabs.com/rest/v1/${process.env.SAUCE_USERNAME}/${route}`, {
method,
json: true,
body,
headers: {
Authorization: `Basic ${getCredentials()}`
}
}).then((response) => {
return response.body
}).catch((error) => {
throw error.response.body
})
} | javascript | {
"resource": ""
} | |
q28398 | getMessage | train | function getMessage (messages, field, validation, args) {
/**
* Since we allow array expression as `*`, we want all index of the
* current field to be replaced with `.*`, so that we get the
* right message.
*/
const originalField = field.replace(/\.\d/g, '.*')
const camelizedValidation = snakeToCamelCase(validation)
const message = messages[`${originalField}.${validation}`] ||
messages[`${originalField}.${camelizedValidation}`] ||
messages[validation] ||
messages[camelizedValidation] ||
'{{validation}} validation failed on {{ field }}'
return typeof (message) === 'function'
? message(originalField, validation, args)
: pope(message, { field, validation, argument: args })
} | javascript | {
"resource": ""
} |
q28399 | train | function(bytes) {
bytes = bytes || 2;
var max = Math.pow(16, bytes) - 1;
var css = [
"#",
pad(Math.round(this.red * max).toString(16).toUpperCase(), bytes),
pad(Math.round(this.green * max).toString(16).toUpperCase(), bytes),
pad(Math.round(this.blue * max).toString(16).toUpperCase(), bytes)
];
return css.join('');
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.