_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q42800 | hasFullCoverage | train | function hasFullCoverage(cov) {
for (var name in cov) {
var file = cov[name];
if (file instanceof Array) {
if (file.coverage !== 100) {
return false;
}
}
}
return true;
} | javascript | {
"resource": ""
} |
q42801 | send | train | function send(id) {
if (msg.ack) { server._rememberAck(msg.ack, ws.broker_uuid); }
var destWs = server.id2ws[id];
if (destWs) {
if (destWs.readyState === WebSocket.OPEN) {
destWs.send(JSON.stringify({
action: 'message',
message: msg.message,
ack: msg.ack,
from: server.ws2id[ws.broker_uuid]
}));
} else {
err = new Error('Unable to send message. Client "'+id+'" disconnected');
server.emit('error', err);
}
} else {
server.emit('warn', new Error('Unable to send message. Client "'+id+'" unknown'));
}
} | javascript | {
"resource": ""
} |
q42802 | load | train | function load(filename) {
return function(cb) {
var file = path.join(process.cwd(), filename)
, json = require(file)
, model = exports[json.table]
, rows = json.rows;
console.log('Loading', file);
run();
function run() {
var row = rows.shift();
if(row !== undefined) {
model.create(row, function(err) {
if(err) {
cb(err);
} else {
run();
}
});
} else {
cb();
}
}
};
} | javascript | {
"resource": ""
} |
q42803 | connect | train | function connect(uri, cb) {
pg.connect(uri, function(err, client, done) {
// Backwards compatibility with pg
if(typeof done === 'undefined') { done = noop; }
if(err) {
cb(err, null, done);
} else {
cb(null, client, done);
}
});
} | javascript | {
"resource": ""
} |
q42804 | getClient | train | function getClient(uri, cb) {
if(typeof uri === 'function') {
cb = uri;
uri = conf.db;
}
connect(uri, function(err, client, done) {
if(err) {
cb(err, null, done);
} else {
cb(null, client, done);
}
});
} | javascript | {
"resource": ""
} |
q42805 | getFirstReturnStatement | train | function getFirstReturnStatement(node) {
if (!node || !node.body) {
return;
}
if (node.body.type === 'BlockStatement') {
node = node.body;
}
for (var i = 0; i < node.body.length; i++) {
if (node.body[i].type === 'ReturnStatement') {
return node.body[i];
}
}
} | javascript | {
"resource": ""
} |
q42806 | get | train | function get(tableName, fieldNames, where, orderBy) {
if (orderBy && !checkOrderBy(orderBy)) {
throw new Error('Invalid arg: orderBy');
}
if (!db) {
throw new Error('Not connected');
}
let sql = `SELECT ${fieldNames.join(',')} FROM ${tableName}`;
if (where) {
sql += ` WHERE ${where}`;
}
if (orderBy) {
sql += ` ORDER BY ${orderBy.join(',')}`;
}
return new Promise(((resolve, reject) => {
db.get(sql, [], (error, row) => {
if (error) {
reject(error);
} else {
resolve(row);
}
});
}));
} | javascript | {
"resource": ""
} |
q42807 | all | train | function all(tableName, fieldNames, where, orderBy, limit = null, join = null) {
if (orderBy && !checkOrderBy(orderBy)) {
throw new Error('Invalid arg: orderBy');
}
if (!db) {
throw new Error('Not connected');
}
let sql = `SELECT ${fieldNames.join(',')} FROM ${tableName}`;
if (join) {
sql += ` JOIN ${join}`;
}
if (where) {
sql += ` WHERE ${where}`;
}
if (orderBy) {
sql += ` ORDER BY ${orderBy.join(',')}`;
}
if (limit) {
sql += ` LIMIT ${limit}`;
}
return new Promise(((resolve, reject) => {
db.all(sql, [], (error, rows) => {
if (error) {
reject(error);
} else {
resolve(rows);
}
});
}));
} | javascript | {
"resource": ""
} |
q42808 | train | function(db) {
if (!db.type) {
return defaultDbType;
}
return dbTypes.find(function(dbType) {
return dbType.name === db.type;
}) || null;
} | javascript | {
"resource": ""
} | |
q42809 | train | function(obj, keys) {
return keys.reduce(function(memo, key) {
if (obj[key] !== undefined) {
memo[key] = obj[key];
}
return memo;
}, {});
} | javascript | {
"resource": ""
} | |
q42810 | train | function(doc) {
if (!this._props) {
return doc;
}
return this._props.reduce(function(obj, prop) {
if (doc.hasOwnProperty(prop)) {
obj[prop] = doc[prop];
}
return obj;
}, {});
} | javascript | {
"resource": ""
} | |
q42811 | train | function(doc) {
if (!this.isValid(doc)) {
return Promise.resolve(false);
}
var props = pick(doc, this._uniq);
if (!Object.keys(props).length) {
return Promise.resolve(true);
}
return this._dbApi.isAdmissible(doc, props);
} | javascript | {
"resource": ""
} | |
q42812 | train | function(doc) {
var that = this;
doc = that._in_map(doc);
return this._init.then(function() {
return that.isAdmissible(doc);
}).then(function(admissible) {
if (!admissible) {
throw new Error('Document not admissible');
}
doc = that.clean(doc);
if (that._index) {
delete doc[that._index];
}
return that.getNextIndex();
}).then(function(max) {
if (that._index && typeof max === 'number') {
doc[that._index] = max;
}
return that._dbApi.create(doc).then(function(doc) {
if (!doc) {
throw new Error('Document not created');
}
return doc;
});
});
} | javascript | {
"resource": ""
} | |
q42813 | train | function(props) {
var that = this;
return this._dbApi.find(props || {}).then(function(docs) {
return docs.map(that._out_map);
});
} | javascript | {
"resource": ""
} | |
q42814 | train | function(id) {
var that = this;
return this._dbApi.read(id).then(function(doc) {
return that._readDoc(doc);
});
} | javascript | {
"resource": ""
} | |
q42815 | train | function(key) {
var that = this;
if (!this._key || !key) {
return Promise.reject(new Error('No unique key specified'));
}
var props = {};
props[this._key] = key;
return this._dbApi.find(props).then(function(docs) {
return that._readDoc(docs[0]);
});
} | javascript | {
"resource": ""
} | |
q42816 | train | function(index) {
var that = this;
var props = this._propIndex(index);
if (!props) {
return Promise.reject(new Error('No auto-indexing key specified'));
}
return this._dbApi.find(props).then(function(docs) {
return that._readDoc(docs[0]);
});
} | javascript | {
"resource": ""
} | |
q42817 | train | function(doc, updates) {
updates = this._in_map(updates || {});
Object.keys(doc).forEach(function(prop) {
if (updates.hasOwnProperty(prop)) {
doc[prop] = updates[prop];
}
});
if (!this.isValid(doc)) {
throw new Error('Updated document is invalid');
}
var id = doc[this._dbType.id];
this._uniq.forEach(function(uniq) {
delete doc[uniq];
});
doc = this.clean(doc);
return this._dbApi.update(id, doc);
} | javascript | {
"resource": ""
} | |
q42818 | train | function(id, updates) {
var that = this;
return this.read(id).then(function(doc) {
return that._updateDoc(doc, updates);
});
} | javascript | {
"resource": ""
} | |
q42819 | train | function(key, updates) {
var that = this;
if (!this._key || !key) {
return Promise.reject(new Error('No unique key specified'));
}
return this.readByKey(key).then(function(doc) {
return that._updateDoc(doc, updates);
});
} | javascript | {
"resource": ""
} | |
q42820 | train | function(index, updates) {
var that = this;
return this.readByIndex(index).then(function(doc) {
return that._updateDoc(doc, updates);
});
} | javascript | {
"resource": ""
} | |
q42821 | train | function(key) {
var that = this;
if (!this._key || !key) {
return Promise.reject(new Error('No unique key specified'));
}
return this.readByKey(key).then(function(doc) {
return that.delete(doc[that._dbType.id]);
});
} | javascript | {
"resource": ""
} | |
q42822 | train | function(index) {
var that = this;
return this.readByIndex(index).then(function(doc) {
return that.delete(doc[that._dbType.id]);
});
} | javascript | {
"resource": ""
} | |
q42823 | train | function(operation, res) {
var that = this;
var method = res.req.method;
return operation.then(function(doc) {
if (method === 'POST') {
if (that._path && (that._key || that._index)) {
res.header('Location', '/' + that._path + '/' + doc[that._key || that._index]);
}
return res.status(201).json(doc);
}
return res.status(200).json(doc);
}, function(err) {
console.error(err.message);
if (method === 'POST' || method === 'PUT') {
return res.status(409).end();
}
if (method === 'GET') {
res.status(404).end();
}
return res.status(500).end();
});
} | javascript | {
"resource": ""
} | |
q42824 | get_trit | train | function get_trit(n,i) {
// convert entire number to balanced ternary string then slice
// would be nice to extract without converting everything, see extract_digit(), which
// works for unbalanced ternary, but balanced converts 2 -> 1i, so individual digit extraction
// is more difficult -- see https://en.wikipedia.org/wiki/Balanced_ternary#Conversion_from_ternary
var s = n2bts(n);
return ~~BT_DIGIT_TO_N[s.charAt(s.length - i - 1)];
} | javascript | {
"resource": ""
} |
q42825 | resolveFunctionList | train | function resolveFunctionList (functionList, basedir) {
if (!functionList) return []
return (Array.isArray(functionList) ? functionList : [functionList])
.map(function (proc) {
if (typeof (proc) === 'string') {
proc = require(resolve.sync(proc, { basedir: basedir }))
}
return toAsync(proc)
})
} | javascript | {
"resource": ""
} |
q42826 | processJson | train | function processJson(obj) {
for (var i in obj) {
if (typeof(obj[i]) === "object") {
processJson(obj[i]); // found an obj or array keep digging
} else if (obj[i] !== null){
obj[i] = getFunctionNameAndArgs(obj[i]);// not an obj or array, check contents
}
}
return obj;
} | javascript | {
"resource": ""
} |
q42827 | getFunctionNameAndArgs | train | function getFunctionNameAndArgs(value) {
var pattern = /^(.*)\{\{([^()]+?)(\((.+)\))?\}\}(.*)$/g,
match, func, args;
var argArray = [], surroundings = [];
var retValue;
while (match = pattern.exec(value)) {
surroundings[0] = match[1];
func = match[2];
args = match[4];
surroundings[1] = match[5];
}
if (args !== undefined ){
if (args.indexOf("[") !== -1){
// is an array as string
args = JSON.parse(args);
argArray.push(args);
} else {
// one or more string/number params
args = args.replace(/, /gi, ",");
args = args.replace(/'/gi, "", "gi");
argArray = args.split(',');
}
}
// return value if no Faker method is detected
retValue = func ?
executeFunctionByName(func,argArray) :
value;
if(surroundings[0]) { // prefix
retValue = surroundings[0] + retValue;
}
if(surroundings[1]) { // postfix
retValue += surroundings[1];
}
return retValue;
} | javascript | {
"resource": ""
} |
q42828 | executeFunctionByName | train | function executeFunctionByName(functionName, args) {
var namespaces = functionName.split(".");
var nsLength = namespaces.length;
var context = Faker;
var parentContext = Faker;
if (namespaces[0].toLowerCase() === 'definitions'){
grunt.log.warn('The definitions module from Faker.js is not avail in this task.');
return;
}
for(var i = 0; i < nsLength; i++) {
context = context[namespaces[i]];
}
for(var j = 0; j < nsLength - 1; j++) {
parentContext = parentContext[namespaces[j]];
}
return context.apply(parentContext, args);
} | javascript | {
"resource": ""
} |
q42829 | train | function(){
if(errors.length) return cb(errors);
var transform = opts.transform || function(_result, _cb){
_cb(null, _result);
};
transform(result, function(err, _result){
if(err){
errors.push(formatError(err, key));
cb(errors);
}else{
cb(null, _result);
}
});
} | javascript | {
"resource": ""
} | |
q42830 | train | function(text, color=[255,255,255], colorBg=[0,0,0], style="reset") {
// First check for raw RGB truecolor code... if the console scheme
// supports this then no probs... but if not - we need to degrade appropriately.
if(color.constructor === Array && colorBg.constructor === Array) {
if(config.scheme === "16M") {
return this._styleTruecolor(text, color, colorBg, style);
} else {
return this._degrade(text, color, colorBg, style);
}
} else {
throw new Error("Unrecognized or malformed RGB array values.");
}
} | javascript | {
"resource": ""
} | |
q42831 | decimalLength | train | function decimalLength(n) {
let ns = cleanNumber(n).toString();
let ems = ns.match(/e([\+\-]\d+)$/);
let e = 0;
if (ems && ems[1]) e = parseInt(ems[1]);
ns = ns.replace(/e[\-\+]\d+$/, '');
let parts = ns.split('.', 2);
if (parts.length === 1) return -e;
return parts[1].length - e;
} | javascript | {
"resource": ""
} |
q42832 | createClean | train | function createClean(inPath) {
if (!inPath) {
throw new Error('Input path argument is required');
}
return function cleanDir() {
return gulp.src(inPath, { read: false }).pipe(clean());
};
} | javascript | {
"resource": ""
} |
q42833 | Exception | train | function Exception(code, message) {
const factory = Object.create(Exception.prototype);
factory.code = code;
factory.message = message;
factory.stack = factory.toString();
return factory;
} | javascript | {
"resource": ""
} |
q42834 | someSchemasValidate | train | function someSchemasValidate(propName) {
return schema[propName].some(function (possibleType) {
var tempInput = {},
tempSchema = {},
tempErrs;
tempInput[propName] = input[propName];
tempSchema[propName] = possibleType;
tempErrs = getErrs({
input: tempInput,
schema: tempSchema,
optional: optional
});
return tempErrs.length === 0;
});
} | javascript | {
"resource": ""
} |
q42835 | firstExist | train | function firstExist(fileNames) {
const head = fileNames.slice(0, 1);
if (head.length === 0) {
return new Promise((resolve, reject) => {
resolve(false);
});
}
const tail = fileNames.slice(1);
return fileExist(head[0]).then((result) => {
if (false === result) {
return firstExist(tail);
}
return result;
});
} | javascript | {
"resource": ""
} |
q42836 | train | function(csg) {
var newpolygons = this.polygons.concat(csg.polygons);
var result = CSG.fromPolygons(newpolygons);
result.properties = this.properties._merge(csg.properties);
result.isCanonicalized = this.isCanonicalized && csg.isCanonicalized;
result.isRetesselated = this.isRetesselated && csg.isRetesselated;
return result;
} | javascript | {
"resource": ""
} | |
q42837 | train | function(matrix4x4) {
var newpolygons = this.polygons.map(function(p) {
return p.transform(matrix4x4);
});
var result = CSG.fromPolygons(newpolygons);
result.properties = this.properties._transform(matrix4x4);
result.isRetesselated = this.isRetesselated;
return result;
} | javascript | {
"resource": ""
} | |
q42838 | train | function(normal, point, length) {
var plane = CSG.Plane.fromNormalAndPoint(normal, point);
var onb = new CSG.OrthoNormalBasis(plane);
var crosssect = this.sectionCut(onb);
var midpiece = crosssect.extrudeInOrthonormalBasis(onb, length);
var piece1 = this.cutByPlane(plane);
var piece2 = this.cutByPlane(plane.flipped());
var result = piece1.union([midpiece, piece2.translate(plane.normal.times(length))]);
return result;
} | javascript | {
"resource": ""
} | |
q42839 | train | function(csg) {
if ((this.polygons.length === 0) || (csg.polygons.length === 0)) {
return false;
} else {
var mybounds = this.getBounds();
var otherbounds = csg.getBounds();
if (mybounds[1].x < otherbounds[0].x) return false;
if (mybounds[0].x > otherbounds[1].x) return false;
if (mybounds[1].y < otherbounds[0].y) return false;
if (mybounds[0].y > otherbounds[1].y) return false;
if (mybounds[1].z < otherbounds[0].z) return false;
if (mybounds[0].z > otherbounds[1].z) return false;
return true;
}
} | javascript | {
"resource": ""
} | |
q42840 | train | function(plane) {
if (this.polygons.length === 0) {
return new CSG();
}
// Ideally we would like to do an intersection with a polygon of inifinite size
// but this is not supported by our implementation. As a workaround, we will create
// a cube, with one face on the plane, and a size larger enough so that the entire
// solid fits in the cube.
// find the max distance of any vertex to the center of the plane:
var planecenter = plane.normal.times(plane.w);
var maxdistance = 0;
this.polygons.map(function(polygon) {
polygon.vertices.map(function(vertex) {
var distance = vertex.pos.distanceToSquared(planecenter);
if (distance > maxdistance) maxdistance = distance;
});
});
maxdistance = Math.sqrt(maxdistance);
maxdistance *= 1.01; // make sure it's really larger
// Now build a polygon on the plane, at any point farther than maxdistance from the plane center:
var vertices = [];
var orthobasis = new CSG.OrthoNormalBasis(plane);
vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(maxdistance, -maxdistance))));
vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(-maxdistance, -maxdistance))));
vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(-maxdistance, maxdistance))));
vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(maxdistance, maxdistance))));
var polygon = new CSG.Polygon(vertices, null, plane.flipped());
// and extrude the polygon into a cube, backwards of the plane:
var cube = polygon.extrude(plane.normal.times(-maxdistance));
// Now we can do the intersection:
var result = this.intersect(cube);
result.properties = this.properties; // keep original properties
return result;
} | javascript | {
"resource": ""
} | |
q42841 | train | function(shared) {
var polygons = this.polygons.map(function(p) {
return new CSG.Polygon(p.vertices, shared, p.plane);
});
var result = CSG.fromPolygons(polygons);
result.properties = this.properties; // keep original properties
result.isRetesselated = this.isRetesselated;
result.isCanonicalized = this.isCanonicalized;
return result;
} | javascript | {
"resource": ""
} | |
q42842 | train | function(cuberadius) {
var csg = this.reTesselated();
var result = new CSG();
// make a list of all unique vertices
// For each vertex we also collect the list of normals of the planes touching the vertices
var vertexmap = {};
csg.polygons.map(function(polygon) {
polygon.vertices.map(function(vertex) {
vertexmap[vertex.getTag()] = vertex.pos;
});
});
for (var vertextag in vertexmap) {
var pos = vertexmap[vertextag];
var cube = CSG.cube({
center: pos,
radius: cuberadius
});
result = result.unionSub(cube, false, false);
}
result = result.reTesselated();
return result;
} | javascript | {
"resource": ""
} | |
q42843 | train | function(orthobasis) {
var EPS = 1e-5;
var cags = [];
this.polygons.filter(function(p) {
// only return polys in plane, others may disturb result
return p.plane.normal.minus(orthobasis.plane.normal).lengthSquared() < EPS*EPS;
})
.map(function(polygon) {
var cag = polygon.projectToOrthoNormalBasis(orthobasis);
if (cag.sides.length > 0) {
cags.push(cag);
}
});
var result = new CAG().union(cags);
return result;
} | javascript | {
"resource": ""
} | |
q42844 | train | function() {
var abs = this.abs();
if ((abs._x <= abs._y) && (abs._x <= abs._z)) {
return CSG.Vector3D.Create(1, 0, 0);
} else if ((abs._y <= abs._x) && (abs._y <= abs._z)) {
return CSG.Vector3D.Create(0, 1, 0);
} else {
return CSG.Vector3D.Create(0, 0, 1);
}
} | javascript | {
"resource": ""
} | |
q42845 | train | function(other, t) {
var newpos = this.pos.lerp(other.pos, t);
return new CSG.Vertex(newpos);
} | javascript | {
"resource": ""
} | |
q42846 | train | function(features) {
var result = [];
features.forEach(function(feature) {
if (feature == 'volume') {
result.push(this.getSignedVolume());
} else if (feature == 'area') {
result.push(this.getArea());
}
}, this);
return result;
} | javascript | {
"resource": ""
} | |
q42847 | train | function(offsetvector) {
var newpolygons = [];
var polygon1 = this;
var direction = polygon1.plane.normal.dot(offsetvector);
if (direction > 0) {
polygon1 = polygon1.flipped();
}
newpolygons.push(polygon1);
var polygon2 = polygon1.translate(offsetvector);
var numvertices = this.vertices.length;
for (var i = 0; i < numvertices; i++) {
var sidefacepoints = [];
var nexti = (i < (numvertices - 1)) ? i + 1 : 0;
sidefacepoints.push(polygon1.vertices[i].pos);
sidefacepoints.push(polygon2.vertices[i].pos);
sidefacepoints.push(polygon2.vertices[nexti].pos);
sidefacepoints.push(polygon1.vertices[nexti].pos);
var sidefacepolygon = CSG.Polygon.createFromPoints(sidefacepoints, this.shared);
newpolygons.push(sidefacepolygon);
}
polygon2 = polygon2.flipped();
newpolygons.push(polygon2);
return CSG.fromPolygons(newpolygons);
} | javascript | {
"resource": ""
} | |
q42848 | train | function(matrix4x4) {
var newvertices = this.vertices.map(function(v) {
return v.transform(matrix4x4);
});
var newplane = this.plane.transform(matrix4x4);
if (matrix4x4.isMirroring()) {
// need to reverse the vertex order
// in order to preserve the inside/outside orientation:
newvertices.reverse();
}
return new CSG.Polygon(newvertices, this.shared, newplane);
} | javascript | {
"resource": ""
} | |
q42849 | train | function(orthobasis) {
var points2d = this.vertices.map(function(vertex) {
return orthobasis.to2D(vertex.pos);
});
var result = CAG.fromPointsNoCheck(points2d);
var area = result.area();
if (Math.abs(area) < 1e-5) {
// the polygon was perpendicular to the orthnormal plane. The resulting 2D polygon would be degenerate
// return an empty area instead:
result = new CAG();
} else if (area < 0) {
result = result.flipped();
}
return result;
} | javascript | {
"resource": ""
} | |
q42850 | train | function() {
if (!this.removed) {
this.removed = true;
if (_CSGDEBUG) {
if (this.isRootNode()) throw new Error("Assertion failed"); // can't remove root node
if (this.children.length) throw new Error("Assertion failed"); // we shouldn't remove nodes with children
}
// remove ourselves from the parent's children list:
var parentschildren = this.parent.children;
var i = parentschildren.indexOf(this);
if (i < 0) throw new Error("Assertion failed");
parentschildren.splice(i, 1);
// invalidate the parent's polygon, and of all parents above it:
this.parent.recursivelyInvalidatePolygon();
}
} | javascript | {
"resource": ""
} | |
q42851 | train | function() {
var queue = [this];
var i, node;
for (var i = 0; i < queue.length; i++) {
node = queue[i];
if(node.plane) node.plane = node.plane.flipped();
if(node.front) queue.push(node.front);
if(node.back) queue.push(node.back);
var temp = node.front;
node.front = node.back;
node.back = temp;
}
} | javascript | {
"resource": ""
} | |
q42852 | train | function() {
var u = new CSG.Vector3D(this.elements[0], this.elements[4], this.elements[8]);
var v = new CSG.Vector3D(this.elements[1], this.elements[5], this.elements[9]);
var w = new CSG.Vector3D(this.elements[2], this.elements[6], this.elements[10]);
// for a true orthogonal, non-mirrored base, u.cross(v) == w
// If they have an opposite direction then we are mirroring
var mirrorvalue = u.cross(v).dot(w);
var ismirror = (mirrorvalue < 0);
return ismirror;
} | javascript | {
"resource": ""
} | |
q42853 | train | function(distance) {
var newpoint = this.point.plus(this.axisvector.unit().times(distance));
return new CSG.Connector(newpoint, this.axisvector, this.normalvector);
} | javascript | {
"resource": ""
} | |
q42854 | train | function(pathradius, resolution) {
var sides = [];
var numpoints = this.points.length;
var startindex = 0;
if (this.closed && (numpoints > 2)) startindex = -1;
var prevvertex;
for (var i = startindex; i < numpoints; i++) {
var pointindex = i;
if (pointindex < 0) pointindex = numpoints - 1;
var point = this.points[pointindex];
var vertex = new CAG.Vertex(point);
if (i > startindex) {
var side = new CAG.Side(prevvertex, vertex);
sides.push(side);
}
prevvertex = vertex;
}
var shellcag = CAG.fromSides(sides);
var expanded = shellcag.expandedShell(pathradius, resolution);
return expanded;
} | javascript | {
"resource": ""
} | |
q42855 | buildOnce | train | function buildOnce(config) {
// verify config
if (!lintConfig(config)) throw new Error('invalid config')
// set default holder
if (!config.holder) {
config.holder = { name: 'app', stub: 'epii' }
}
// prepare static dir
shell.mkdir('-p', config.$path.target.client)
shell.mkdir('-p', config.$path.target.vendor)
// process source
pureRecipe(config, CONTEXT)
viewRecipe(config, CONTEXT)
sassRecipe(config, CONTEXT)
fileRecipe(config, CONTEXT)
} | javascript | {
"resource": ""
} |
q42856 | watchBuild | train | function watchBuild(config) {
// verify config
if (!lintConfig(config)) throw new Error('invalid config')
// set development env
CONTEXT.env = 'development'
// build once immediately
buildOnce(config)
// bind watch handler
assist.tryWatch(
config.$path.source.client,
function (e, file) {
if (!file) return
CONTEXT.entries.push(path.join(config.$path.source.client, file))
buildOnce(config, CONTEXT)
CONTEXT.entries = []
}
)
} | javascript | {
"resource": ""
} |
q42857 | replaceBetween | train | function replaceBetween(args) {
const getSourceContent = args.source ? fs.readFile(path.normalize(args.source), { encoding: 'utf8' }) : getStdin();
const getTargetContent = fs.readFile(path.normalize(args.target), { encoding: 'utf8' });
const commentBegin = args.comment ? commentTypes[args.comment].begin : args.begin;
const commentEnd = args.comment ? commentTypes[args.comment].end : args.end;
const beginTokenPattern = `(${commentBegin}\\s*?${args.token} BEGIN\\s*?${commentEnd}.*?[\\r\\n]+)`;
const endTokenPattern = `(${commentBegin}\\s*?${args.token} END\\s*?${commentEnd})`;
const contentPattern = '[\\s\\S]*?';
const RX = new RegExp(`${beginTokenPattern}${contentPattern}${endTokenPattern}`, 'm');
return Promise.all([getSourceContent, getTargetContent])
.then(([sourceContent, targetContent]) => {
if (!sourceContent) {
throw new Error('Source content is empty.');
}
if (!targetContent.match(RX)) {
const error = `Target file content does not have necessary tokens ${chalk.yellow(`${commentBegin} ${args.token} BEGIN ${commentEnd}`)} `
+ `and ${chalk.yellow(`${commentBegin} ${args.token} END ${commentEnd}`)}.`;
throw new Error(error);
}
return targetContent.replace(RX, `$1${sourceContent}$2`);
})
.then(newContent => fs.outputFile(path.normalize(args.target), newContent));
} | javascript | {
"resource": ""
} |
q42858 | GitHubContentAPI | train | function GitHubContentAPI(opts) {
if (!(this instanceof GitHubContentAPI)) return new GitHubContentAPI(opts);
opts = Object.create(opts || {});
if (!opts.auth && GITHUB_USERNAME && GITHUB_PASSWORD) opts.auth = GITHUB_USERNAME + ':' + GITHUB_PASSWORD;
this._host = opts.host || 'https://api.github.com';
GitHub.call(this, opts);
Remote.call(this, opts);
this._gh_request = this.request;
delete this.request;
main = this;
} | javascript | {
"resource": ""
} |
q42859 | errorRateLimitExceeded | train | function errorRateLimitExceeded(res) {
var err = new Error('GitHub rate limit exceeded.');
err.res = res;
err.remote = 'github-content-api';
throw err;
} | javascript | {
"resource": ""
} |
q42860 | checkRateLimitRemaining | train | function checkRateLimitRemaining(res) {
var remaining = parseInt(res.headers['x-ratelimit-remaining'], 10);
if (remaining <= 50) {
console.warn('github-content-api remote: only %d requests remaining.', remaining);
}
} | javascript | {
"resource": ""
} |
q42861 | errorBadCredentials | train | function errorBadCredentials(res) {
var err = new Error('Invalid credentials');
err.res = res;
err.remote = 'github-content-api';
throw err;
} | javascript | {
"resource": ""
} |
q42862 | train | function(what) {
var mainData = what;
var localData = {};
if (typeof what == 'string') {
// main
var mainFile = path.resolve(process.cwd(), what);
delete require.cache[mainFile];
mainData = require(mainFile);
// local
var localFile = mainFile.substr(0, mainFile.lastIndexOf('.'))+'.local'+path.extname(mainFile);
if (fs.existsSync(localFile)) {
delete require.cache[localFile];
localData = require(localFile);
}
}
// main and local merged
return _.merge({},
_.merge({}, mainData.default, mainData[this.env]),
_.merge({}, localData.default, localData[this.env])
);
} | javascript | {
"resource": ""
} | |
q42863 | addProperty | train | function addProperty(prop, func){
Object.defineProperty(String.prototype, prop, {
enumerable: true,
configurable: false,
get: func
});
} | javascript | {
"resource": ""
} |
q42864 | train | function() {
return function (req, res, next) {
if (!req.locals) {
req.locals = {};
}
var requestTemplates = getTemplates(res);
req.locals.templates = requestTemplates;
req.locals.knownTemplates = knownTemplates;
if (!res.locals) {
res.locals = {};
}
res.locals.templates = requestTemplates;
res.locals.knownTemplates = knownTemplates;
res.locals.renderTemplate = invokeRenderTemplate.bind(null, res.locals);
return next();
};
} | javascript | {
"resource": ""
} | |
q42865 | loadIntoLibrary | train | function loadIntoLibrary(schemas) {
assert(_.isObject(schemas));
_.extend(library, schemas);
} | javascript | {
"resource": ""
} |
q42866 | train | function(site_path, arg, cmd, done) {
var start = Date.now();
var nell_site = {
site_path: site_path
};
async.series([
function(callback) {
nell_site.config_path = path.join(site_path, 'nell.json');
fs.exists(nell_site.config_path, function(exists) {
if (!exists) {
return callback(new Error(__('Unable to load nell.json config file')));
}
callback();
});
},
function(callback) {
nell_site.config = require(nell_site.config_path);
nell_site.output_path = (nell_site.config.output && nell_site.config.output.path) ? path.join(nell_site.site_path, nell_site.config.output.path) : path.join(nell_site.site_path, 'output');
async.forEach(Object.keys(nell_site.config), function(key, key_done) {
nell_site[key] = nell_site.config[key] || {};
key_done();
}, callback);
},
function(callback) {
loadSwig(nell_site, callback);
},
function(callback) {
loadItems(nell_site, 'post', callback);
},
function(callback) {
loadItems(nell_site, 'page', callback);
},
function(callback) {
if (nell_site.config.output && nell_site.config.output.delete) {
fs.unlink(nell_site.output_path, callback);
} else {
callback();
}
},
function(callback) {
outputItems(nell_site, 'post', callback);
},
function(callback) {
outputItems(nell_site, 'page', callback);
},
function(callback) {
outputIndex(nell_site, callback);
},
function(callback) {
moveStatic(nell_site, callback);
}
], function(err) {
var end = Date.now();
if (err) {
return done(err);
}
done(null, __('Site "%s" generated in %ds', nell_site.site.title, (end - start) / 1000));
});
} | javascript | {
"resource": ""
} | |
q42867 | train | function(value) {
var DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
var _rem = Long.fromNumber(0);
var i = 0;
if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
return { quotient: value, rem: _rem };
}
for (i = 0; i <= 3; i++) {
// Adjust remainder to match value of next dividend
_rem = _rem.shiftLeft(32);
// Add the divided to _rem
_rem = _rem.add(new Long(value.parts[i], 0));
value.parts[i] = _rem.div(DIVISOR).low_;
_rem = _rem.modulo(DIVISOR);
}
return { quotient: value, rem: _rem };
} | javascript | {
"resource": ""
} | |
q42868 | train | function(left, right) {
if (!left && !right) {
return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
}
var leftHigh = left.shiftRightUnsigned(32);
var leftLow = new Long(left.getLowBits(), 0);
var rightHigh = right.shiftRightUnsigned(32);
var rightLow = new Long(right.getLowBits(), 0);
var productHigh = leftHigh.multiply(rightHigh);
var productMid = leftHigh.multiply(rightLow);
var productMid2 = leftLow.multiply(rightHigh);
var productLow = leftLow.multiply(rightLow);
productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
productMid = new Long(productMid.getLowBits(), 0)
.add(productMid2)
.add(productLow.shiftRightUnsigned(32));
productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
// Return the 128 bit result
return { high: productHigh, low: productLow };
} | javascript | {
"resource": ""
} | |
q42869 | addStatics | train | function addStatics(statics, Subclass) {
// static method inheritance (including `extend`)
Object.keys(statics).forEach(function(key) {
var descriptor = Object.getOwnPropertyDescriptor(statics, key);
if (!descriptor.configurable) return;
Object.defineProperty(Subclass, key, descriptor);
});
} | javascript | {
"resource": ""
} |
q42870 | getTree | train | function getTree(root, deps) {
var tree;
tree = {};
populateItem(tree, root, deps);
return tree;
} | javascript | {
"resource": ""
} |
q42871 | train | function(options) {
var stream = through.obj(function(file, enc, cb) {
var out = options.out;
// Convert to the main file to a vinyl file
options.out = function(text) {
cb(null, new gutil.File({
path: out,
contents: new Buffer(text)
}));
};
// Optimize the main file
requirejs.optimize(options, null, function(err) {
stream.emit('error', new gutil.PluginError('gulp-rjs', err.message));
});
});
return stream;
} | javascript | {
"resource": ""
} | |
q42872 | log | train | function log(data) {
if (type.isError(data)) {
if (!data.handled) {
_setHandled(data);
_console.error(data);
}
}
else {
_console.log(_transform(data));
}
return data;
} | javascript | {
"resource": ""
} |
q42873 | train | function () {
// don't do it twice
if (!tcpConnections[msg.tcpId]) return;
exports.verbose(new Date(), 'Connection closed by remote peer for: ' + addressForLog(msg.address, msg.port));
newCon.removeAllListeners();
delete tcpConnections[msg.tcpId];
send(channel, new MSG.Close(msg.tcpId));
} | javascript | {
"resource": ""
} | |
q42874 | train | function (error) {
send(channel, new MSG.OpenResult(msg.tcpId, Protocol.toOpenResultStatus(error), null, null));
} | javascript | {
"resource": ""
} | |
q42875 | loadData | train | function loadData(dataUrl, jsonEditor) {
// jQuery getJSON will read the file from a Web resources.
$.getJSON(dataUrl, function(data) {
//$.getJSON('data/simple-zoomable-circle.json', function(data) {
// set data to JSON editor.
jsonEditor.set(data);
// update the JSON source code
$('#jsonstring').html(JSON.stringify(data, null, 2));
// remove the existing one.
$('#svgpreview').empty();
// build the circles...
var options = {
"margin":10,
"diameter":500
};
$("#svgpreview").zoomableCircles(options, data);
//console.log(JSON.stringify(data));
});
} | javascript | {
"resource": ""
} |
q42876 | getVersion | train | function getVersion (plugin) {
return new Promise(function (resolve, reject) {
npm.commands.view([plugin, 'version'], function (err, data) {
if (err) return reject(err)
resolve(Object.keys(data)[0])
})
})
} | javascript | {
"resource": ""
} |
q42877 | defineActionProp | train | function defineActionProp(type) {
ActionsHub[type] = function() {
var creators = _actions[type];
if (creators.length === 1) {
// Simply forward to original action creator
return creators[0].apply(null, arguments);
} else if (creators.length > 1) {
// ThunkAction
var args = arguments;
return function(dispatch) {
// dispatch all action creator
for (var i = 0, cLength = creators.length; i < cLength; i++) {
dispatch(creators[i].apply(null, args));
}
};
}
}
} | javascript | {
"resource": ""
} |
q42878 | wrapFunctions | train | function wrapFunctions(name, obj, protoLevel, hooks, state, rules){
if (!(obj && (util.isObject(obj) || util.isFunction(obj)))){
return;
}
if (obj.__concurix_blacklisted || (obj.constructor && obj.constructor.__concurix_blacklisted)) {
return;
}
if (obj.__concurix_wrapped_obj__ || !Object.isExtensible(obj)){
return;
}
tagObject(obj, '__concurix_wrapped_obj__');
protoLevel = protoLevel ? protoLevel : 0;
util.iterateOwnProperties(obj, function(key){
var desc = Object.getOwnPropertyDescriptor(obj, key);
// We got a property that wasn't a property.
if (desc == null) {
return;
}
// ignore properties that cannot be set
if (!desc.configurable || !desc.writable || desc.set){
return;
}
// ignore blacklisted properties
if (desc.value && desc.value.__concurix_blacklisted) {
return;
}
// if we are supposed to skip a function, blacklist it so we don't wrap it.
if( !rules.wrapKey(key) ){
blacklist(obj[key]);
return;
}
if ( util.isFunction(desc.value) && !wrap.isWrapper(obj[key]) && rules.wrapKey(key) ) {
//console.log('wrapping ', key, ' for ', name, state.modInfo.top);
obj[key] = wrap(obj[key])
.before(hooks.beforeHook)
.after(hooks.afterHook)
.module(name)
.state(state)
.nameIfNeeded(key)
.getProxy();
} else if (util.isObject(desc.value) && !wrap.isWrapper(obj[key]) && rules.wrapKey(key)) {
// to save cycles do not go up through the prototype chain for object-type properties
wrapFunctions(name, desc.value, 0, hooks, state, rules);
}
});
// protoLevel is how deep you want to traverse the prototype chain.
// protoLevel = -1 - this will go all the way up excluding Object.prototype
if (protoLevel != 0){
protoLevel--;
var proto = Object.getPrototypeOf(obj);
wrapFunctions(name, proto, protoLevel, hooks, state, rules);
}
} | javascript | {
"resource": ""
} |
q42879 | wrapArguments | train | function wrapArguments(trace, clientState, hooks) {
//wrap any callbacks found in the arguments
var args = trace.args;
var handler = clientState.rules.handleArgs(trace.funInfo.name);
if (handler) {
handler(trace, clientState);
}
for (var i = args.length - 1; i >= 0; i--) {
var a = args[i];
if (util.isFunction(a) && !a.__concurix_blacklisted) {
var callbackState = {
modInfo: clientState.modInfo,
rules: clientState.rules,
callbackOf: trace
};
if (wrap.isWrapper(args[i])) {
args[i].__concurix_proxy_state__
.module((trace.calledBy && trace.calledBy.moduleName) || 'root')
.state(callbackState)
.nameIfNeeded(trace.funInfo.name + ' callback')
.getProxy();
}
else {
args[i] = wrap(a)
.before(hooks.beforeHook)
.after(hooks.afterHook)
.module((trace.calledBy && trace.calledBy.moduleName) || 'root')
.state(callbackState)
.nameIfNeeded(trace.funInfo.name + ' callback')
.getProxy();
}
trace.origFunctionArguments = trace.origFunctionArguments || [];
trace.origFunctionArguments.push(a);
}
}
} | javascript | {
"resource": ""
} |
q42880 | next | train | function next() {
var limireq = this;
var conn = limireq.connections.shift()
if (!conn) return
request(conn.options, function(err, res, body) {
if (typeof conn.callback === 'function')
conn.callback(err, res, body)
else
limireq.emit('data', err, res, body)
// Signal the end of processing
if (++limireq.completed === limireq.total) {
limireq.active = false
limireq.emit('end')
} else next.call(limireq)
})
} | javascript | {
"resource": ""
} |
q42881 | configureESFormatter | train | function configureESFormatter(options) {
const ESFormatConfig = {
root: true,
allowShebang: true,
indent: {value: '\t'},
whiteSpace: {
before: {
IfStatementConditionalOpening: -1
},
after: {
IfStatementConditionalClosing: -1,
FunctionReservedWord: 1
}
},
lineBreak: {after: {ClassDeclarationClosingBrace: 0}}
}
if (options.space > 0) {
ESFormatConfig.indent.value = ' '.repeat(parseInt(options.space, 10))
}
console.debug(stripIndent`
${clr.title}esFormatter Options${clr.title.out}:
`)
if (console.canWrite(5)) {
console.pretty(ESFormatConfig, 2)
}
return () => esFormatter.rc(ESFormatConfig)
} | javascript | {
"resource": ""
} |
q42882 | configureESLint | train | function configureESLint(options) {
const ESLintConfig = {
rules: options.rules
}
ESLintConfig.extends = 'xo'
if (options.esnext) {
ESLintConfig.extends = 'xo/esnext'
}
if (!options.semicolon) {
ESLintConfig.rules.semi = [2, 'never']
}
if (options.space === false) {
ESLintConfig.rules.indent = [
2, 'tab', {
SwitchCase: 1
}
]
} else {
ESLintConfig.rules.indent = [
2, parseInt(options.space, 10), {
SwitchCase: 0
}
]
}
ESLintConfig.rules['valid-jsdoc'] = [0]
ESLintConfig.rules['require-jsdoc'] = [0]
console.debug(stripIndent`
${clr.title}ESlint Options${clr.title.out}:
`)
if (console.canWrite(5)) {
console.pretty(ESLintConfig, 2)
}
return () => new ESLint({
baseConfig: ESLintConfig,
fix: true,
rules: options.rules
})
} | javascript | {
"resource": ""
} |
q42883 | train | function(next) {
async.map([src,dest], function(path, done) {
fs.stat(path, function(err, stat) {
done(null, stat); // Ignore error
});
},
function(err, results) {
statSrc = results[0];
statDest = results[1];
if(!statSrc) {
// src is needed
next(new Error('File not found: ' + src));
}
// Ignore anything that is not directory or file
if(!(statSrc.isFile() || statSrc.isDirectory())) {
grunt.verbose.writeln(' Ignore:'+' Source is not a file or a directory.'.grey);
return done(null, false);
}
// Add stat to options for user defined transform & process
options.statSrc = statSrc;
options.statDest = statDest;
next();
});
} | javascript | {
"resource": ""
} | |
q42884 | train | function(next) {
if(!statDest || !lazy || readOnly) {
return next();
}
if(statDest.mtime.getTime() >= statSrc.mtime.getTime()) {
tally.useCached++;
grunt.verbose.writeln(' Ignore %s:'+' Destination file is allready transformed (See options.lazy).'.grey, src.blue);
// Leave proceed
return done(null, false);
} else {
next();
}
} | javascript | {
"resource": ""
} | |
q42885 | addToQueueConcat | train | function addToQueueConcat(sources, dest, options) {
queueConcat.push({
src: sources,
dest: dest,
options: _.extend({}, defaultOptions, options || {})
});
} | javascript | {
"resource": ""
} |
q42886 | train | function(next) {
Q.all(sources.map(function(src) {
return Q.nfcall(fs.stat, src)
.then(function(stat) {
statSources[src] = stat;
});
}))
.then(function() { next(); })
.fail(function(err) {next(err);});
} | javascript | {
"resource": ""
} | |
q42887 | train | function(next) {
// Here destination is allways a file.
// Only the parent folder is required
var dir = dirname(dest);
if(dirExists[dir]) {
return next();
}
grunt.verbose.writeln(' Make directory %s', dir.blue);
mkdirp(dir, function(err) {
if(err) {
return next(err);
}
tally.dirs++;
dirExists[dir] = true;
return next();
});
} | javascript | {
"resource": ""
} | |
q42888 | train | function(clock) {
clock = clock || new LocalClock();
this.gameTime = 0;
this.callCount = 0;
var then = clock.getTime();
/**
* Gets the time elapsed in seconds since the last time this was
* called
* @return {number} The time elapsed in seconds since this was
* last called. Note will never return a time more than
* 1/20th of second. This is to help prevent giant time
* range that might overflow the math on a game.
*
*/
this.getElapsedTime = function() {
++this.callCount;
var now = clock.getTime();
var elapsedTime = Math.min(now - then, 0.05); // Don't return a time less than 0.05 second
this.gameTime += elapsedTime;
then = now;
return elapsedTime;
}.bind(this);
} | javascript | {
"resource": ""
} | |
q42889 | FNStack | train | function FNStack() {
var stack = slice.call(arguments, 0).filter(function iterator(val) {
return typeof val === "function";
});
this._context = null;
this.stack = stack;
return this;
} | javascript | {
"resource": ""
} |
q42890 | train | function(matchedWord, imgUrl) {
if (!imgUrl || !matchedWord) {
return;
}
var flag = imgUrl.indexOf(options.tag) != -1; // urls like "img/bg.png?__inline" will be transformed to base64
//grunt.log.write('urlMatcher :: matchedWord=' + matchedWord + ',imgUrl=' + imgUrl + '\n$$$\n');
if((isBase64Path(imgUrl)) || isRemotePath(imgUrl)) {
return matchedWord;
}
var absoluteImgUrl = path.resolve(path.dirname(filepath), imgUrl); // img url relative to project root
var newUrl = path.relative(path.dirname(htmlFilepath), absoluteImgUrl); // img url relative to the html file
absoluteImgUrl = absoluteImgUrl.replace(/\?.*$/, '');
if(flag && grunt.file.exists(absoluteImgUrl)) {
newUrl = new datauri(absoluteImgUrl);
} else {
newUrl = newUrl.replace(/\\/g, '/');
}
return matchedWord.replace(imgUrl, newUrl);
} | javascript | {
"resource": ""
} | |
q42891 | train | function( includeChildren, cloneId ) {
var $clone = this.$.cloneNode( includeChildren );
var removeIds = function( node ) {
// Reset data-cke-expando only when has been cloned (IE and only for some types of objects).
if ( node[ 'data-cke-expando' ] )
node[ 'data-cke-expando' ] = false;
if ( node.nodeType != CKEDITOR.NODE_ELEMENT )
return;
if ( !cloneId )
node.removeAttribute( 'id', false );
if ( includeChildren ) {
var childs = node.childNodes;
for ( var i = 0; i < childs.length; i++ )
removeIds( childs[ i ] );
}
};
// The "id" attribute should never be cloned to avoid duplication.
removeIds( $clone );
return new CKEDITOR.dom.node( $clone );
} | javascript | {
"resource": ""
} | |
q42892 | train | function( normalized ) {
var address = [];
var $documentElement = this.getDocument().$.documentElement;
var node = this.$;
while ( node && node != $documentElement ) {
var parentNode = node.parentNode;
if ( parentNode ) {
// Get the node index. For performance, call getIndex
// directly, instead of creating a new node object.
address.unshift( this.getIndex.call( { $: node }, normalized ) );
}
node = parentNode;
}
return address;
} | javascript | {
"resource": ""
} | |
q42893 | train | function( normalized ) {
// Attention: getAddress depends on this.$
// getIndex is called on a plain object: { $ : node }
var current = this.$,
index = -1,
isNormalizing;
if ( !this.$.parentNode )
return index;
do {
// Bypass blank node and adjacent text nodes.
if ( normalized && current != this.$ && current.nodeType == CKEDITOR.NODE_TEXT && ( isNormalizing || !current.nodeValue ) )
continue;
index++;
isNormalizing = current.nodeType == CKEDITOR.NODE_TEXT;
}
while ( ( current = current.previousSibling ) );
return index;
} | javascript | {
"resource": ""
} | |
q42894 | train | function( closerFirst ) {
var node = this;
var parents = [];
do {
parents[ closerFirst ? 'push' : 'unshift' ]( node );
}
while ( ( node = node.getParent() ) );
return parents;
} | javascript | {
"resource": ""
} | |
q42895 | train | function( query, includeSelf ) {
var $ = this.$,
evaluator,
isCustomEvaluator;
if ( !includeSelf ) {
$ = $.parentNode;
}
// Custom checker provided in an argument.
if ( typeof query == 'function' ) {
isCustomEvaluator = true;
evaluator = query;
} else {
// Predefined tag name checker.
isCustomEvaluator = false;
evaluator = function( $ ) {
var name = ( typeof $.nodeName == 'string' ? $.nodeName.toLowerCase() : '' );
return ( typeof query == 'string' ? name == query : name in query );
};
}
while ( $ ) {
// For user provided checker we use CKEDITOR.dom.node.
if ( evaluator( isCustomEvaluator ? new CKEDITOR.dom.node( $ ) : $ ) ) {
return new CKEDITOR.dom.node( $ );
}
try {
$ = $.parentNode;
} catch ( e ) {
$ = null;
}
}
return null;
} | javascript | {
"resource": ""
} | |
q42896 | TypedFunction | train | function TypedFunction (config) {
const fn = this;
if (config.hasOwnProperty('minArguments') && (!util.isInteger(config.minArguments) || config.minArguments < 0)) {
const message = util.propertyErrorMessage('minArguments', config.minArguments, 'Expected a non-negative integer.');
throw Error(message);
}
const min = config.hasOwnProperty('minArguments') ? config.minArguments : 0;
if (config.hasOwnProperty('maxArguments') && (!util.isInteger(config.maxArguments) || config.maxArguments < min)) {
const message = util.propertyErrorMessage('minArguments', config.maxArguments, 'Expected a integer greater than minArgument value of ' + min + '.');
throw Error(message);
}
// define properties
Object.defineProperties(fn, {
maxArguments: {
/**
* @property
* @name TypedString#maxArguments
* @type {number}
*/
value: config.maxArguments,
writable: false
},
minArguments: {
/**
* @property
* @name TypedString#minArguments
* @type {number}
*/
value: min,
writable: false
},
named: {
/**
* @property
* @name TypedString#strict
* @type {boolean}
*/
value: config.hasOwnProperty('named') ? !!config.named : false,
writable: false
}
});
return fn;
} | javascript | {
"resource": ""
} |
q42897 | train | function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
hashomatic._gap = '';
hashomatic._indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
hashomatic._indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
}
else if (typeof space === 'string') {
hashomatic._indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
hashomatic._rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return hashomatic._str('', {'': value});
} | javascript | {
"resource": ""
} | |
q42898 | train | function () {
if (packageInfo) return packageInfo;
var fs = require('fs');
packageInfo = JSON.parse(fs.readFileSync(__dirname + '/../package.json', 'utf8'));
return packageInfo;
} | javascript | {
"resource": ""
} | |
q42899 | train | function (is_ignore_errors, opt_config_filename) {
var self = this;
var config_paths = [];
if (opt_config_filename) {
config_paths.push(opt_config_filename);
} else {
// root of dependence source directory
config_paths.push('./config.json');
// root of denhub-device directory
config_paths.push(__dirname + '/../config.json');
}
var config_file = null;
for (var i = 0, l = config_paths.length; i < l; i++) {
try {
config_file = require('fs').readFileSync(config_paths[i]);
} catch (e) {
continue;
}
if (config_file) break;
}
if (!config_file && !is_ignore_errors) {
console.log(colors.bold.red('Error: Could not read the configuration file.'));
console.log(config_paths.join('\n'));
console.log(colors.bold('If you never created it, please try the following command:'));
console.log('$ denhub-device-generator init\n');
process.exit(255);
}
var config = {};
if (config_file) {
try {
config = JSON.parse(config_file.toString());
} catch (e) {
if (!is_ignore_errors) throw e;
}
}
config.commands = self._getLocalCommands(is_ignore_errors) || null;
return config;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.