_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q50900
|
remove_null_undefined
|
train
|
function remove_null_undefined(object) {
Object.keys(object).forEach(key => {
if (object[key] === null || typeof object[key] === "undefined") {
delete object[key]
}
})
return object
}
|
javascript
|
{
"resource": ""
}
|
q50901
|
get_related_columns
|
train
|
function get_related_columns(collection) {
return Object.keys(collection.attributes)
.filter(attribute => collection.attributes[attribute].collection || collection.attributes[attribute].model)
}
|
javascript
|
{
"resource": ""
}
|
q50902
|
compile_constraints
|
train
|
function compile_constraints(request, constraints) {
const Constraints = require("./constraints")
// Exit if there aren't any constraints.
if (!constraints)
return {}
return new Constraints()
.set_source(request)
.set_rules(constraints)
.compile()
.results
}
|
javascript
|
{
"resource": ""
}
|
q50903
|
replace_env_values
|
train
|
function replace_env_values(val_in) {
if (!val_in)
return ""
let val_out = val_in
const matches = val_in.match(/\$\w+/g)
if (matches)
matches.forEach(env => {
const value = process.env[env.substring(1, env.length)]
val_out = value.replace(new RegExp(`${env}`, "g"), value) // eslint-disable-line
})
return val_out
}
|
javascript
|
{
"resource": ""
}
|
q50904
|
getJunctionTableFromModelAndRelatedColumn
|
train
|
function getJunctionTableFromModelAndRelatedColumn(model, parentTableName, relatedColumnTableName) {
const junctionTableName = Object.keys(model.waterline.schema)
.find(schemaName => {
const tables = model.waterline.schema[schemaName].tables
if (!tables) return false
return tables[0] === parentTableName && tables[1] === relatedColumnTableName
})
if (!junctionTableName) return false
const junctionTableSchema = model.waterline.schema[junctionTableName]
const junctionTableCollection = model.waterline.collections[junctionTableName]
return {
tableName: junctionTableName,
tables: junctionTableSchema.tables,
collection: junctionTableCollection,
columns: Object.keys(junctionTableCollection.attributes).filter(name => name !== "id")
}
}
|
javascript
|
{
"resource": ""
}
|
q50905
|
hash_password
|
train
|
function hash_password(values, next) {
// If no password was provided, just move on and exit.
if (!values.password || values.password.length > 1000) {
return next()
}
this
.findOne(values)
.then(user => {
// Create a salt for this user if they don't have one.
const salt = user && user.salt ? user.salt : utils.create_salt()
// We're going to encrypt the password.
utils.hash_password(values.password, salt, (password, salt) => {
// Apply the hash and salt to the inbound values.
values.password = password.toString("hex")
values.salt = salt
values.requires_password = false
// Move on.
next()
})
})
.catch(next)
}
|
javascript
|
{
"resource": ""
}
|
q50906
|
toJSON
|
train
|
function toJSON() {
const model = this.toObject()
delete model.password
delete model.salt
// Return the modified user object.
return utils.remove_null_undefined(model)
}
|
javascript
|
{
"resource": ""
}
|
q50907
|
custom_routes
|
train
|
function custom_routes(hapi_server, multicolour) {
// Joi is an amazing validation library,
// read me at https://github.com/hapijs/joi/blob/v10.2.2/API.md
const Joi = require("joi")
// Set up a simple route that counts examples.
hapi_server.route({
method: "GET",
path: "/example/count",
config: {
// Get any auth config from core.
auth: multicolour.get("server").request("auth_config"),
// Add tags to appear in the /docs endpoint.
tags: ["api", "example"],
// Validate the params.
validate: {
// Get valid headers from Multicolour.
headers: Joi.object(
multicolour.get("server")
.request("header_validator")
.get()
).unknown(true)
},
// Validate the response.
response: {
// Get the schema from Multicolour to validate the response.
schema: Joi.object({
count: Joi.number().required(),
message: Joi.string()
})
.meta({className: "person_count"})
.label("person_count")
},
handler: (request, reply) => {
// `this` is the current model but only with
// a full function () definition (no fat arrows)
// on the custom_routes file.
this.count(request.url.query)
.then(count => reply({
count,
message: "Try POST /person to increase this count result!"
}))
}
}
})
}
|
javascript
|
{
"resource": ""
}
|
q50908
|
random
|
train
|
function random (utxos, outputs, feeRate) {
utxos = shuffle(utxos)
return accumulative(utxos, outputs, feeRate)
}
|
javascript
|
{
"resource": ""
}
|
q50909
|
train
|
function (point, geopoly) {
var inside = 0;
if(geopoly.type !== "Polygon" && geopoly.type !== "MultiPolygon") return false;
var shape = geopoly.type === 'Polygon' ? [geopoly.coordinates] : geopoly.coordinates;
shape.forEach(function (polygon) {
polygon.forEach(function (ring) {
if(pip([point.longitude, point.latitude], ring)) inside++;
});
});
return inside % 2;
}
|
javascript
|
{
"resource": ""
}
|
|
q50910
|
train
|
function(fn) {
return function(evt, param) {
var p = TP.getPkg(evt);
if (p.ytplayer) {
var ret = fn(evt, param, p);
if (typeof(ret) === "undefined") {
ret = p.$player;
}
return ret;
}
return p.$player;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q50911
|
train
|
function(storybook, baseUrl, previewRoute) {
// clean baseUrl. remove query/hash/trailing-slash
var urlObj = url.parse(baseUrl);
urlObj = omit(urlObj, 'hash', 'search', 'query');
urlObj.pathname = urlObj.pathname.replace(/\/$/, '');
baseUrl = url.format(urlObj);
// transform into states
var states = [];
storybook.forEach(function(component) {
component.stories.forEach(function(story) {
var previewUrl = baseUrl + previewRoute + '?dataId=0&selectedKind=' + encodeURIComponent(component.kind) + '&selectedStory=' + encodeURIComponent(story.name);
var state = {
url: previewUrl,
name: component.kind + ': ' + story.name
};
if (story.steps) {
state.steps = story.steps;
}
states.push(state);
});
});
return states;
}
|
javascript
|
{
"resource": ""
}
|
|
q50912
|
train
|
function(current) {
if (current && current.props) {
if (current.props.isScreenerComponent === true) {
return current.props.steps;
} else {
var steps = null;
if (typeof current.props.story === 'function') {
steps = findScreenerSteps(current.props.story());
}
if (!steps && typeof current.props.storyFn === 'function') {
steps = findScreenerSteps(current.props.storyFn());
}
if (!steps && current.props.initialContent) {
steps = findScreenerSteps(current.props.initialContent);
}
if (!steps && typeof current.type === 'function') {
try {
steps = findScreenerSteps(current.type());
} catch(ex) { /**/ }
}
if (!steps && current.props.children) {
var children = current.props.children;
// handle array of children
if (typeof children === 'object' && typeof children.map === 'function' && children.length > 0) {
for (var i = 0, len = children.length; i < len; i++) {
steps = findScreenerSteps(children[i]);
if (steps) break;
}
} else {
steps = findScreenerSteps(children);
}
}
return steps;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50913
|
train
|
function(current) {
if (typeof current.steps === 'object' && typeof current.steps.map === 'function' && current.steps.length > 0) {
return current.steps;
}
var steps = null;
if (typeof current.render === 'function') {
try {
steps = findScreenerStepsInRender(current.render(function(fn) {
return fn;
}));
} catch (ex) {
steps = null;
}
}
if (typeof current.components === 'object' && typeof current.components.story === 'object' && typeof current.components.story.render === 'function') {
try {
steps = findScreenerStepsInRender(current.components.story.render(function(fn) {
return fn;
}, {}));
} catch (ex) {
steps = null;
}
}
return steps;
}
|
javascript
|
{
"resource": ""
}
|
|
q50914
|
hasRest
|
train
|
function hasRest(pattern) {
for (let elem of pattern.elements) {
if (isRestElement(t, elem)) {
return true
}
}
return false
}
|
javascript
|
{
"resource": ""
}
|
q50915
|
getDirective
|
train
|
function getDirective(path) {
for (let directive of path.node.directives) {
let dirstr = directive.value.value
if (dirstr.startsWith('use ')) {
let uses = dirstr.substr(4).split(',').map((use) => use.trim())
if (uses.indexOf('extensible') !== -1) {
return 1
}
if (uses.indexOf('!extensible') !== -1) {
return -1
}
}
}
return 0
}
|
javascript
|
{
"resource": ""
}
|
q50916
|
flipPixels
|
train
|
function flipPixels(buffer, width, height) {
const newBuffer = Buffer.alloc(buffer.length)
for (let x = 0; x < width; x += 1) {
for (let y = 0; y < height; y += 1) {
const offset = (width * y + x) << 2
const newOffset = (width * y + width - 1 - x) << 2
const pixel = buffer.readUInt32BE(offset, true)
newBuffer.writeUInt32BE(pixel, newOffset, true)
}
}
return newBuffer
}
|
javascript
|
{
"resource": ""
}
|
q50917
|
parseOrientationTag
|
train
|
function parseOrientationTag({buffer, exifData}) {
let orientation = null
if (exifData['0th'] && exifData['0th'][piexif.ImageIFD.Orientation]) {
orientation = parseInt(exifData['0th'][piexif.ImageIFD.Orientation])
}
if (orientation === null) {
throw new CustomError(m.errors.no_orientation, 'No orientation tag found in EXIF', buffer)
}
if (isNaN(orientation) || orientation < 1 || orientation > 8) {
throw new CustomError(m.errors.unknown_orientation, 'Unknown orientation (' + orientation + ')', buffer)
}
if (orientation === 1) {
throw new CustomError(m.errors.correct_orientation, 'Orientation already correct', buffer)
}
return orientation
}
|
javascript
|
{
"resource": ""
}
|
q50918
|
computeFinalBuffer
|
train
|
function computeFinalBuffer(image, thumbnail, exifData, orientation) {
exifData['0th'][piexif.ImageIFD.Orientation] = 1
if (typeof exifData['Exif'][piexif.ExifIFD.PixelXDimension] !== 'undefined') {
exifData['Exif'][piexif.ExifIFD.PixelXDimension] = image.width
}
if (typeof exifData['Exif'][piexif.ExifIFD.PixelYDimension] !== 'undefined') {
exifData['Exif'][piexif.ExifIFD.PixelYDimension] = image.height
}
if (thumbnail.buffer) {
exifData['thumbnail'] = thumbnail.buffer.toString('binary')
}
const exifBytes = piexif.dump(exifData)
const updatedBuffer = Buffer.from(piexif.insert(exifBytes, image.buffer.toString('binary')), 'binary')
const updatedDimensions = {
height: image.height,
width: image.width,
}
return Promise.resolve({updatedBuffer, orientation, updatedDimensions})
}
|
javascript
|
{
"resource": ""
}
|
q50919
|
contextRenderer
|
train
|
function contextRenderer (tpl, locals, options, noCache) {
var finalLocals = merge({}, helpers, defaultLocals, this.state, locals)
this.body = renderer(tpl, finalLocals, options, noCache)
this.type = 'text/html'
return this
}
|
javascript
|
{
"resource": ""
}
|
q50920
|
train
|
function (restrict) {
return ['$compile', function ($compile) {
return {
restrict: restrict,
require: ['?^valdrType', '?^ngModel', '?^valdrFormGroup'],
link: function (scope, element, attrs, controllers) {
var valdrTypeController = controllers[0],
ngModelController = controllers[1],
valdrFormGroupController = controllers[2],
valdrNoValidate = attrs.valdrNoValidate,
valdrNoMessage = attrs.valdrNoMessage,
fieldName = attrs.name;
/**
* Don't do anything if
* - this is an <input> that's not inside of a valdr-type or valdr-form-group block
* - there is no ng-model bound to input
* - there is a 'valdr-no-validate' or 'valdr-no-message' attribute present
*/
if (!valdrTypeController || !valdrFormGroupController || !ngModelController ||
angular.isDefined(valdrNoValidate) || angular.isDefined(valdrNoMessage)) {
return;
}
var valdrMessageElement = angular.element('<span valdr-message="' + fieldName + '"></span>');
$compile(valdrMessageElement)(scope);
valdrFormGroupController.addMessageElement(ngModelController, valdrMessageElement);
scope.$on('$destroy', function () {
valdrFormGroupController.removeMessageElement(ngModelController);
});
}
};
}];
}
|
javascript
|
{
"resource": ""
}
|
|
q50921
|
train
|
function (value, prefix) {
return angular.isString(value) &&
angular.isString(prefix) &&
value.lastIndexOf(prefix, 0) === 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q50922
|
train
|
function (value, constraint) {
var pattern = asRegExp(constraint.value);
return valdrUtil.isEmpty(value) || pattern.test(value);
}
|
javascript
|
{
"resource": ""
}
|
|
q50923
|
train
|
function (value, constraint) {
if (valdrUtil.isEmpty(value)) {
return true;
}
if (valdrUtil.isNaN(Number(value))) {
return false;
}
return doValidate(value, constraint);
}
|
javascript
|
{
"resource": ""
}
|
|
q50924
|
train
|
function (typeName, fieldName, value) {
var validResult = { valid: true },
typeConstraints = constraintsForType(typeName);
if (valdrUtil.has(typeConstraints, fieldName)) {
var fieldConstraints = typeConstraints[fieldName],
fieldIsValid = true,
validationResults = [],
violations = [];
angular.forEach(fieldConstraints, function (constraint, validatorName) {
var validator = validators[validatorName];
if (angular.isUndefined(validator)) {
$log.warn('No validator defined for \'' + validatorName +
'\'. Can not validate field \'' + fieldName + '\'');
return validResult;
}
var valid = validator.validate(value, constraint);
var validationResult = {
valid: valid,
value: value,
field: fieldName,
type: typeName,
validator: validatorName
};
angular.extend(validationResult, constraint);
validationResults.push(validationResult);
if (!valid) {
violations.push(validationResult);
}
fieldIsValid = fieldIsValid && valid;
});
return {
valid: fieldIsValid,
violations: violations.length === 0 ? undefined : violations,
validationResults: validationResults.length === 0 ? undefined : validationResults
};
} else {
return validResult;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50925
|
train
|
function (value) {
if (valdrUtil.isEmpty(value)) {
return true;
}
// split email at '@' and consider local and domain part separately
var emailParts = value.split('@');
if (emailParts.length !== 2) {
return false;
}
if (!localPattern.test(emailParts[0])) {
return false;
}
return domainPattern.test(emailParts[1]);
}
|
javascript
|
{
"resource": ""
}
|
|
q50926
|
train
|
function(tech) {
return (this.level.getConfig().bundleBuildLevels || [])
.concat([PATH.resolve(this.root, PATH.dirname(this.getNodePrefix()), 'blocks')]);
}
|
javascript
|
{
"resource": ""
}
|
|
q50927
|
train
|
function(techName, techPath, declPath, bundleNode, magicNode, forked) {
var arch = this.ctx.arch,
buildNode = new BemBuildNode.BemBuildNode({
root: this.root,
bundlesLevel: this.level,
levels: this.getLevels(techName),
declPath: declPath,
techPath: techPath,
techName: techName,
output: this.getNodePrefix(),
forked: forked === undefined? ~this.getForkedTechs().indexOf(techName): forked
});
var tech = this.level.getTech(techName, techPath),
metaNode;
/* techs-v2: don't create meta node */
if (tech.API_VER !== 2) metaNode = buildNode.getMetaNode();
// Set bem build node to arch and add dependencies to it
arch.setNode(buildNode)
.addChildren(buildNode, buildNode.getDependencies());
// Add file aliases to arch and link with buildNode as parents
buildNode.getFiles().forEach(function(f) {
if (buildNode.getId() === f) return;
var alias = new fileNodes.FileNode({ path: f, root: this.root });
arch.setNode(alias).addParents(buildNode, alias);
}, this);
bundleNode && arch.addParents(buildNode, bundleNode);
magicNode && arch.addChildren(buildNode, magicNode);
/* techs-v2: don't add dependency on meta node */
if (metaNode) {
// Set bem build meta node to arch
arch.setNode(metaNode)
.addParents(metaNode, buildNode)
.addChildren(metaNode, metaNode.getDependencies());
}
return buildNode;
}
|
javascript
|
{
"resource": ""
}
|
|
q50928
|
train
|
function(techName, techPath, bundleNode, magicNode, force, forked) {
var arch = this.ctx.arch,
node = this.useFileOrBuild(new BemCreateNode.BemCreateNode({
root: this.root,
level: this.level,
item: this.item,
techPath: techPath,
techName: techName,
force: force,
forked: forked === undefined? ~this.getForkedTechs().indexOf(techName): forked
}));
if (!node) return;
// Set bem create node to arch and add dependencies to it
arch.setNode(node)
.addChildren(node, node.getDependencies());
// Add file aliases to arch and link with node as parents
node.getFiles && node.getFiles().forEach(function(f) {
if (node.getId() === f) return;
var alias = new fileNodes.FileNode({ path: f, root: this.root });
arch.setNode(alias).addParents(node, alias);
}, this);
bundleNode && arch.addParents(node, bundleNode);
magicNode && arch.addChildren(node, magicNode);
return node;
}
|
javascript
|
{
"resource": ""
}
|
|
q50929
|
train
|
function(tech, bundleNode, magicNode) {
var arch = this.ctx.arch,
filePath = this.getBundlePath(tech);
if (!PATH.existsSync(PATH.resolve(this.root, filePath))) return;
var node = new fileNodes.FileNode({
root: this.root,
path: filePath
});
arch.setNode(node);
bundleNode && arch.addParents(node, bundleNode);
magicNode && arch.addChildren(node, magicNode);
return node;
}
|
javascript
|
{
"resource": ""
}
|
|
q50930
|
train
|
function(tech, bundleNode, magicNode) {
var ctx = this.ctx,
arch = ctx.arch,
levelNode = arch.getNode(PATH.relative(this.root, this.level.dir)),
depsTech = this.level.getTech('deps.js').getTechName(),
bundles = arch.getChildren(levelNode)
.filter(function(b) {
var n = arch.getNode(b);
return n instanceof exports.BundleNode && n !== this;
}, this)
.map(function(b) {
return U.getNodeTechPath(this.level, arch.getNode(b).item, depsTech);
}, this);
return this.setBemDeclNode(
tech,
this.level.resolveTech(tech),
bundleNode,
magicNode,
'merge',
bundles);
}
|
javascript
|
{
"resource": ""
}
|
|
q50931
|
train
|
function(nodeName, objectOrBaseName, objectOrStatic, staticObject) {
var explicitBase = typeof objectOrBaseName === 'string',
baseName = explicitBase? objectOrBaseName : nodeName,
staticObj = typeof objectOrBaseName !== 'string'? objectOrStatic: staticObject,
obj = explicitBase? objectOrStatic : objectOrBaseName,
base = baseName;
if (typeof baseName === 'string') {
base = baseName === nodeName? cache[baseName] : this.getNodeClass(baseName);
}
if (typeof objectOrStatic === 'function') {
cache[nodeName] = objectOrStatic;
} else {
cache[nodeName] = base? INHERIT(base, obj, staticObj) : INHERIT(obj, staticObj);
}
return cache;
}
|
javascript
|
{
"resource": ""
}
|
|
q50932
|
train
|
function(nodeName, objectOrBaseName, objectOrStatic, staticObject) {
cache = {};
var stack = registry[nodeName] || [];
stack.push(Array.prototype.slice.call(arguments, 0));
registry[nodeName] = stack;
}
|
javascript
|
{
"resource": ""
}
|
|
q50933
|
d3_format_group
|
train
|
function d3_format_group(value) {
var i = value.lastIndexOf("."),
f = i >= 0 ? value.substring(i) : (i = value.length, ""),
t = [];
while (i > 0) t.push(value.substring(i -= 3, i + 3));
return t.reverse().join(",") + f;
}
|
javascript
|
{
"resource": ""
}
|
q50934
|
l
|
train
|
function l(e) {
var o = d3.event; // Events can be reentrant (e.g., focus).
d3.event = e;
try {
listener.call(node, node.__data__, i);
} finally {
d3.event = o;
}
}
|
javascript
|
{
"resource": ""
}
|
q50935
|
brush
|
train
|
function brush(g) {
g.each(function() {
var g = d3.select(this),
bg = g.selectAll(".background").data([0]),
fg = g.selectAll(".extent").data([0]),
tz = g.selectAll(".resize").data(resizes, String),
e;
// Prepare the brush container for events.
g
.style("pointer-events", "all")
.on("mousedown.brush", brushstart)
.on("touchstart.brush", brushstart);
// An invisible, mouseable area for starting a new brush.
bg.enter().append("rect")
.attr("class", "background")
.style("visibility", "hidden")
.style("cursor", "crosshair");
// The visible brush extent; style this as you like!
fg.enter().append("rect")
.attr("class", "extent")
.style("cursor", "move");
// More invisible rects for resizing the extent.
tz.enter().append("g")
.attr("class", function(d) { return "resize " + d; })
.style("cursor", function(d) { return d3_svg_brushCursor[d]; })
.append("rect")
.attr("x", function(d) { return /[ew]$/.test(d) ? -3 : null; })
.attr("y", function(d) { return /^[ns]/.test(d) ? -3 : null; })
.attr("width", 6)
.attr("height", 6)
.style("visibility", "hidden");
// Show or hide the resizers.
tz.style("display", brush.empty() ? "none" : null);
// Remove any superfluous resizers.
tz.exit().remove();
// Initialize the background to fill the defined range.
// If the range isn't defined, you can post-process.
if (x) {
e = d3_scaleRange(x);
bg.attr("x", e[0]).attr("width", e[1] - e[0]);
redrawX(g);
}
if (y) {
e = d3_scaleRange(y);
bg.attr("y", e[0]).attr("height", e[1] - e[0]);
redrawY(g);
}
redraw(g);
});
}
|
javascript
|
{
"resource": ""
}
|
q50936
|
recurse
|
train
|
function recurse(data, depth, nodes) {
var childs = children.call(hierarchy, data, depth),
node = d3_layout_hierarchyInline ? data : {data: data};
node.depth = depth;
nodes.push(node);
if (childs && (n = childs.length)) {
var i = -1,
n,
c = node.children = [],
v = 0,
j = depth + 1,
d;
while (++i < n) {
d = recurse(childs[i], j, nodes);
d.parent = node;
c.push(d);
v += d.value;
}
if (sort) c.sort(sort);
if (value) node.value = v;
} else if (value) {
node.value = +value.call(hierarchy, data, depth) || 0;
}
return node;
}
|
javascript
|
{
"resource": ""
}
|
q50937
|
revalue
|
train
|
function revalue(node, depth) {
var children = node.children,
v = 0;
if (children && (n = children.length)) {
var i = -1,
n,
j = depth + 1;
while (++i < n) v += revalue(children[i], j);
} else if (value) {
v = +value.call(hierarchy, d3_layout_hierarchyInline ? node : node.data, depth) || 0;
}
if (value) node.value = v;
return v;
}
|
javascript
|
{
"resource": ""
}
|
q50938
|
d3_layout_hierarchyRebind
|
train
|
function d3_layout_hierarchyRebind(object, hierarchy) {
d3.rebind(object, hierarchy, "sort", "children", "value");
// Add an alias for links, for convenience.
object.links = d3_layout_hierarchyLinks;
// If the new API is used, enabling inlining.
object.nodes = function(d) {
d3_layout_hierarchyInline = true;
return (object.nodes = object)(d);
};
return object;
}
|
javascript
|
{
"resource": ""
}
|
q50939
|
squarify
|
train
|
function squarify(node) {
var children = node.children;
if (children && children.length) {
var rect = pad(node),
row = [],
remaining = children.slice(), // copy-on-write
child,
best = Infinity, // the best row score so far
score, // the current row score
u = Math.min(rect.dx, rect.dy), // initial orientation
n;
scale(remaining, rect.dx * rect.dy / node.value);
row.area = 0;
while ((n = remaining.length) > 0) {
row.push(child = remaining[n - 1]);
row.area += child.area;
if ((score = worst(row, u)) <= best) { // continue with this orientation
remaining.pop();
best = score;
} else { // abort, and try a different orientation
row.area -= row.pop().area;
position(row, u, rect, false);
u = Math.min(rect.dx, rect.dy);
row.length = row.area = 0;
best = Infinity;
}
}
if (row.length) {
position(row, u, rect, true);
row.length = row.area = 0;
}
children.forEach(squarify);
}
}
|
javascript
|
{
"resource": ""
}
|
q50940
|
stickify
|
train
|
function stickify(node) {
var children = node.children;
if (children && children.length) {
var rect = pad(node),
remaining = children.slice(), // copy-on-write
child,
row = [];
scale(remaining, rect.dx * rect.dy / node.value);
row.area = 0;
while (child = remaining.pop()) {
row.push(child);
row.area += child.area;
if (child.z != null) {
position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length);
row.length = row.area = 0;
}
}
children.forEach(stickify);
}
}
|
javascript
|
{
"resource": ""
}
|
q50941
|
token
|
train
|
function token() {
if (re.lastIndex >= text.length) return EOF; // special case: end of file
if (eol) { eol = false; return EOL; } // special case: end of line
// special case: quotes
var j = re.lastIndex;
if (text.charCodeAt(j) === 34) {
var i = j;
while (i++ < text.length) {
if (text.charCodeAt(i) === 34) {
if (text.charCodeAt(i + 1) !== 34) break;
i++;
}
}
re.lastIndex = i + 2;
var c = text.charCodeAt(i + 1);
if (c === 13) {
eol = true;
if (text.charCodeAt(i + 2) === 10) re.lastIndex++;
} else if (c === 10) {
eol = true;
}
return text.substring(j + 1, i).replace(/""/g, "\"");
}
// common case
var m = re.exec(text);
if (m) {
eol = m[0].charCodeAt(0) !== 44;
return text.substring(j, m.index);
}
re.lastIndex = text.length;
return text.substring(j);
}
|
javascript
|
{
"resource": ""
}
|
q50942
|
resample
|
train
|
function resample(coordinates) {
var i = 0,
n = coordinates.length,
j,
m,
resampled = n ? [coordinates[0]] : coordinates,
resamples,
origin = arc.source();
while (++i < n) {
resamples = arc.source(coordinates[i - 1])(coordinates[i]).coordinates;
for (j = 0, m = resamples.length; ++j < m;) resampled.push(resamples[j]);
}
arc.source(origin);
return resampled;
}
|
javascript
|
{
"resource": ""
}
|
q50943
|
d3_geom_hullCCW
|
train
|
function d3_geom_hullCCW(i1, i2, i3, v) {
var t, a, b, c, d, e, f;
t = v[i1]; a = t[0]; b = t[1];
t = v[i2]; c = t[0]; d = t[1];
t = v[i3]; e = t[0]; f = t[1];
return ((f-b)*(c-a) - (d-b)*(e-a)) > 0;
}
|
javascript
|
{
"resource": ""
}
|
q50944
|
d3_geom_polygonIntersect
|
train
|
function d3_geom_polygonIntersect(c, d, a, b) {
var x1 = c[0], x2 = d[0], x3 = a[0], x4 = b[0],
y1 = c[1], y2 = d[1], y3 = a[1], y4 = b[1],
x13 = x1 - x3,
x21 = x2 - x1,
x43 = x4 - x3,
y13 = y1 - y3,
y21 = y2 - y1,
y43 = y4 - y3,
ua = (x43 * y13 - y43 * x13) / (y43 * x21 - x43 * y21);
return [x1 + ua * x21, y1 + ua * y21];
}
|
javascript
|
{
"resource": ""
}
|
q50945
|
train
|
function(o) {
this.__base(o);
this.root = o.root;
this.target = o.target;
this.npmPackages = o.npmPackages === undefined? ['package.json']: o.npmPackages;
}
|
javascript
|
{
"resource": ""
}
|
|
q50946
|
train
|
function() {
var _this = this;
return QFS.statLink(this.getPath())
.fail(function() {
return false;
})
.then(function(stat) {
if (!stat) return;
/* jshint -W109 */
if (!stat.isSymbolicLink()) {
return Q.reject(UTIL.format("SymlinkLibraryNode: Path '%s' is exists and is not a symbolic link",
_this.getPath()));
}
/* jshint +W109 */
return QFS.remove(_this.getPath());
})
.then(function() {
var parent = PATH.dirname(_this.getPath());
return QFS.exists(parent)
.then(function(exists) {
/* jshint -W109 */
if(!exists) {
LOGGER.verbose("SymlinkLibraryNode: Creating parent directory for target '%s'",
_this.getPath());
return QFS.makeTree(parent);
}
/* jshint +W109 */
});
})
.then(function() {
return QFS.symbolicLink(_this.getPath(), _this.relative);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q50947
|
train
|
function(o) {
this.__base(o);
this.url = o.url;
this.paths = [''];
this.timeout = typeof o.timeout !== 'undefined'? Number(o.timeout) : SCM_VALIDITY_TIMEOUT;
}
|
javascript
|
{
"resource": ""
}
|
|
q50948
|
train
|
function(o) {
this.__base(o);
this.treeish = o.treeish;
this.branch = o.branch || 'master';
this.origin = o.origin || 'origin';
}
|
javascript
|
{
"resource": ""
}
|
|
q50949
|
train
|
function(o) {
this.__base(o);
this.paths = Array.isArray(o.paths)? o.paths : [o.paths || ''];
this.revision = o.revision || 'HEAD';
}
|
javascript
|
{
"resource": ""
}
|
|
q50950
|
train
|
function() {
var _this = this,
base = this.__base();
if (this.revision === 'HEAD') return base;
return Q.all(this.paths.map(function(path) {
return QFS.exists(PATH.resolve(_this.root, _this.target, path))
.then(function(exists) {
return exists && _this.getInfo(path)
.then(function(info) {
return String(info.revision) === String(_this.revision);
});
});
}))
.then(function(checks) {
return checks.reduce(function(cur, prev) {
return cur && prev;
}, true) || base;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q50951
|
train
|
function(path, opts) {
opts = opts || {};
this.dir = PATH.resolve(path.path || path);
this.projectRoot = opts.projectRoot || PATH.resolve('');
// NOTE: keep this.path for backwards compatibility
this.path = this.bemDir = PATH.join(this.dir, '.bem');
path = PATH.relative(this.projectRoot, this.dir);
this.cache = useCache;
for(var e in exceptLevels) {
var except = exceptLevels[e];
if (path.substr(0, except.length) === except) {
this.cache = !this.cache;
break;
}
}
// NOTE: tech modules cache
this._techsCache = {};
}
|
javascript
|
{
"resource": ""
}
|
|
q50952
|
train
|
function(techIdent, opts) {
if (typeof opts === 'boolean') {
//legacy code used `force` second argument
opts = {force: opts};
}
opts = opts || {};
if(bemUtil.isPath(techIdent)) {
return this.resolveTechPath(techIdent);
}
if(!opts.force && this.getTechs().hasOwnProperty(techIdent)) {
return this.resolveTechName(techIdent);
}
return bemUtil.getBemTechPath(techIdent, opts);
}
|
javascript
|
{
"resource": ""
}
|
|
q50953
|
train
|
function(techName) {
var p = this.getTechs()[techName];
return typeof p !== 'undefined'? this.resolveTech(p, {force: true}) : null;
}
|
javascript
|
{
"resource": ""
}
|
|
q50954
|
train
|
function(techPath) {
// Get absolute path if path starts with "."
// NOTE: Can not replace check to !isAbsolute()
if(techPath.substring(0, 1) === '.') {
// Resolve relative path starting at level `.bem/` directory
techPath = PATH.join(this.bemDir, techPath);
/* jshint -W109 */
if(!isRequireable(techPath)) {
throw new Error("Tech module on path '" + techPath + "' not found");
}
/* jshint +W109 */
return techPath;
}
// Trying absolute of relative-without-dot path
if(isRequireable(techPath)) {
return techPath;
}
/* jshint -W109 */
try {
return require.resolve('./' + PATH.join('./techs', techPath));
} catch (err) {
throw new Error("Tech module with path '" + techPath + "' not found on require search paths");
}
/* jshint +W109 */
}
|
javascript
|
{
"resource": ""
}
|
|
q50955
|
train
|
function(item) {
var getter, args;
if (item.block) {
getter = 'block';
args = [item.block];
if (item.elem) {
getter = 'elem';
args.push(item.elem);
}
if (item.mod) {
getter += '-mod';
args.push(item.mod);
if (item.val) {
getter += '-val';
args.push(item.val);
}
}
return this.getRel(getter, args);
}
return '';
}
|
javascript
|
{
"resource": ""
}
|
|
q50956
|
train
|
function(block, mod) {
return PATH.join.apply(null,
[block,
'_' + mod,
block + '_' + mod]);
}
|
javascript
|
{
"resource": ""
}
|
|
q50957
|
train
|
function(path) {
if (PATH.isAbsolute(path)) path = PATH.relative(this.dir, path);
var matchTechs = this.matchTechsOrder().map(function(t) {
return this.getTech(t);
}, this);
return this.matchOrder().reduce(function(match, matcher) {
// Skip if already matched
if (match) return match;
// Try matcher
match = this.match(matcher, path);
// Skip if not matched
if (!match) return false;
// Try to match for tech
match.tech = matchTechs.reduce(function(tech, t) {
if (tech || !t.matchSuffix(match.suffix)) return tech;
return t.getTechName();
}, match.tech);
return match;
}.bind(this), false);
}
|
javascript
|
{
"resource": ""
}
|
|
q50958
|
train
|
function(blockName) {
// TODO: support any custom naming scheme, e.g. flat, when there are
// no directories for blocks
var decl = this.getDeclByIntrospection(PATH.dirname(this.get('block', [blockName])));
return decl.length? decl.shift() : {};
}
|
javascript
|
{
"resource": ""
}
|
|
q50959
|
train
|
function(from) {
this._declIntrospector || (this._declIntrospector = this.createIntrospector({
creator: function(res, match) {
if (match && match.tech) {
return this._mergeMatchToDecl(match, res);
}
return res;
}
}));
return this._declIntrospector(from);
}
|
javascript
|
{
"resource": ""
}
|
|
q50960
|
train
|
function(opts) {
var level = this;
if (!opts) opts = {
opts: false
};
// clone opts
opts = bemUtil.extend({}, opts);
// set default options
opts.from || (opts.from = '.');
// initial value initializer
opts.init || (opts.init = function() {
return [];
});
// paths filter function
opts.filter || (opts.filter = function(path) {
return !this.isIgnorablePath(path);
});
// matcher function
opts.matcher || (opts.matcher = function(path) {
return this.matchAny(path);
});
// result creator function
opts.creator || (opts.creator = function(res, match) {
if (match && match.tech) res.push(match);
return res;
});
/**
* Introspection function.
*
* @param {String} [from] Relative path to subdirectory of level directory to start introspection from.
* @param {*} [res] Initial introspection value to extend.
* @return {*}
*/
return function(from, res) {
if (opts.opts === false) {
level.scanFiles();
return level.files.blocks;
}
from = PATH.resolve(level.dir, from || opts.from);
res || (res = opts.init.call(level));
bemUtil.fsWalkTree(from, function(path) {
res = opts.creator.call(level, res, opts.matcher.call(level, path));
},
opts.filter,
level);
return res;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q50961
|
train
|
function(path, opts) {
var bemDir = PATH.join(path, '.bem'),
levels = PATH.join(bemDir, 'levels'),
// .bem/levels/create blocks.js level prototype
blocks = this.createLevel({
forceTech: ['examples', 'tech-docs'],
outputDir: levels,
force: opts.force
}, ['blocks.js']),
// create .bem/levels/bundles.js level prototype
bundles = this.createLevel({
forceTech: ['bemjson.js', 'blocks'],
outputDir: levels,
force: opts.force
}, ['bundles.js']),
// create .bem/levels/examples.js level prototype
examples = bundles.then(function() {
return this.createLevel({
level: PATH.resolve(levels, 'bundles.js'),
outputDir: levels,
force: opts.force
}, ['examples.js']);
}.bind(this)),
// create .bem/levels/docs.js level prototype
docs = this.createLevel({
forceTech: ['md'],
outputDir: levels,
force: opts.force
}, ['docs.js']),
// create .bem/levels/tech-docs.js level prototype
techDocs = this.createLevel({
forceTech: ['docs', 'md'],
outputDir: levels,
force: opts.force,
level: 'simple'
}, ['tech-docs.js']),
// create .bem/techs and node_modules/ directories
dirs = Q.all([
U.mkdirp(PATH.join(bemDir, 'techs')),
U.mkdirp(PATH.join(path, 'node_modules'))
]),
// run `npm link bem` command
linkBem = U.exec('npm link bem', { cwd: path, env: process.env });
return Q.all([blocks, bundles, examples, docs, techDocs, dirs, linkBem])
.then(function() {});
}
|
javascript
|
{
"resource": ""
}
|
|
q50962
|
train
|
function() {
return Q.all(this.tech
.getPaths(PATH.resolve(this.root, this.output), this.tech.getBuildSuffixes())
.map(function(path) {
return QFS.lastModified(path)
.fail(function() {
return -1;
});
}))
.spread(Math.min);
}
|
javascript
|
{
"resource": ""
}
|
|
q50963
|
vimeo_fetcher
|
train
|
async function vimeo_fetcher(env) {
tpl.query.url = env.src;
let response;
try {
response = await env.self.request(url.format(tpl));
} catch (err) {
if (err.statusCode) {
throw new EmbedzaError(
`Vimeo fetcher: Bad response code: ${err.statusCode}`,
'EHTTP',
err.statusCode);
}
throw err;
}
// that should not happen
/* istanbul ignore next */
if (response.statusCode !== 200) {
throw new EmbedzaError(
`Vimeo fetcher: Bad response code: ${response.statusCode}`,
'EHTTP',
response.statusCode);
}
try {
env.data.oembed = JSON.parse(response.body);
} catch (__) {
throw new EmbedzaError(
"Vimeo fetcher: Can't parse oembed JSON response",
'ECONTENT');
}
}
|
javascript
|
{
"resource": ""
}
|
q50964
|
findMeta
|
train
|
function findMeta(meta, names) {
if (!meta) return null;
if (!_.isArray(names)) names = [ names ];
let record;
names.some((name) => {
record = _.find(meta, (item) => item.name === name);
return record;
});
return (record || {}).value;
}
|
javascript
|
{
"resource": ""
}
|
q50965
|
wlCheck
|
train
|
function wlCheck(wl, record, value) {
if (!value) value = 'allow';
let wlItem = _.get(wl, record);
if (_.isArray(wlItem)) return wlItem.indexOf(value) !== -1;
return wlItem === value;
}
|
javascript
|
{
"resource": ""
}
|
q50966
|
createUpdateRDF
|
train
|
function createUpdateRDF(manifest) {
var header = [{
name: "RDF",
attrs: {
"xmlns": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"xmlns:em": "http://www.mozilla.org/2004/em-rdf#"
},
children: []
}];
var description = {
name: "Description",
attrs: {
"about": "urn:mozilla:extension:" + getID(manifest)
},
children: []
};
var enginesDescription = {
name: "Description",
children: []
};
var updateRdfTree = {
name: "em:updates",
children: [
{
name: "Seq",
children: [
{
name: "li",
children: []
}
]
}
]
};
var jetpackMeta = {
"em:version": manifest.version || "0.0.0"
};
enginesDescription.children.push(jetpackMeta);
var engines = Object.keys(manifest.engines || {});
// If engines defined, use them
if (engines.length) {
engines.forEach(function(engine) {
enginesDescription.children.push(createApplication(
engine, manifest.engines[engine]));
});
}
// Otherwise, assume default Firefox support
else {
enginesDescription.children.push(createApplication("Firefox"));
}
//we add the updateLink for each engine
enginesDescription.children.forEach(function(descriptionData, index) {
if (descriptionData.hasOwnProperty("em:targetApplication")) {
enginesDescription.children[index][Object.keys(descriptionData)].
Description["em:updateLink"] = manifest.updateLink;
}
});
updateRdfTree.children[0].children[0].children.push(enginesDescription);
description.children.push(updateRdfTree);
header[0].children.push(description);
var xml = jsontoxml(header, {
prettyPrint: true,
xmlHeader: true,
indent: " ",
escape: true
});
return xml;
}
|
javascript
|
{
"resource": ""
}
|
q50967
|
filter
|
train
|
function filter(options, includes, root, filepath, stat) {
var paths = path.relative(root, filepath).split(path.sep);
// always include test/tests directory when running jpm test
if (options.command === "test") {
if (/^tests?$/.test(paths[0])) {
if (paths.length === 1 && stat.isDirectory()) {
return true;
}
if (paths.length > 1) {
return true;
}
}
}
return includes.indexOf(filepath) !== -1;
}
|
javascript
|
{
"resource": ""
}
|
q50968
|
ignore
|
train
|
function ignore(dir, options) {
var jpmignore = path.join(dir, ".jpmignore");
var defaultRules = ["*.zip", ".*", "test/", ".jpmignore", "*.xpi"];
return utils.getManifest({addonDir: options.addonDir})
.then(function(manifest) {
return fs.exists(jpmignore);
})
.then(function(exists) {
if (exists) {
if (options.verbose) {
console.log(".jpmignore found");
}
return fs.stat(jpmignore)
.then(function(stat) {
if (stat.isFile()) {
return fs.readFile(jpmignore)
.then(function(data) {
return data.toString().replace(/[\r\n]/, "\n").split("\n");
});
} else {
console.warn(
".jpmignore is not a file, fallback to use " +
"default filter rules");
return defaultRules;
}
});
} else {
if (options.verbose) {
console.warn(
".jpmignore does not exist, fallback to use default filter rules");
}
return defaultRules;
}
})
.then(function(lines) {
// Add "manifest.json" to always exclude it from the xpi (See
// https://github.com/mozilla-jetpack/jpm/pull/566 for rationale),
// but ensure the "webextension/manifest.json", that is used for the
// webextension embedded in an SDK hybrid add-on, is always included
// (See https://github.com/mozilla-jetpack/jpm/pull/578 for rationale).
lines = ["manifest.json", "!webextension/manifest.json"].concat(lines);
var rules = lines.filter(function(e) {
// exclude blank lines and comments
return !/^\s*(#|$)/.test(e);
});
// http://git-scm.com/docs/gitignore
// the last matching pattern decides the outcome
// reverse rules and break at first matched rule when filtering
return rules.reverse().map(function(rule) {
return new Minimatch(rule, {
matchBase: true,
dot: true,
flipNegate: true
});
});
})
.then(function(rules) {
return listdir(dir, rules, dir, true);
});
}
|
javascript
|
{
"resource": ""
}
|
q50969
|
listdir
|
train
|
function listdir(dir, rules, root, included) {
return fs.readdir(dir)
.then(function(files) {
return when.all(files.map(function(f) {
f = path.join(dir, f);
return when(fs.stat(f), function(stat) {
return {
path: f,
isDirectory: stat.isDirectory()
};
});
}));
})
.then(function(arr) {
var files = [];
var subdirs = [];
arr.forEach(function(e) {
if (e.isDirectory) {
subdirs.push(e.path);
} else {
files.push(e.path);
}
});
files = files.filter(function(f) {
return filter(f, rules, root, false, included);
});
return when.all(subdirs.map(function(d) {
return listdir(d, rules, root, filter(d, rules, root, true, included));
}))
.then(function(list) {
list = list.reduce(function(ret, i) {
return ret.concat(i);
}, files);
// include current dir only if at least one of its children is included
if (list.length > 0) {
list.push(dir);
}
return list;
});
});
}
|
javascript
|
{
"resource": ""
}
|
q50970
|
filter
|
train
|
function filter(p, rules, root, isDirectory, included) {
p = path.relative(root, p);
for (var i in rules) {
var rule = rules[i];
if (isDirectory) {
if (rule.match(p) || rule.match("/" + p) ||
rule.match(p + "/") || rule.match("/" + p + "/")
) {
return rule.negate;
}
} else {
if (rule.match(p) || rule.match("/" + p)) {
return rule.negate;
}
}
}
return included;
}
|
javascript
|
{
"resource": ""
}
|
q50971
|
log
|
train
|
function log(type) {
var messages = Array.prototype.slice.call(arguments);
messages.shift();
// Concatenate default strings and first message argument into
// one string so we can use `printf`-like replacement
var first = "JPM [" + type + "] " + (messages.shift() + "");
if (process.env.NODE_ENV !== "test") {
console.log.apply(console, [first].concat(messages)); // eslint-disable-line no-console
}
}
|
javascript
|
{
"resource": ""
}
|
q50972
|
getManifest
|
train
|
function getManifest(options) {
options = _.assign({
addonDir: process.cwd(),
xpiPath: null
}, options);
return when.promise(function(resolve, reject) {
if (options.xpiPath) {
return getXpiInfo(options.xpiPath)
.then(function(xpiInfo) {
resolve(xpiInfo.manifest);
})
.catch(reject);
} else {
var json = path.join(options.addonDir, "package.json");
var manifest = {};
try {
manifest = require(json);
} catch (e) {} // eslint-disable-line no-empty
return resolve(manifest);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q50973
|
getXpiInfo
|
train
|
function getXpiInfo(xpiPath) {
return extractXPI(xpiPath)
.then(function(tmpXPI) {
var getInfo;
var packageFile = path.join(tmpXPI.path, "package.json");
var installRdfFile = path.join(tmpXPI.path, "install.rdf");
if (fileExists(packageFile)) {
getInfo = getXpiInfoFromManifest(require(packageFile));
} else if (fileExists(installRdfFile)) {
getInfo = nodefn.call(fs.readFile, installRdfFile)
.then(function(data) {
return getXpiInfoFromInstallRdf(data);
});
} else {
getInfo = when.reject(
new Error("Cannot get info: no manifest found in this XPI"));
}
return getInfo
.catch(function(err) {
try {
tmpXPI.remove();
} catch (e) {} // eslint-disable-line no-empty
throw err;
})
.then(function(info) {
tmpXPI.remove();
return info;
});
});
}
|
javascript
|
{
"resource": ""
}
|
q50974
|
addPrefs
|
train
|
function addPrefs(profile, options) {
var userPrefs = options.prefs || {};
return when.promise(function(resolve, reject) {
Object.keys(userPrefs).forEach(function(key) {
profile.setPreference(key, userPrefs[key]);
});
profile.updatePreferences();
resolve(profile);
});
}
|
javascript
|
{
"resource": ""
}
|
q50975
|
Checkit
|
train
|
function Checkit(validations, options) {
if (!(this instanceof Checkit)) {
return new Checkit(validations, options);
}
this.conditional = [];
options = _.clone(options || {});
this.labels = options.labels || {};
this.messages = options.messages || {};
this.language = Checkit.i18n[options.language || Checkit.language] || {};
this.labelTransform = options.labelTransform || Checkit.labelTransform
this.validations = prepValidations(validations || {});
}
|
javascript
|
{
"resource": ""
}
|
q50976
|
checkSync
|
train
|
function checkSync(validations, input, key) {
var arr = new Checkit(validations).runSync(input);
if (arr[0] === null) return arr;
if (arr[0] instanceof CheckitError) {
return [arr[0].get(key), null]
}
return arr;
}
|
javascript
|
{
"resource": ""
}
|
q50977
|
Runner
|
train
|
function Runner(checkit, target, context) {
this.errors = {};
this.checkit = checkit;
this.conditional = checkit.conditional;
this.target = _.clone(target || {})
this.context = _.clone(context || {})
this.validator = new Validator(this.target, checkit.language)
}
|
javascript
|
{
"resource": ""
}
|
q50978
|
addVerifiedConditional
|
train
|
function addVerifiedConditional(validations, conditional) {
_.each(conditional[0], function(val, key) {
validations[key] = validations[key] || [];
validations[key] = validations[key].concat(val);
})
}
|
javascript
|
{
"resource": ""
}
|
q50979
|
checkConditional
|
train
|
function checkConditional(runner, conditional) {
try {
return conditional[1].call(runner, runner.target, runner.context);
} catch (e) {}
}
|
javascript
|
{
"resource": ""
}
|
q50980
|
processItemAsync
|
train
|
function processItemAsync(runner, currentValidation, key, context) {
return Promise.resolve(true).then(function() {
return processItem(runner, currentValidation, key, context)
});
}
|
javascript
|
{
"resource": ""
}
|
q50981
|
train
|
function(val, item) {
if (_.isString(val)) return val.indexOf(item) !== -1;
if (_.isArray(val)) return _.indexOf(val, item) !== -1;
if (_.isObject(val)) return _.has(val, item);
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q50982
|
train
|
function(val, param) {
return checkNumber(val) || checkNumber(param) || parseFloat(val) <= parseFloat(param);
}
|
javascript
|
{
"resource": ""
}
|
|
q50983
|
train
|
function(flat) {
return this.transform(function(acc, val, key) {
var json = val.toJSON();
acc[key] = flat && _.isArray(json) ? json[0] : json
}, {});
}
|
javascript
|
{
"resource": ""
}
|
|
q50984
|
prepValidations
|
train
|
function prepValidations(validations) {
validations = _.cloneDeep(validations);
for (var key in validations) {
var validation = validations[key];
if (!_.isArray(validation)) validations[key] = validation = [validation];
for (var i = 0, l = validation.length; i < l; i++) {
validation[i] = assembleValidation(validation[i]);
}
}
return validations;
}
|
javascript
|
{
"resource": ""
}
|
q50985
|
mergeQueries
|
train
|
function mergeQueries(query, options) {
if (options == null) {
return query;
}
Object.keys(options).forEach(key => {
let label = key;
let value = options[key];
validateProp(key, value);
switch (key) {
case 'orderByKey':
label = orderedBy;
value = orderByKey;
break;
case 'orderByPriority':
label = orderedBy;
value = orderByPriority;
break;
case 'orderByValue':
label = orderedBy;
value = orderByValue;
break;
case 'orderByChild':
label = orderedBy;
break;
default:
break;
}
query[label] = value;
});
return query;
}
|
javascript
|
{
"resource": ""
}
|
q50986
|
validateProp
|
train
|
function validateProp(key, value) {
const type = typeof value;
switch (key) {
case 'orderByKey':
case 'orderByPriority':
case 'orderByValue':
if (!value) {
throw new Error(`"query.${key}" should not be set to false. Set it off by setting an other order.`);
}
break;
case 'orderByChild':
if (value == null) {
throw new Error('"query.orderByChild" should not be set to null. Set it off by setting an other order.');
}
if (type !== 'string') {
throw new Error('"query.orderByChild" should be a string or null.');
}
break;
case 'startAt':
case 'endAt':
case 'equalTo':
if (
value !== null &&
type !== 'string' &&
type !== 'number' &&
type !== 'boolean'
) {
throw new Error(`query.${key} should be a string, a number, a boolean or null.`);
}
break;
case 'limitToFirst':
case 'limitToLast':
if (value != null && type !== 'number') {
throw new Error(`query.${key} should be a number or null.`);
}
break;
default:
throw new Error(`"${key}" is not a query parameter.`);
}
}
|
javascript
|
{
"resource": ""
}
|
q50987
|
setInflectType
|
train
|
function setInflectType (inflect, types) {
// use inflections if set as object else start fresh
const out = typeof inflect === 'boolean' ? {} : inflect
// if inflect is boolean use it for all types,
// else use default for unset types
const setInflect = typeof inflect === 'boolean' ? inflect : inflectTypeDef
// For each Type set inflection, if not set
for (const t of types) {
const plural = inflection.transform(t, typeInflections[1])
if (!(t in out))
out[t] = setInflect
// allow checking on pluralized too
if (!(plural in out))
out[plural] = out[t]
}
return out
}
|
javascript
|
{
"resource": ""
}
|
q50988
|
processBsbError
|
train
|
function processBsbError(err /*: Error | string */) /*: Error[] */ {
if (typeof err === 'string') {
const errors = errorRegexes
// $FlowIssue: err is definitely a string
.map((r /*: RegExp */) => err.match(r))
.reduce((a, s) => a.concat(s), [])
.filter(x => x)
return (errors.length > 0 ? errors : [err]).map(e => new Error(e))
} else {
return [err]
}
}
|
javascript
|
{
"resource": ""
}
|
q50989
|
runBuild
|
train
|
function runBuild(cwd /*: string */) /*: Promise<string> */ {
return new Promise((resolve, reject) => {
exec(bsb, {maxBuffer: Infinity, cwd}, (err, stdout, stderr) => {
const output = `${stdout.toString()}\n${stderr.toString()}`
if (err) {
reject(output)
} else {
resolve(output)
}
})
})
}
|
javascript
|
{
"resource": ""
}
|
q50990
|
compileFile
|
train
|
function compileFile(
buildDir /*: string */,
moduleType /*: BsModuleFormat | 'js' */,
path /*: string */,
id /*: ?string */ = null,
) /*: Promise<Compilation> */ {
if (id && buildRuns[id] !== undefined) {
buildRuns[id] = runBuild(buildDir)
}
const buildProcess = id ? buildRuns[id] : runBuild(buildDir)
return buildProcess
.then(
output =>
new Promise((resolve, reject) => {
readFile(path, (err, res) => {
if (err) {
resolve({
src: undefined,
warnings: [],
errors: [err],
})
} else {
const src = utils.transformSrc(moduleType, res.toString())
resolve({
src,
warnings: utils.processBsbWarnings(output),
errors: [],
})
}
})
}),
)
.catch(err => ({
src: undefined,
warnings: [],
errors: utils.processBsbError(err),
}))
}
|
javascript
|
{
"resource": ""
}
|
q50991
|
compileFileSync
|
train
|
function compileFileSync(
buildDir /*: string */,
moduleType /*: BsModuleFormat | 'js' */,
path /*: string */,
) /*: string */ {
try {
runBuildSync(buildDir)
} catch (e) {
throw utils.processBsbError(e.output.toString())
}
const res = readFileSync(path)
return utils.transformSrc(moduleType, res.toString())
}
|
javascript
|
{
"resource": ""
}
|
q50992
|
compact
|
train
|
function compact(value, keepNewlines) {
var check = keepNewlines ? / +/g : /\s+/g;
return value.replace(check, ' ');
}
|
javascript
|
{
"resource": ""
}
|
q50993
|
Helpers
|
train
|
function Helpers(options) {
this.config = {};
for (var key in options || {}) {
this.config[key] = options[key];
}
this.ancestor = [];
}
|
javascript
|
{
"resource": ""
}
|
q50994
|
Minimize
|
train
|
function Minimize(parser, options) {
if ('object' !== typeof options) {
options = parser || {};
options.dom = options.dom || {};
parser = void 0;
}
this.emits = emits;
this.plugins = Object.create(null);
this.helpers = new Helpers(options);
//
// Prepare the parser.
//
this.htmlparser = parser || new html.Parser(
new html.DomHandler(this.emits('read')),
options.dom
);
//
// Register plugins.
//
this.plug(options.plugins);
}
|
javascript
|
{
"resource": ""
}
|
q50995
|
traverser
|
train
|
function traverser(element, content, next) {
return function () {
return minimize.traverse(element.children, content, sync, step(element, 'close', next))
};
}
|
javascript
|
{
"resource": ""
}
|
q50996
|
step
|
train
|
function step(element, type, cb) {
return function generate(error, html) {
html += minimize.helpers[type](element);
return returns(error, html, cb);
}
}
|
javascript
|
{
"resource": ""
}
|
q50997
|
run
|
train
|
function run(element, cb) {
return function level(error, content) {
debug('Traversing children of element %s', element.name);
if (sync) {
return traverser(element, content, cb)();
}
setImmediate(traverser(element, content, cb));
}
}
|
javascript
|
{
"resource": ""
}
|
q50998
|
createPlug
|
train
|
function createPlug(element) {
return function plug(plugin, fn) {
fn = fn || minimize.emits('plugin');
debug('Running plugin for element %s', element.name);
minimize.plugins[plugin].element.call(minimize, element, fn);
}
}
|
javascript
|
{
"resource": ""
}
|
q50999
|
reduce
|
train
|
function reduce(html, element, next) {
//
// Run the registered plugins before the element is processed.
// Note that the plugins are not run in order.
//
if (sync) {
plugins.forEach(createPlug(element));
return open(element, html, run(element, next));
}
async.eachSeries(plugins, createPlug(element), function finished(error) {
if (error) return next(error);
return open(element, html, run(element, next));
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.