_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q3800
|
openExplorerinLinux
|
train
|
function openExplorerinLinux(path, callback) {
path = path || '/';
let p = spawn('xdg-open', [path]);
p.on('error', (err) => {
p.kill();
return callback(err);
});
}
|
javascript
|
{
"resource": ""
}
|
q3801
|
openExplorer
|
train
|
function openExplorer(path, callback) {
if (osType == 'Windows_NT') {
openExplorerinWindows(path, callback);
}
else if (osType == 'Darwin') {
openExplorerinMac(path, callback);
}
else {
openExplorerinLinux(path, callback);
}
}
|
javascript
|
{
"resource": ""
}
|
q3802
|
openExplorerinMac
|
train
|
function openExplorerinMac(path, callback) {
path = path || '/';
let p = spawn('open', [path]);
p.on('error', (err) => {
p.kill();
return callback(err);
});
}
|
javascript
|
{
"resource": ""
}
|
q3803
|
openExplorerinWindows
|
train
|
function openExplorerinWindows(path, callback) {
path = path || '=';
let p = spawn('explorer', [path]);
p.on('error', (err) => {
p.kill();
return callback(err);
});
}
|
javascript
|
{
"resource": ""
}
|
q3804
|
train
|
function(p1, p2) {
var r = {
c: 90,
A: Math.abs(p2.x - p1.x),
B: Math.abs(p2.y - p1.y)
};
var brad = Math.atan2(r.B, r.A);
r.b = this.toDegrees(brad);
// r.C = Math.sqrt(Math.pow(r.B, 2) + Math.pow(r.A, 2));
r.C = r.B / Math.sin(brad);
r.a = 90 - r.b;
return r;
}
|
javascript
|
{
"resource": ""
}
|
|
q3805
|
train
|
function(r) {
r = Object.assign(r, {
C: 90
});
r.A = r.A || 90 - r.B;
r.B = r.B || 90 - r.A;
var arad = toRadians(r.A);
// sinA = a/c
// a = c * sinA
// tanA = a/b
// a = b * tanA
r.a = r.a || (r.c ? r.c * Math.sin(arad) : r.b * Math.tan(arad));
// sinA = a/c
r.c = r.c || r.a / Math.sin(arad);
// tanA = a/b
r.b = r.b || r.a / Math.tan(arad);
return r;
}
|
javascript
|
{
"resource": ""
}
|
|
q3806
|
train
|
function(object) {
return Array.isArray(object) ? object : [object.x, object.y, object.z];
}
|
javascript
|
{
"resource": ""
}
|
|
q3807
|
train
|
function(desired, nozzel = NOZZEL_SIZE, nozzie = 0) {
return (Math.floor(desired / nozzel) + nozzie) * nozzel;
}
|
javascript
|
{
"resource": ""
}
|
|
q3808
|
train
|
function(desired, nozzel = NOZZEL_SIZE, nozzie = 0) {
return (Math.ceil(desired / nozzel) + nozzie) * nozzel;
}
|
javascript
|
{
"resource": ""
}
|
|
q3809
|
train
|
function(msg, o) {
echo(
msg,
JSON.stringify(o.getBounds()),
JSON.stringify(this.size(o.getBounds()))
);
}
|
javascript
|
{
"resource": ""
}
|
|
q3810
|
train
|
function(object, segments, axis) {
var size = object.size()[axis];
var width = size / segments;
var result = [];
for (var i = width; i < size; i += width) {
result.push(i);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q3811
|
size
|
train
|
function size(o) {
var bbox = o.getBounds ? o.getBounds() : o;
var foo = bbox[1].minus(bbox[0]);
return foo;
}
|
javascript
|
{
"resource": ""
}
|
q3812
|
fit
|
train
|
function fit(object, x, y, z, keep_aspect_ratio) {
var a;
if (Array.isArray(x)) {
a = x;
keep_aspect_ratio = y;
x = a[0];
y = a[1];
z = a[2];
} else {
a = [x, y, z];
}
// var c = util.centroid(object);
var size = this.size(object.getBounds());
function scale(size, value) {
if (value == 0) return 1;
return value / size;
}
var s = [scale(size.x, x), scale(size.y, y), scale(size.z, z)];
var min = util.array.min(s);
return util.centerWith(
object.scale(
s.map(function(d, i) {
if (a[i] === 0) return 1; // don't scale when value is zero
return keep_aspect_ratio ? min : d;
})
),
"xyz",
object
);
}
|
javascript
|
{
"resource": ""
}
|
q3813
|
flush
|
train
|
function flush(moveobj, withobj, axis, mside, wside) {
return moveobj.translate(
util.calcFlush(moveobj, withobj, axis, mside, wside)
);
}
|
javascript
|
{
"resource": ""
}
|
q3814
|
getDelta
|
train
|
function getDelta(size, bounds, axis, offset, nonzero) {
if (!util.isEmpty(offset) && nonzero) {
if (Math.abs(offset) < 1e-4) {
offset = 1e-4 * (util.isNegative(offset) ? -1 : 1);
}
}
// if the offset is negative, then it's an offset from
// the positive side of the axis
var dist = util.isNegative(offset) ? (offset = size[axis] + offset) : offset;
return util.axisApply(axis, function(i, a) {
return bounds[0][a] + (util.isEmpty(dist) ? size[axis] / 2 : dist);
});
}
|
javascript
|
{
"resource": ""
}
|
q3815
|
bisect
|
train
|
function bisect(
object,
axis,
offset,
angle,
rotateaxis,
rotateoffset,
options
) {
options = util.defaults(options, {
addRotationCenter: false
});
angle = angle || 0;
var info = util.normalVector(axis);
var bounds = object.getBounds();
var size = util.size(object);
rotateaxis =
rotateaxis ||
{
x: "y",
y: "x",
z: "x"
}[axis];
// function getDelta(axis, offset) {
// // if the offset is negative, then it's an offset from
// // the positive side of the axis
// var dist = util.isNegative(offset) ? offset = size[axis] + offset : offset;
// return util.axisApply(axis, function (i, a) {
// return bounds[0][a] + (util.isEmpty(dist) ? size[axis] / 2 : dist);
// });
// }
var cutDelta = options.cutDelta || util.getDelta(size, bounds, axis, offset);
var rotateOffsetAxis = {
xy: "z",
yz: "x",
xz: "y"
}[[axis, rotateaxis].sort().join("")];
var centroid = object.centroid();
var rotateDelta = util.getDelta(size, bounds, rotateOffsetAxis, rotateoffset);
var rotationCenter =
options.rotationCenter ||
new CSG$1.Vector3D(
util.axisApply("xyz", function(i, a) {
if (a == axis) return cutDelta[i];
if (a == rotateOffsetAxis) return rotateDelta[i];
return centroid[a];
})
);
var rotationAxis = util.rotationAxes[rotateaxis];
var cutplane = CSG$1.OrthoNormalBasis.GetCartesian(
info.orthoNormalCartesian[0],
info.orthoNormalCartesian[1]
)
.translate(cutDelta)
.rotate(rotationCenter, rotationAxis, angle);
var g = util.group("negative,positive", [
object.cutByPlane(cutplane.plane).color("red"),
object.cutByPlane(cutplane.plane.flipped()).color("blue")
]);
if (options.addRotationCenter)
g.add(
util.unitAxis(size.length() + 10, 0.5, rotationCenter),
"rotationCenter"
);
return g;
}
|
javascript
|
{
"resource": ""
}
|
q3816
|
stretch
|
train
|
function stretch(object, axis, distance, offset) {
var normal = {
x: [1, 0, 0],
y: [0, 1, 0],
z: [0, 0, 1]
};
var bounds = object.getBounds();
var size = util.size(object);
var cutDelta = util.getDelta(size, bounds, axis, offset, true);
// console.log('stretch.cutDelta', cutDelta, normal[axis]);
return object.stretchAtPlane(normal[axis], cutDelta, distance);
}
|
javascript
|
{
"resource": ""
}
|
q3817
|
poly2solid
|
train
|
function poly2solid(top, bottom, height) {
if (top.sides.length == 0) {
// empty!
return new CSG$1();
}
// var offsetVector = CSG.parseOptionAs3DVector(options, "offset", [0, 0, 10]);
var offsetVector = CSG$1.Vector3D.Create(0, 0, height);
var normalVector = CSG$1.Vector3D.Create(0, 1, 0);
var polygons = [];
// bottom and top
polygons = polygons.concat(
bottom._toPlanePolygons({
translation: [0, 0, 0],
normalVector: normalVector,
flipped: !(offsetVector.z < 0)
})
);
polygons = polygons.concat(
top._toPlanePolygons({
translation: offsetVector,
normalVector: normalVector,
flipped: offsetVector.z < 0
})
);
// walls
var c1 = new CSG$1.Connector(
offsetVector.times(0),
[0, 0, offsetVector.z],
normalVector
);
var c2 = new CSG$1.Connector(
offsetVector,
[0, 0, offsetVector.z],
normalVector
);
polygons = polygons.concat(
bottom._toWallPolygons({
cag: top,
toConnector1: c1,
toConnector2: c2
})
);
// }
return CSG$1.fromPolygons(polygons);
}
|
javascript
|
{
"resource": ""
}
|
q3818
|
Hexagon
|
train
|
function Hexagon(diameter, height) {
var radius = diameter / 2;
var sqrt3 = Math.sqrt(3) / 2;
var hex = CAG.fromPoints([
[radius, 0],
[radius / 2, radius * sqrt3],
[-radius / 2, radius * sqrt3],
[-radius, 0],
[-radius / 2, -radius * sqrt3],
[radius / 2, -radius * sqrt3]
]);
return hex.extrude({
offset: [0, 0, height]
});
}
|
javascript
|
{
"resource": ""
}
|
q3819
|
Tube
|
train
|
function Tube(
outsideDiameter,
insideDiameter,
height,
outsideOptions,
insideOptions
) {
return Parts.Cylinder(outsideDiameter, height, outsideOptions).subtract(
Parts.Cylinder(insideDiameter, height, insideOptions || outsideOptions)
);
}
|
javascript
|
{
"resource": ""
}
|
q3820
|
train
|
function(
headDiameter,
headLength,
diameter,
length,
clearLength,
options
) {
var head = Parts.Hexagon(headDiameter, headLength);
var thread = Parts.Cylinder(diameter, length);
if (clearLength) {
var headClearSpace = Parts.Hexagon(headDiameter, clearLength);
}
return Parts.Hardware.Screw(head, thread, headClearSpace, options);
}
|
javascript
|
{
"resource": ""
}
|
|
q3821
|
_formatErrorsWarnings
|
train
|
function _formatErrorsWarnings(level, list, projectRoot){
return list.map(x => {
let file, line, col, endLine, endCol, message
try{
// resolve the relative path
let fullFilePath = data_get(x, 'module.resource')
file = fullFilePath && projectRoot ? path.relative(projectRoot, fullFilePath) : ''
// file = file.replace(/[\\//]/g, '/')
line = data_get(x, 'error.error.loc.line') || 0
col = data_get(x, 'error.error.loc.column') || 0
// only need first line of message
let fullMessage = (x.message + '').trim()
let crPos = fullMessage.indexOf("\n")
if (crPos >= 0){
message = fullMessage.substring(0, crPos)
} else {
message = fullMessage
}
if (!line){
let linesColsInfo
let m
if (x.name === 'ModuleNotFoundError'
&& (m = fullMessage.match(MODULE_NOT_FOUND_ERR_MSG_PATTERN))){
linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1])
} else if (fullMessage.indexOf('component lists rendered with v-for should have explicit keys') > 0
&& (m = fullMessage.match(/([a-zA-Z-_]+)\s+(v-for=['"].*?['"])/))){
linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[2], {after: m[1]})
} else if (m = fullMessage.match(/export ['"](\S+?)['"] was not found/)){
linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1], {after: 'import'})
} else if (m = fullMessage.match(/Error compiling template:((?:.|[\r\n])*)- Component template/m)){
linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1].trim())
message = fullMessage.replace(/\n/g, ' ')
}
if (linesColsInfo){
line = linesColsInfo.line || 0
col = linesColsInfo.col || 0
endLine = linesColsInfo.endLine
endCol = linesColsInfo.endCol
}
}
let endLinesCols = (endLine || endCol) ? ('~' + (endLine || '') + (endLine ? ',' : '') + (endCol || '0')) : ''
return `!>${level}: ${file}:${line},${col}${endLinesCols}: ${message || '@see output window'}`
} catch (e){
console.warn(e)
return ''
}
}).join("\n")
}
|
javascript
|
{
"resource": ""
}
|
q3822
|
_resolveLineColNumInFile
|
train
|
function _resolveLineColNumInFile(file, message, options={}){
if (!message){
return {line: 0, col: 0}
}
let fileContent = fs.readFileSync(file, 'utf8')
let beyondPos = 0
switch (typeof options.after){
case 'string':
beyondPos = fileContent.indexOf(options.after)
break
case 'number':
beyondPos = options.after
break
default:
break
}
let pos = fileContent.indexOf(message, beyondPos >= 0 ? beyondPos : 0)
if (pos <= 0){
return {line: 0, col: 0}
}
let lineNum = 1
let linePos = 0
for (let i = 0; i < pos; i++){
if (fileContent.charCodeAt(i) === 10){ // 10: "\n"
lineNum++
linePos = i
}
}
return {line: lineNum, col: pos - linePos, endCol: pos - linePos + message.length}
}
|
javascript
|
{
"resource": ""
}
|
q3823
|
qpdecode
|
train
|
function qpdecode(callback) {
return function(data) {
var string = callback(data);
return string
.replace(/[\t\x20]$/gm, '')
.replace(/=(?:\r\n?|\n|$)/g, '')
.replace(/=([a-fA-F0-9]{2})/g, function($0, $1) {
var codePoint = parseInt($1, 16);
return String.fromCharCode(codePoint);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q3824
|
order
|
train
|
function order(type, name) {
if (type === '' || type === 'M') return name;
if (type === 'm') return type + name;
if (type === 'aug') return name + '#5';
if (type === 'm#5') return 'm' + name + '#5';
if (type === 'dim') return name === 'b7' ? 'dim7' : 'm' + name + 'b5';
if (type === 'Mb5') return name + 'b5';
else return name + type;
}
|
javascript
|
{
"resource": ""
}
|
q3825
|
indicesToItems
|
train
|
function indicesToItems(target, items, indices, r) {
for (var i = 0; i < r; i++)
target[i] = items[indices[i]];
}
|
javascript
|
{
"resource": ""
}
|
q3826
|
makeGlobal
|
train
|
function makeGlobal(pattern) {
var flags = 'g';
if (pattern.multiline) flags += 'm';
if (pattern.ignoreCase) flags += 'i';
if (pattern.sticky) flags += 'y';
if (pattern.unicode) flags += 'u';
return new RegExp(pattern.source, flags);
}
|
javascript
|
{
"resource": ""
}
|
q3827
|
forEach
|
train
|
function forEach(iterable, callback) {
var iterator, k, i, l, s;
if (!iterable)
throw new Error('obliterator/forEach: invalid iterable.');
if (typeof callback !== 'function')
throw new Error('obliterator/forEach: expecting a callback.');
// The target is an array or a string or function arguments
if (
Array.isArray(iterable) ||
(ARRAY_BUFFER_SUPPORT && ArrayBuffer.isView(iterable)) ||
typeof iterable === 'string' ||
iterable.toString() === '[object Arguments]'
) {
for (i = 0, l = iterable.length; i < l; i++)
callback(iterable[i], i);
return;
}
// The target has a #.forEach method
if (typeof iterable.forEach === 'function') {
iterable.forEach(callback);
return;
}
// The target is iterable
if (
SYMBOL_SUPPORT &&
Symbol.iterator in iterable &&
typeof iterable.next !== 'function'
) {
iterable = iterable[Symbol.iterator]();
}
// The target is an iterator
if (typeof iterable.next === 'function') {
iterator = iterable;
i = 0;
while ((s = iterator.next(), s.done !== true)) {
callback(s.value, i);
i++;
}
return;
}
// The target is a plain object
for (k in iterable) {
if (iterable.hasOwnProperty(k)) {
callback(iterable[k], k);
}
}
return;
}
|
javascript
|
{
"resource": ""
}
|
q3828
|
initTmpDir
|
train
|
function initTmpDir (dirname, cb) {
var dir = path.join(os.tmpDir(), dirname);
rmrf(dir, function (err) {
if (err) return cb(err);
mkdir(dir, function (err) {
if (err) return cb(err);
cb(null, dir);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q3829
|
p
|
train
|
function p() {
// global promise object to wait for all plot options to be completed before writing
this.promises = [];
// global array for options to plot
this.optArray = [];
// simple plot
this.plot = function(seriesArr, title, yLabel, xLabel) {
// console.log("plotting")
var defer = q.defer();
this.promises.push(defer.promise);
title = title || false;
yLabel = yLabel || false;
xLabel = xLabel || false;
var opt = _.cloneDeep(tmpOpt),
set = _.set.bind(null, opt);
set('series', seriesArr);
set('title.text', title);
set('yAxis.title.text', yLabel);
set('xAxis.title.text', xLabel);
// setTimeout(function() {}, 2000);
this.optArray.push(opt);
defer.resolve();
return opt;
};
// advance plot = specify your own highcharts options
this.advPlot = function(opt) {
var defer = q.defer();
this.promises.push(defer.promise);
this.optArray.push(opt);
defer.resolve();
return opt;
};
// write highchart options to json for rendering
// if autosave is true, charts will save on view
this.write = function(autosave) {
var defer = q.defer();
for (var i = 0; i < this.optArray.length; i++) {
_.set(this.optArray[i], 'chart.renderTo', 'hchart' + i);
_.set(this.optArray[i], 'autosave', autosave);
}
fs.writeFile(__dirname + '/src/options.json', JSON.stringify(this.optArray), defer.resolve);
return defer.promise;
};
// serialize optArray and write to
this.serialize = function(autosave) {
var defer = q.defer();
q.all(this.promises)
.then(this.write(autosave))
.then(defer.resolve());
return defer.promise;
};
// finally, render after all plots specified
// if autosave is true, charts will save on view
this.render = function(autosave) {
var gulpplot = require(__dirname + '/../gulpfile.js').gulpplot;
this.serialize(autosave)
.then(gulpplot)
};
this.dynrender = function() {
this.serialize()
// .then(dyngulpplot)
};
}
|
javascript
|
{
"resource": ""
}
|
q3830
|
localExport
|
train
|
function localExport(opt) {
var ind = _.reGet(/\d/)(opt.chart.renderTo);
_.assign(opt, {
'exporting': {
'buttons': {
'contextButton': {
'y': -10,
'menuItems': [{
'text': 'Save as PNG',
onclick: function() {
this.createCanvas(opt.title, 'png', ind);
},
'separator': false
}, {
'text': 'Save as JPEG',
onclick: function() {
this.createCanvas(opt.title, 'jpeg', ind);
},
'separator': false
}]
}
}
}
})
return opt;
}
|
javascript
|
{
"resource": ""
}
|
q3831
|
docme
|
train
|
function docme(readme, args, jsdocargs, cb) {
args = args || {};
jsdocargs = jsdocargs || [];
log.level = args.loglevel || 'info';
var projectRoot = args.projectRoot || process.cwd()
, projectName = path.basename(projectRoot)
resolveReadme(readme, function (err, fullPath) {
if (err) return cb(err);
log.info('docme', 'Updating API in "%s" with current jsdocs', readme);
update(projectRoot, projectName, jsdocargs, fullPath, cb);
});
}
|
javascript
|
{
"resource": ""
}
|
q3832
|
train
|
function(schema) {
if (!schema) {
throw new Error('Schema is empty');
}
this._defaultLimitTypes = [String,Boolean,Number,Date,Array,Object]
this.schema = schema;
}
|
javascript
|
{
"resource": ""
}
|
|
q3833
|
unrar
|
train
|
function unrar(arrayBuffer) {
RarEventMgr.emitStart();
var bstream = new BitStream(arrayBuffer, false /* rtl */ );
var header = new RarVolumeHeader(bstream);
if (header.crc == 0x6152 &&
header.headType == 0x72 &&
header.flags.value == 0x1A21 &&
header.headSize == 7) {
RarEventMgr.emitInfo("Found RAR signature");
var mhead = new RarVolumeHeader(bstream);
if (mhead.headType != RarUtils.VOLUME_TYPES.MAIN_HEAD) {
RarEventMgr.emitError("Error! RAR did not include a MAIN_HEAD header");
} else {
var localFiles = [],
localFile = null;
do {
try {
localFile = new RarLocalFile(bstream);
RarEventMgr.emitInfo("RAR localFile isValid=" + localFile.isValid + ", volume packSize=" + localFile.header.packSize);
if (localFile && localFile.isValid && localFile.header.packSize > 0) {
RarUtils.PROGRESS.totalUncompressedBytesInArchive += localFile.header.unpackedSize;
localFiles.push(localFile);
} else if (localFile.header.packSize == 0 && localFile.header.unpackedSize == 0) {
localFile.isValid = true;
}
} catch (err) {
break;
}
RarEventMgr.emitInfo("bstream" + bstream.bytePtr + "/" + bstream.bytes.length);
} while (localFile.isValid);
RarUtils.PROGRESS.totalFilesInArchive = localFiles.length;
// now we have all console.information but things are unpacked
// TODO: unpack
localFiles = localFiles.sort(function(a, b) {
var aname = a.filename;
var bname = b.filename;
return aname > bname ? 1 : -1;
});
RarEventMgr.emitInfo(localFiles.map(function(a) {
return a.filename
}).join(', '));
for (var i = 0; i < localFiles.length; ++i) {
var localfile = localFiles[i];
RarEventMgr.emitInfo("Local file: ", localfile.filename);
// update progress
RarUtils.PROGRESS.currentFilename = localfile.header.filename;
RarUtils.PROGRESS.currentBytesUnarchivedInFile = 0;
// actually do the unzipping
localfile.unrar();
if (localfile.isValid) {
// notify extract event with file
RarEventMgr.emitExtract(localfile);
RarEventMgr.emitProgress(RarUtils.PROGRESS);
}
}
RarEventMgr.emitProgress(RarUtils.PROGRESS);
}
} else {
RarEventMgr.emitError("Invalid RAR file");
}
RarEventMgr.emitFinish(localFiles);
return localFiles;
}
|
javascript
|
{
"resource": ""
}
|
q3834
|
BitStream
|
train
|
function BitStream(ab, rtl, opt_offset, opt_length) {
// if (!ab || !ab.toString || ab.toString() !== "[object ArrayBuffer]") {
// throw "Error! BitArray constructed with an invalid ArrayBuffer object";
// }
var offset = opt_offset || 0;
var length = opt_length || ab.byteLength;
this.bytes = new Uint8Array(ab, offset, length);
this.bytePtr = 0; // tracks which byte we are on
this.bitPtr = 0; // tracks which bit we are on (can have values 0 through 7)
this.peekBits = rtl ? this.peekBits_rtl : this.peekBits_ltr;
}
|
javascript
|
{
"resource": ""
}
|
q3835
|
mapRoutes
|
train
|
function mapRoutes(msg, done) {
var seneca = this
var adapter = msg.adapter || locals.adapter
var context = msg.context || locals.context
var options = msg.options || locals.options
var routes = Mapper(msg.routes)
var auth = msg.auth || locals.auth
// Call the adaptor with the mapped routes, context to apply them to
// and instance of seneca and the provided consumer callback.
adapter.call(seneca, options, context, auth, routes, done)
}
|
javascript
|
{
"resource": ""
}
|
q3836
|
setServer
|
train
|
function setServer(msg, done) {
var seneca = this
var context = msg.context || locals.context
var adapter = msg.adapter || locals.adapter
var options = msg.options || locals.options
var auth = msg.auth || locals.auth
var routes = msg.routes
// If the adapter is a string, we look up the
// adapters collection in opts.adapters.
if (!_.isFunction(adapter)) {
return done(new Error('Provide a function as adapter'))
}
// either replaced or the same. Regardless
// this sets what is called by mapRoutes.
locals = {
context: context,
adapter: adapter,
auth: auth,
options: options
}
// If we have routes in the msg map them and
// let the matter handle the callback
if (routes) {
mapRoutes.call(seneca, { routes: routes }, done)
} else {
// no routes to process, let the
// caller know everything went ok.
done(null, { ok: true })
}
}
|
javascript
|
{
"resource": ""
}
|
q3837
|
cmd
|
train
|
function cmd(handlers)
{
this.fieldindex = 0;
this.state = "start";
this.stmt = ""
this.params = []
// mixin all handlers
for (var h in handlers)
{
this[h] = handlers[h];
}
// save command name to display in debug output
this.command_name = cmd.caller.command_name;
this.args = Array.prototype.slice.call(cmd.caller.arguments);
}
|
javascript
|
{
"resource": ""
}
|
q3838
|
updateJXcoreExtensionImport
|
train
|
function updateJXcoreExtensionImport(context) {
var cordovaUtil =
context.requireCordovaModule('cordova-lib/src/cordova/util');
var ConfigParser = context.requireCordovaModule('cordova-lib').configparser;
var projectRoot = cordovaUtil.isCordova();
var xml = cordovaUtil.projectConfig(projectRoot);
var cfg = new ConfigParser(xml);
var Q = context.requireCordovaModule('q');
var deferred = new Q.defer();
var jxcoreExtensionPath = path.join(
context.opts.plugin.dir, 'src', 'ios', 'JXcoreExtension.m');
try {
console.log('Updating JXcoreExtension.m');
var oldContent = fs.readFileSync(jxcoreExtensionPath, 'utf8');
var newContent = oldContent.replace('%PROJECT_NAME%', cfg.name());
fs.writeFileSync(jxcoreExtensionPath, newContent, 'utf8');
deferred.resolve();
} catch (error) {
console.log('Failed updating of JXcoreExtension.m');
deferred.reject(error);
}
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
q3839
|
train
|
function (methodName, callback) {
Mobile(methodName).registerToNative(callback);
Mobile('didRegisterToNative').callNative(methodName, function () {
logger.debug('Method %s registered to native', methodName);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q3840
|
compareBufferArrays
|
train
|
function compareBufferArrays(buffArray1, buffArray2) {
assert(Array.isArray(buffArray1), 'We only accept arrays.');
assert(Array.isArray(buffArray2), 'We only accept arrays.');
if (buffArray1.length !== buffArray2.length) {
return false;
}
for (var i = 0; i < buffArray1.length; ++i) {
var buff1 = buffArray1[i];
assert(Buffer.isBuffer(buff1), 'Only buffers allowed in 1');
var buff2 = buffArray2[i];
assert(Buffer.isBuffer(buff2), 'Only buffers allowed in 2');
if (Buffer.compare(buff1, buff2) !== 0) {
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q3841
|
closeOldestServer
|
train
|
function closeOldestServer() {
var oldest = null;
Object.keys(self._peerServers).forEach(function (k) {
if (oldest == null) {
oldest = k;
}
else {
if (self._peerServers[k].lastActive <
self._peerServers[oldest].lastActive) {
oldest = k;
}
}
});
if (oldest) {
closeServer(self, self._peerServers[oldest], null, false);
}
}
|
javascript
|
{
"resource": ""
}
|
q3842
|
httpRequestPromise
|
train
|
function httpRequestPromise(method, urlObject) {
if (method !== 'GET' && method !== 'HEAD') {
return Promise.reject(new Error('We only support GET or HEAD requests'));
}
return new Promise(function (resolve, reject) {
var httpsRequestOptions = {
host: urlObject.host,
method: method,
path: urlObject.path
};
var req = https.request(httpsRequestOptions, function (res) {
if (res.statusCode !== 200) {
reject(new Error('Did not get 200 for ' + urlObject.href +
', instead got ' + res.statusCode));
return;
}
resolve(res);
})
.on('error', function (e) {
reject(new Error('Got error on ' + urlObject.href + ' - ' + e));
});
req.end();
});
}
|
javascript
|
{
"resource": ""
}
|
q3843
|
getReleaseConfig
|
train
|
function getReleaseConfig() {
var configFileName = path.join(__dirname, '..', 'package.json');
return fs.readFileAsync(configFileName, 'utf-8')
.then(function (data) {
var conf;
try {
conf = JSON.parse(data);
if (conf && conf.thaliInstall) {
return conf.thaliInstall;
}
return Promise.reject('Configuration error!');
}
catch (err) {
return Promise.reject(new Error(err));
}
});
}
|
javascript
|
{
"resource": ""
}
|
q3844
|
doGitHubEtagsMatch
|
train
|
function doGitHubEtagsMatch(projectName, depotName, branchName,
directoryToInstallIn) {
return getEtagFromEtagFile(depotName, branchName, directoryToInstallIn)
.then(function (etagFromFile) {
if (!etagFromFile) {
return false;
}
return httpRequestPromise('HEAD',
getGitHubZipUrlObject(projectName, depotName, branchName))
.then(function (res) {
var etagFromHeadRequest = returnEtagFromResponse(res);
return etagFromFile === etagFromHeadRequest;
});
});
}
|
javascript
|
{
"resource": ""
}
|
q3845
|
copyDevelopmentThaliCordovaPluginToProject
|
train
|
function copyDevelopmentThaliCordovaPluginToProject(appRootDirectory,
thaliDontCheckIn,
depotName,
branchName) {
var targetDirectory = createUnzippedDirectoryPath(depotName, branchName,
thaliDontCheckIn);
var sourceDirectory = path.join(
appRootDirectory, '..', 'Thali_CordovaPlugin');
return new Promise(function (resolve, reject) {
fs.remove(targetDirectory, function (err) {
if (err) {
reject(new Error('copyDevelopmentThaliCordovaPluginToProject remove ' +
'failed with ' + err));
return;
}
console.log('Copying files from ' + sourceDirectory + ' to ' +
targetDirectory);
fs.copy(sourceDirectory, targetDirectory, function (err) {
if (err) {
reject(
new Error('copyDevelopmentThaliCordovaPluginToProject failed with' +
err));
return;
}
resolve(createGitHubZipResponse(depotName, branchName, thaliDontCheckIn,
true));
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q3846
|
checkVersion
|
train
|
function checkVersion(objectName, versionNumber) {
const desiredVersion = versionNumber ? versionNumber : versions[objectName];
const commandAndResult = commandsAndResults[objectName];
if (!commandAndResult) {
return Promise.reject(
new Error('Unrecognized objectName in commandsAndResults'));
}
if (!desiredVersion) {
return Promise.reject(new Error('Unrecognized objectName in versions'));
}
if (commandAndResult.platform &&
!commandAndResult.platform.includes(os.platform()))
{
return Promise.reject(new Error('Requested object is not supported on ' +
'this platform'));
}
if (typeof commandAndResult.versionCheck === 'function') {
return promiseTry(commandAndResult.versionCheck)
.catch(() =>
Promise.reject(new Error('Version Check failed on ' + objectName)))
.then((versionCheckResult) =>
commandAndResult.versionValidate(versionCheckResult, desiredVersion))
.then(() => Promise.resolve(true))
.catch(() => Promise.reject(
new Error('Version not installed of ' + objectName)));
}
return execAndCheck(commandAndResult.versionCheck,
commandAndResult.checkStdErr,
desiredVersion,
commandAndResult.versionValidate);
}
|
javascript
|
{
"resource": ""
}
|
q3847
|
findFirstFile
|
train
|
function findFirstFile (name, rootDir) {
return new Promise(function (resolve, reject) {
var resultPath;
function end() {
if (resultPath) {
resolve(resultPath);
} else {
reject(new Error(
format('file is not found, name: \'%s\'', name)
));
}
}
var finder = findit(rootDir)
.on('file', function (path) {
// We can receive here 'path': 'a/b/my-file', 'a/b/bad-my-file',
// 'my-file', 'bad-my-file'.
// Both 'a/b/my-file' and 'my-file' should be valid.
if (path === name || endsWith(path, '/' + name)) {
resultPath = path;
finder.stop();
}
})
.on('error', function (error) {
reject(new Error(error));
})
.on('stop', end)
.on('end', end);
})
.catch(function (error) {
console.error(
'finder failed, error: \'%s\', stack: \'%s\'',
error.toString(), error.stack
);
return Promise.reject(error);
});
}
|
javascript
|
{
"resource": ""
}
|
q3848
|
ConnectionTable
|
train
|
function ConnectionTable(thaliReplicationManager) {
EventEmitter.call(this);
var self = this;
this.thaliReplicationManager = thaliReplicationManager;
this.connectionTable = {};
this.connectionSuccessListener = function (successObject) {
self.connectionTable[successObject.peerIdentifier] = {
muxPort: successObject.muxPort,
time: Date.now()
};
self.emit(successObject.peerIdentifier, self.connectionTable[successObject.peerIdentifier]);
};
thaliReplicationManager.on(ThaliReplicationManager.events.CONNECTION_SUCCESS, this.connectionSuccessListener);
}
|
javascript
|
{
"resource": ""
}
|
q3849
|
start
|
train
|
function start (router, pskIdToSecret, networkType) {
if (thaliMobileStates.started === true) {
return Promise.reject(new Error('Call Stop!'));
}
thaliMobileStates.started = true;
thaliMobileStates.networkType =
networkType || global.NETWORK_TYPE || thaliMobileStates.networkType;
return getWifiOrNativeMethodByNetworkType('start',
thaliMobileStates.networkType)(router, pskIdToSecret)
.then(function (result) {
if (result.wifiResult === null && result.nativeResult === null) {
return result;
}
return Promise.reject(result);
});
}
|
javascript
|
{
"resource": ""
}
|
q3850
|
train
|
function (appRoot) {
var filePath = path.join(appRoot,
'platforms/android/src/io/jxcore/node/JXcoreExtension.java');
var content = fs.readFileSync(filePath, 'utf-8');
content = content.replace('lifeCycleMonitor.start();',
'lifeCycleMonitor.start();\n\t\tRegisterExecuteUT.Register();');
content = content.replace('package io.jxcore.node;',
'package io.jxcore.node;\nimport com.test.thalitest.RegisterExecuteUT;');
fs.writeFileSync(filePath, content, 'utf-8');
}
|
javascript
|
{
"resource": ""
}
|
|
q3851
|
HKDF
|
train
|
function HKDF(hashAlg, salt, ikm) {
if (!(this instanceof HKDF)) { return new HKDF(hashAlg, salt, ikm); }
this.hashAlg = hashAlg;
// create the hash alg to see if it exists and get its length
var hash = crypto.createHash(this.hashAlg);
this.hashLength = hash.digest().length;
this.salt = salt || zeros(this.hashLength);
this.ikm = ikm;
// now we compute the PRK
var hmac = crypto.createHmac(this.hashAlg, this.salt);
hmac.update(this.ikm);
this.prk = hmac.digest();
}
|
javascript
|
{
"resource": ""
}
|
q3852
|
createPublicKeyHash
|
train
|
function createPublicKeyHash (ecdhPublicKey) {
return crypto.createHash(module.exports.SHA256)
.update(ecdhPublicKey)
.digest()
.slice(0, 16);
}
|
javascript
|
{
"resource": ""
}
|
q3853
|
generatePreambleAndBeacons
|
train
|
function generatePreambleAndBeacons (publicKeysToNotify,
ecdhForLocalDevice,
millisecondsUntilExpiration) {
if (publicKeysToNotify == null) {
throw new Error('publicKeysToNotify cannot be null');
}
if (ecdhForLocalDevice == null) {
throw new Error('ecdhForLocalDevice cannot be null');
}
if (millisecondsUntilExpiration <= 0 ||
millisecondsUntilExpiration > module.exports.ONE_DAY) {
throw new Error('millisecondsUntilExpiration must be > 0 & < ' +
module.exports.ONE_DAY);
}
if (publicKeysToNotify.length === 0) { return null; }
var beacons = [];
var ke = crypto.createECDH(thaliConfig.BEACON_CURVE);
// Generate preamble
var pubKe = ke.generateKeys();
// We fuzz the expiration by adding on a random number that fits in
// an unsigned 8 bit integer.
var expiration = Date.now() + millisecondsUntilExpiration +
crypto.randomBytes(1).readUInt8(0);
var expirationLong = Long.fromNumber(expiration);
var expirationBuffer = new Buffer(module.exports.LONG_SIZE);
expirationBuffer.writeInt32BE(expirationLong.high, 0);
expirationBuffer.writeInt32BE(expirationLong.low, 4);
beacons.push(Buffer.concat([pubKe, expirationBuffer]));
// UnencryptedKeyId = SHA256(Kx.public().encode()).first(16)
var unencryptedKeyId =
createPublicKeyHash(ecdhForLocalDevice.getPublicKey());
publicKeysToNotify.forEach(function (pubKy) {
// Sxy = ECDH(Kx.private(), PubKy)
var sxy = ecdhForLocalDevice.computeSecret(pubKy);
// HKxy = HKDF(SHA256, Sxy, Expiration, 32)
var hkxy = HKDF(module.exports.SHA256, sxy, expirationBuffer)
.derive('', module.exports.SHA256_HMAC_KEY_SIZE);
// BeaconHmac = HMAC(SHA256, HKxy, Expiration).first(16)
var beaconHmac = crypto.createHmac(module.exports.SHA256, hkxy)
.update(expirationBuffer)
.digest()
.slice(0, module.exports.TRUNCATED_HASH_SIZE);
// Sey = ECDH(Ke.private(), PubKy)
var sey = ke.computeSecret(pubKy);
// hkey = HKDF(SHA256, Sey, Expiration, 16)
var hkey = HKDF(module.exports.SHA256, sey, expirationBuffer)
.derive('', module.exports.AES_128_KEY_SIZE);
// beacons.append(AESEncrypt(GCM, HKey, 0, 128, UnencryptedKeyId) +
// BeaconHmac)
var aes = crypto.createCipher(module.exports.GCM, hkey);
beacons.push(Buffer.concat([
Buffer.concat([aes.update(unencryptedKeyId), aes.final()]),
beaconHmac
]));
});
return Buffer.concat(beacons);
}
|
javascript
|
{
"resource": ""
}
|
q3854
|
generatePskSecret
|
train
|
function generatePskSecret(ecdhForLocalDevice, remotePeerPublicKey,
pskIdentityField) {
var sxy = ecdhForLocalDevice.computeSecret(remotePeerPublicKey);
return HKDF(module.exports.SHA256, sxy, pskIdentityField)
.derive('', module.exports.AES_256_KEY_SIZE);
}
|
javascript
|
{
"resource": ""
}
|
q3855
|
generatePskSecrets
|
train
|
function generatePskSecrets(publicKeysToNotify,
ecdhForLocalDevice,
beaconStreamWithPreAmble) {
var preAmbleSizeInBytes = module.exports.PUBLIC_KEY_SIZE +
module.exports.EXPIRATION_SIZE;
var preAmble = beaconStreamWithPreAmble.slice(0, preAmbleSizeInBytes);
var beaconStreamNoPreAmble =
beaconStreamWithPreAmble.slice(preAmbleSizeInBytes);
var beacons = [];
for (var i = 0; i < beaconStreamNoPreAmble.length;
i += module.exports.BEACON_SIZE) {
beacons.push(
beaconStreamNoPreAmble.slice(i, i + module.exports.BEACON_SIZE));
}
assert(beacons.length === publicKeysToNotify.length, 'We should have the' +
'same number of beacons as public keys to notify');
var pskMap = {};
for (i = 0; i < publicKeysToNotify.length; ++i) {
var pskIdentityField = generatePskIdentityField(preAmble, beacons[i]);
var pskSecret = generatePskSecret(ecdhForLocalDevice, publicKeysToNotify[i],
pskIdentityField);
pskMap[pskIdentityField] = {
publicKey: publicKeysToNotify[i],
pskSecret: pskSecret
};
}
return pskMap;
}
|
javascript
|
{
"resource": ""
}
|
q3856
|
PeerAction
|
train
|
function PeerAction (peerIdentifier, connectionType, actionType, pskIdentity,
pskKey)
{
EventEmitter.call(this);
this._peerIdentifier = peerIdentifier;
this._connectionType = connectionType;
this._actionType = actionType;
this._pskIdentity = pskIdentity;
this._pskKey = pskKey;
this._actionState = PeerAction.actionState.CREATED;
this._id = peerActionCounter;
++peerActionCounter;
}
|
javascript
|
{
"resource": ""
}
|
q3857
|
BrowserInfo
|
train
|
function BrowserInfo() {
var res = {
name: "",
version: ""
};
var userAgent = self.navigator.userAgent;
var reg;
if (reg = /edge\/([\d\.]+)/i.exec(userAgent)) {
res.name = Browser.Edge;
res.version = reg[1];
}
else if (/msie/i.test(userAgent)) {
res.name = Browser.IE;
res.version = /msie ([\d\.]+)/i.exec(userAgent)[1];
}
else if (/Trident/i.test(userAgent)) {
res.name = Browser.IE;
res.version = /rv:([\d\.]+)/i.exec(userAgent)[1];
}
else if (/chrome/i.test(userAgent)) {
res.name = Browser.Chrome;
res.version = /chrome\/([\d\.]+)/i.exec(userAgent)[1];
}
else if (/safari/i.test(userAgent)) {
res.name = Browser.Safari;
res.version = /([\d\.]+) safari/i.exec(userAgent)[1];
}
else if (/firefox/i.test(userAgent)) {
res.name = Browser.Firefox;
res.version = /firefox\/([\d\.]+)/i.exec(userAgent)[1];
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
q3858
|
createUnpackedBundle
|
train
|
function createUnpackedBundle() {
fs.mkdirp(unpackedDir, err => {
if (err && err.code !== 'EEXIST') {
console.log(err);
throw err;
}
let unpackedFile = path.join(__dirname, 'unpacked.js');
let b = browserify(unpackedFile).bundle();
b.on('error', console.error);
let unpackedBundleFile = path.join(unpackedDir, 'unpacked-bundle.js');
const bundleFileStream = fs.createWriteStream(unpackedBundleFile);
bundleFileStream.on('finish', () => {
console.log('Wrote bundled JS into ' + unpackedBundleFile);
});
bundleFileStream.on('pipe', () => {
console.log('Writing bundled JS...');
});
bundleFileStream.on('error', console.error);
b.pipe(bundleFileStream);
// bundleFileStream.end(); // do not do this prematurely!
});
}
|
javascript
|
{
"resource": ""
}
|
q3859
|
train
|
function (query, params, stringifier) {
if (!query || !query.length || !params) {
return query;
}
if (!stringifier) {
stringifier = function (a) {return a.toString()};
}
var parts = [];
var isLiteral = false;
var lastIndex = 0;
var paramsCounter = 0;
for (var i = 0; i < query.length; i++) {
var char = query.charAt(i);
if (char === "'" && query.charAt(i-1) !== '\\') {
//opening or closing quotes in a literal value of the query
isLiteral = !isLiteral;
}
if (!isLiteral && char === '?') {
//is a placeholder
parts.push(query.substring(lastIndex, i));
parts.push(stringifier(params[paramsCounter++]));
lastIndex = i+1;
}
}
parts.push(query.substring(lastIndex));
return parts.join('');
}
|
javascript
|
{
"resource": ""
}
|
|
q3860
|
FrameHeader
|
train
|
function FrameHeader(values) {
if (values) {
if (values instanceof Buffer) {
this.fromBuffer(values);
}
else {
for (var prop in values) {
this[prop] = values[prop];
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q3861
|
QueueWhile
|
train
|
function QueueWhile(test, delayRetry) {
this.queue = async.queue(function (task, queueCallback) {
async.whilst(
test,
function(cb) {
//Retry in a while
if (delayRetry) {
setTimeout(cb, delayRetry);
}
else {
setImmediate(cb);
}
},
function() {
queueCallback(null, null);
}
);
}, 1);
}
|
javascript
|
{
"resource": ""
}
|
q3862
|
DriverError
|
train
|
function DriverError (message, constructor) {
if (constructor) {
Error.captureStackTrace(this, constructor);
this.name = constructor.name;
}
this.message = message || 'Error';
this.info = 'Cassandra Driver Error';
}
|
javascript
|
{
"resource": ""
}
|
q3863
|
copyBuffer
|
train
|
function copyBuffer(buf) {
var targetBuffer = new Buffer(buf.length);
buf.copy(targetBuffer);
return targetBuffer;
}
|
javascript
|
{
"resource": ""
}
|
q3864
|
totalLength
|
train
|
function totalLength (arr) {
if (!arr) {
return 0;
}
var total = 0;
arr.forEach(function (item) {
var length = item.length;
length = length ? length : 0;
total += length;
});
return total;
}
|
javascript
|
{
"resource": ""
}
|
q3865
|
Client
|
train
|
function Client(options) {
events.EventEmitter.call(this);
//Unlimited amount of listeners for internal event queues by default
this.setMaxListeners(0);
this.options = utils.extend({}, optionsDefault, options);
//current connection index
this.connectionIndex = 0;
//current connection index for prepared queries
this.prepareConnectionIndex = 0;
this.preparedQueries = {};
this._createPool();
}
|
javascript
|
{
"resource": ""
}
|
q3866
|
BatchWriter
|
train
|
function BatchWriter(queries, consistency, options) {
this.queries = queries;
options = utils.extend({atomic: true}, options);
this.type = options.atomic ? 0 : 1;
this.type = options.counter ? 2 : this.type;
this.consistency = consistency;
this.streamId = null;
if (consistency === null || typeof consistency === 'undefined') {
this.consistency = types.consistencies.getDefault();
}
}
|
javascript
|
{
"resource": ""
}
|
q3867
|
train
|
function(source) {
var src = (source ? source.src : undefined);
if (this.selectedSrc !== src) {
this.selectedSrc = src;
this.update();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3868
|
cloneSvg
|
train
|
function cloneSvg(src, attrs, styles) {
var clonedSvg = src.cloneNode(true);
domWalk(src, clonedSvg, function (src, tgt) {
if (tgt.style) {
(0, _computedStyles2['default'])(src, tgt.style, styles);
}
}, function (src, tgt) {
if (tgt.style && tgt.parentNode) {
cleanStyle(tgt);
}
if (tgt.attributes) {
cleanAttrs(tgt, attrs, styles);
}
});
return clonedSvg;
}
|
javascript
|
{
"resource": ""
}
|
q3869
|
cleanAttrs
|
train
|
function cleanAttrs (el, attrs, styles) { // attrs === false - remove all, attrs === true - allow all
if (attrs === true) { return; }
Array.prototype.slice.call(el.attributes)
.forEach(function (attr) {
// remove if it is not style nor on attrs whitelist
// keeping attributes that are also styles because attributes override
if (attr.specified) {
if (attrs === '' || attrs === false || (isUndefined(styles[attr.name]) && attrs.indexOf(attr.name) < 0)) {
el.removeAttribute(attr.name);
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
q3870
|
setFocusedElement
|
train
|
function setFocusedElement(cstOption) {
if (focusedElement) {
focusedElement.classList.remove(builderParams.hasFocusClass);
}
if (typeof cstOption !== 'undefined') {
focusedElement = cstOption;
focusedElement.classList.add(builderParams.hasFocusClass);
// Offset update: checks if the focused element is in the visible part of the panelClass
// if not dispatches a custom event
if (isOpen) {
if (cstOption.offsetTop < cstOption.offsetParent.scrollTop
|| cstOption.offsetTop >
(cstOption.offsetParent.scrollTop + cstOption.offsetParent.clientHeight)
- cstOption.clientHeight) {
cstOption.dispatchEvent(new CustomEvent('custom-select:focus-outside-panel', { bubbles: true }));
}
}
} else {
focusedElement = undefined;
}
}
|
javascript
|
{
"resource": ""
}
|
q3871
|
validateTableDefinition
|
train
|
function validateTableDefinition(tableDefinition) {
// Do basic table name validation and leave the rest to the store
Validate.notNull(tableDefinition, 'tableDefinition');
Validate.isObject(tableDefinition, 'tableDefinition');
Validate.isString(tableDefinition.name, 'tableDefinition.name');
Validate.notNullOrEmpty(tableDefinition.name, 'tableDefinition.name');
// Validate the specified column types and check for duplicate columns
var columnDefinitions = tableDefinition.columnDefinitions,
definedColumns = {};
Validate.isObject(columnDefinitions);
Validate.notNull(columnDefinitions);
for (var columnName in columnDefinitions) {
Validate.isString(columnDefinitions[columnName], 'columnType');
Validate.notNullOrEmpty(columnDefinitions[columnName], 'columnType');
if (definedColumns[columnName.toLowerCase()]) {
throw new Error('Duplicate definition for column ' + columnName + '" in table "' + tableDefinition.name + '"');
}
definedColumns[columnName.toLowerCase()] = true;
}
}
|
javascript
|
{
"resource": ""
}
|
q3872
|
addTableDefinition
|
train
|
function addTableDefinition(tableDefinitions, tableDefinition) {
Validate.isObject(tableDefinitions);
Validate.notNull(tableDefinitions);
validateTableDefinition(tableDefinition);
tableDefinitions[tableDefinition.name.toLowerCase()] = tableDefinition;
}
|
javascript
|
{
"resource": ""
}
|
q3873
|
getTableDefinition
|
train
|
function getTableDefinition(tableDefinitions, tableName) {
Validate.isObject(tableDefinitions);
Validate.notNull(tableDefinitions);
Validate.isString(tableName);
Validate.notNullOrEmpty(tableName);
return tableDefinitions[tableName.toLowerCase()];
}
|
javascript
|
{
"resource": ""
}
|
q3874
|
getColumnType
|
train
|
function getColumnType(columnDefinitions, columnName) {
Validate.isObject(columnDefinitions);
Validate.notNull(columnDefinitions);
Validate.isString(columnName);
Validate.notNullOrEmpty(columnName);
for (var column in columnDefinitions) {
if (column.toLowerCase() === columnName.toLowerCase()) {
return columnDefinitions[column];
}
}
}
|
javascript
|
{
"resource": ""
}
|
q3875
|
getColumnName
|
train
|
function getColumnName(columnDefinitions, property) {
Validate.isObject(columnDefinitions);
Validate.notNull(columnDefinitions);
Validate.isString(property);
Validate.notNullOrEmpty(property);
for (var column in columnDefinitions) {
if (column.toLowerCase() === property.toLowerCase()) {
return column;
}
}
return property; // If no definition found for property, simply returns the column name as is
}
|
javascript
|
{
"resource": ""
}
|
q3876
|
getId
|
train
|
function getId(record) {
Validate.isObject(record);
Validate.notNull(record);
for (var property in record) {
if (property.toLowerCase() === idPropertyName.toLowerCase()) {
return record[property];
}
}
}
|
javascript
|
{
"resource": ""
}
|
q3877
|
isId
|
train
|
function isId(property) {
Validate.isString(property);
Validate.notNullOrEmpty(property);
return property.toLowerCase() === idPropertyName.toLowerCase();
}
|
javascript
|
{
"resource": ""
}
|
q3878
|
upsertWithLogging
|
train
|
function upsertWithLogging(tableName, instance, action, shouldOverwrite) {
Validate.isString(tableName, 'tableName');
Validate.notNullOrEmpty(tableName, 'tableName');
Validate.notNull(instance, 'instance');
Validate.isValidId(instance.id, 'instance.id');
if (!store) {
throw new Error('MobileServiceSyncContext not initialized');
}
return store.lookup(tableName, instance.id, true /* suppressRecordNotFoundError */).then(function(existingRecord) {
if (existingRecord && !shouldOverwrite) {
throw new Error('Record with id ' + existingRecord.id + ' already exists in the table ' + tableName);
}
}).then(function() {
return operationTableManager.getLoggingOperation(tableName, action, instance);
}).then(function(loggingOperation) {
return store.executeBatch([
{
action: 'upsert',
tableName: tableName,
data: instance
},
loggingOperation
]);
}).then(function() {
return instance;
});
}
|
javascript
|
{
"resource": ""
}
|
q3879
|
getSqliteType
|
train
|
function getSqliteType (columnType) {
var sqliteType;
switch (columnType) {
case ColumnType.Object:
case ColumnType.Array:
case ColumnType.String:
case ColumnType.Text:
sqliteType = "TEXT";
break;
case ColumnType.Integer:
case ColumnType.Int:
case ColumnType.Boolean:
case ColumnType.Bool:
case ColumnType.Date:
sqliteType = "INTEGER";
break;
case ColumnType.Real:
case ColumnType.Float:
sqliteType = "REAL";
break;
default:
throw new Error('Column type ' + columnType + ' is not supported');
}
return sqliteType;
}
|
javascript
|
{
"resource": ""
}
|
q3880
|
serialize
|
train
|
function serialize (value, columnDefinitions) {
var serializedValue = {};
try {
Validate.notNull(columnDefinitions, 'columnDefinitions');
Validate.isObject(columnDefinitions);
Validate.notNull(value);
Validate.isObject(value);
for (var property in value) {
var columnType = storeHelper.getColumnType(columnDefinitions, property);
// Skip properties that don't match any column in the table
if (!_.isNull(columnType)) {
serializedValue[property] = serializeMember(value[property], columnType);
}
}
} catch (error) {
throw new verror.VError(error, 'Failed to serialize value ' + JSON.stringify(value) + '. Column definitions: ' + JSON.stringify(columnDefinitions));
}
return serializedValue;
}
|
javascript
|
{
"resource": ""
}
|
q3881
|
deserialize
|
train
|
function deserialize (value, columnDefinitions) {
var deserializedValue = {};
try {
Validate.notNull(columnDefinitions, 'columnDefinitions');
Validate.isObject(columnDefinitions);
Validate.notNull(value);
Validate.isObject(value);
for (var property in value) {
var columnName = storeHelper.getColumnName(columnDefinitions, property); // this helps us deserialize with proper case for the property name
deserializedValue[columnName] = deserializeMember(value[property], storeHelper.getColumnType(columnDefinitions, property));
}
} catch (error) {
throw new verror.VError(error, 'Failed to deserialize value ' + JSON.stringify(value) + '. Column definitions: ' + JSON.stringify(columnDefinitions));
}
return deserializedValue;
}
|
javascript
|
{
"resource": ""
}
|
q3882
|
serializeMember
|
train
|
function serializeMember(value, columnType) {
// Start by checking if the specified column type is valid
if (!isColumnTypeValid(columnType)) {
throw new Error('Column type ' + columnType + ' is not supported');
}
// Now check if the specified value can be stored in a column of type columnType
if (!isJSValueCompatibleWithColumnType(value, columnType)) {
throw new Error('Converting value ' + JSON.stringify(value) + ' of type ' + typeof value + ' to type ' + columnType + ' is not supported.');
}
// If we are here, it means we are good to proceed with serialization
var sqliteType = getSqliteType(columnType),
serializedValue;
switch (sqliteType) {
case "TEXT":
serializedValue = typeConverter.convertToText(value);
break;
case "INTEGER":
serializedValue = typeConverter.convertToInteger(value);
break;
case "REAL":
serializedValue = typeConverter.convertToReal(value);
break;
default:
throw new Error('Column type ' + columnType + ' is not supported');
}
return serializedValue;
}
|
javascript
|
{
"resource": ""
}
|
q3883
|
deserializeMember
|
train
|
function deserializeMember(value, columnType) {
// Handle this special case first.
// Simply return 'value' if a corresponding columnType is not defined.
if (!columnType) {
return value;
}
// Start by checking if the specified column type is valid.
if (!isColumnTypeValid(columnType)) {
throw new Error('Column type ' + columnType + ' is not supported');
}
// Now check if the specified value can be stored in a column of type columnType.
if (!isSqliteValueCompatibleWithColumnType(value, columnType)) {
throw new Error('Converting value ' + JSON.stringify(value) + ' of type ' + typeof value +
' to type ' + columnType + ' is not supported.');
}
// If we are here, it means we are good to proceed with deserialization
var deserializedValue, error;
switch (columnType) {
case ColumnType.Object:
deserializedValue = typeConverter.convertToObject(value);
break;
case ColumnType.Array:
deserializedValue = typeConverter.convertToArray(value);
break;
case ColumnType.String:
case ColumnType.Text:
deserializedValue = typeConverter.convertToText(value);
break;
case ColumnType.Integer:
case ColumnType.Int:
deserializedValue = typeConverter.convertToInteger(value);
break;
case ColumnType.Boolean:
case ColumnType.Bool:
deserializedValue = typeConverter.convertToBoolean(value);
break;
case ColumnType.Date:
deserializedValue = typeConverter.convertToDate(value);
break;
case ColumnType.Real:
case ColumnType.Float:
deserializedValue = typeConverter.convertToReal(value);
break;
default:
throw new Error(_.format(Platform.getResourceString("sqliteSerializer_UnsupportedColumnType"), columnType));
}
return deserializedValue;
}
|
javascript
|
{
"resource": ""
}
|
q3884
|
serializeValue
|
train
|
function serializeValue(value) {
var type;
if ( _.isNull(value) ) {
type = ColumnType.Object;
} else if ( _.isNumber(value) ) {
type = ColumnType.Real;
} else if ( _.isDate(value) ) {
type = ColumnType.Date;
} else if ( _.isBool(value) ) {
type = ColumnType.Boolean;
} else if ( _.isString(value) ) {
type = ColumnType.String;
} else if ( _.isArray(value) ) {
type = ColumnType.Array;
} else if ( _.isObject(value) ) {
type = ColumnType.Object;
} else {
type = ColumnType.Object;
}
return serializeMember(value, type);
}
|
javascript
|
{
"resource": ""
}
|
q3885
|
run
|
train
|
function run(task) {
return Platform.async(function(callback) {
// parameter validation
Validate.isFunction(task);
Validate.isFunction(callback);
// Add the task to the queue of pending tasks and trigger task processing
queue.push({
task: task,
callback: callback
});
processTask();
})();
}
|
javascript
|
{
"resource": ""
}
|
q3886
|
processTask
|
train
|
function processTask() {
setTimeout(function() {
if (isBusy || queue.length === 0) {
return;
}
isBusy = true;
var next = queue.shift(),
result,
error;
Platform.async(function(callback) { // Start a promise chain
callback();
})().then(function() {
return next.task(); // Run the task
}).then(function(res) { // task completed successfully
isBusy = false;
processTask();
next.callback(null, res); // resolve the promise returned by the run function
}, function(err) { // task failed
isBusy = false;
processTask();
next.callback(err); // reject the promise returned by the run function
});
}, 0);
}
|
javascript
|
{
"resource": ""
}
|
q3887
|
initialize
|
train
|
function initialize () {
return pullTaskRunner.run(function() {
return store.defineTable({
name: pulltimeTableName,
columnDefinitions: {
id: 'string', // column for storing queryId
tableName: 'string', // column for storing table name
value: 'date' // column for storing lastKnownUpdatedAt
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q3888
|
pull
|
train
|
function pull(query, queryId, settings) {
//TODO: support pullQueryId
//TODO: page size should be configurable
return pullTaskRunner.run(function() {
validateQuery(query, 'query');
Validate.isString(queryId, 'queryId'); // non-null string or null - both are valid
Validate.isObject(settings, 'settings');
settings = settings || {};
if (_.isNull(settings.pageSize)) {
pageSize = defaultPageSize;
} else if (_.isInteger(settings.pageSize) && settings.pageSize > 0) {
pageSize = settings.pageSize;
} else {
throw new Error('Page size must be a positive integer. Page size ' + settings.pageSize + ' is invalid.');
}
// Make a copy of the query as we will be modifying it
tablePullQuery = copyQuery(query);
mobileServiceTable = client.getTable(tablePullQuery.getComponents().table);
mobileServiceTable._features = queryId ? [constants.features.OfflineSync, constants.features.IncrementalPull] : [constants.features.OfflineSync];
pullQueryId = queryId;
// Set up the query for initiating a pull and then pull all pages
return setupQuery().then(function() {
return pullAllPages();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q3889
|
pullAllPages
|
train
|
function pullAllPages() {
// 1. Pull one page
// 2. Check if Pull is complete
// 3. If it is complete, go to 5. If not, update the query to fetch the next page.
// 4. Go to 1
// 5. DONE
return pullPage().then(function(pulledRecords) {
if (!isPullComplete(pulledRecords)) {
// update query and continue pulling the remaining pages
return updateQueryForNextPage(pulledRecords).then(function() {
return pullAllPages();
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q3890
|
pullPage
|
train
|
function pullPage() {
// Define appropriate parameter to enable fetching of deleted records from the server.
// Assumption is that soft delete is enabled on the server table.
var params = {};
params[tableConstants.includeDeletedFlag] = true;
var pulledRecords;
// azure-query-js does not support datatimeoffset
// As a temporary workaround, convert the query to an odata string and replace datetime' with datetimeoffset'.
var queryString = pagePullQuery.toOData();
var tableName = pagePullQuery.getComponents().table;
queryString = queryString.replace(new RegExp('^/' + tableName), '').replace("datetime'", "datetimeoffset'");
return mobileServiceTable.read(queryString, params).then(function(result) {
pulledRecords = result || [];
var chain = Platform.async(function(callback) {
callback();
})();
// Process all records in the page
for (var i = 0; i < pulledRecords.length; i++) {
chain = processPulledRecord(chain, tableName, pulledRecords[i]);
}
return chain;
}).then(function(pulled) {
return onPagePulled();
}).then(function() {
return pulledRecords;
});
}
|
javascript
|
{
"resource": ""
}
|
q3891
|
updateQueryForNextPage
|
train
|
function updateQueryForNextPage(pulledRecords) {
return Platform.async(function(callback) {
callback();
})().then(function() {
if (!pulledRecords) {
throw new Error('Something is wrong. pulledRecords cannot be null at this point');
}
var lastRecord = pulledRecords[ pulledRecords.length - 1];
if (!lastRecord) {
throw new Error('Something is wrong. Possibly invalid response from the server. lastRecord cannot be null!');
}
var lastRecordTime = lastRecord[tableConstants.sysProps.updatedAtColumnName];
if (!_.isDate(lastRecordTime)) {
throw new Error('Property ' + tableConstants.sysProps.updatedAtColumnName + ' of the last record should be a valid date');
}
if (lastRecordTime.getTime() === lastKnownUpdatedAt.getTime()) {
pagePullQuery.skip(pagePullQuery.getComponents().skip + pulledRecords.length);
} else {
buildQueryFromLastKnownUpdateAt(lastRecordTime);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q3892
|
buildQueryFromLastKnownUpdateAt
|
train
|
function buildQueryFromLastKnownUpdateAt(updatedAt) {
lastKnownUpdatedAt = updatedAt;
// Make a copy of the table query and tweak it to fetch the next first page
pagePullQuery = copyQuery(tablePullQuery);
pagePullQuery = pagePullQuery.where(function(lastKnownUpdatedAt) {
// Ideally we would have liked to set this[tableConstants.sysProps.updatedAtColumnName]
// but this isn't supported
return this.updatedAt >= lastKnownUpdatedAt;
}, lastKnownUpdatedAt);
pagePullQuery.orderBy(tableConstants.sysProps.updatedAtColumnName);
pagePullQuery.take(pageSize);
}
|
javascript
|
{
"resource": ""
}
|
q3893
|
onPagePulled
|
train
|
function onPagePulled() {
// For incremental pull, make a note of the lastKnownUpdatedAt in the store
if (pullQueryId) {
return store.upsert(pulltimeTableName, {
id: pullQueryId,
tableName: pagePullQuery.getComponents().table,
value: lastKnownUpdatedAt
});
}
}
|
javascript
|
{
"resource": ""
}
|
q3894
|
validateQuery
|
train
|
function validateQuery(query) {
Validate.isObject(query);
Validate.notNull(query);
var components = query.getComponents();
for (var i in components.ordering) {
throw new Error('orderBy and orderByDescending clauses are not supported in the pull query');
}
if (components.skip) {
throw new Error('skip is not supported in the pull query');
}
if (components.take) {
throw new Error('take is not supported in the pull query');
}
if (components.selections && components.selections.length !== 0) {
throw new Error('select is not supported in the pull query');
}
if (components.includeTotalCount) {
throw new Error('includeTotalCount is not supported in the pull query');
}
}
|
javascript
|
{
"resource": ""
}
|
q3895
|
copyQuery
|
train
|
function copyQuery(query) {
var components = query.getComponents();
var queryCopy = new Query(components.table);
queryCopy.setComponents(components);
return queryCopy;
}
|
javascript
|
{
"resource": ""
}
|
q3896
|
purge
|
train
|
function purge(query, forcePurge) {
return storeTaskRunner.run(function() {
Validate.isObject(query, 'query');
Validate.notNull(query, 'query');
if (!_.isNull(forcePurge)) {
Validate.isBool(forcePurge, 'forcePurge');
}
// Query for pending operations associated with this table
var operationQuery = new Query(tableConstants.operationTableName)
.where(function(tableName) {
return this.tableName === tableName;
}, query.getComponents().table);
// Query to search for the incremental sync state associated with this table
var incrementalSyncStateQuery = new Query(tableConstants.pulltimeTableName)
.where(function(tableName) {
return this.tableName === tableName;
}, query.getComponents().table);
// 1. In case of force purge, simply remove operation table entries for the table being purged
// Else, ensure no records exists in the operation table for the table being purged.
// 2. Delete pull state for all incremental queries associated with this table
// 3. Delete the records from the table as specified by 'query'
//
// TODO: All store operations performed while purging should be part of a single transaction
// Note: An incremental pull after a purge should fetch purged records again. If we run 3 before 2,
// we might end up in a state where 3 is complete but 2 has failed. In such a case subsequent incremental pull
// will not re-fetch purged records. Hence, it is important to run 2 before 3.
// There still exists a possibility of pending operations being deleted while force purging and the subsequent
// operations failing which is tracked by the above TODO.
return Platform.async(function(callback) {
callback();
})().then(function() {
if (forcePurge) {
return store.del(operationQuery);
} else {
return store.read(operationQuery).then(function(operations) {
if (operations.length > 0) {
throw new Error('Cannot purge the table as it contains pending operations');
}
});
}
}).then(function() {
return store.del(incrementalSyncStateQuery);
}).then(function() {
return store.del(query);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q3897
|
lockOperation
|
train
|
function lockOperation(id) {
return runner.run(function() {
// Locking a locked operation should have no effect
if (lockedOperationId === id) {
return;
}
if (!lockedOperationId) {
lockedOperationId = id;
return;
}
throw new Error('Only one operation can be locked at a time');
});
}
|
javascript
|
{
"resource": ""
}
|
q3898
|
getCondenseAction
|
train
|
function getCondenseAction(pendingOperation, newAction) {
var pendingAction = pendingOperation.action,
condenseAction;
if (pendingAction === 'insert' && newAction === 'update') {
condenseAction = 'nop';
} else if (pendingAction === 'insert' && newAction === 'delete') {
condenseAction = 'remove';
} else if (pendingAction === 'update' && newAction === 'update') {
condenseAction = 'nop';
} else if (pendingAction === 'update' && newAction === 'delete') {
condenseAction = 'modify';
} else if (pendingAction === 'delete' && newAction === 'delete') {
condenseAction = 'nop';
} else if (pendingAction === 'delete') {
throw new Error('Operation ' + newAction + ' not supported as a DELETE operation is pending'); //TODO: Limitation on all client SDKs
} else {
throw new Error('Condense not supported when pending action is ' + pendingAction + ' and new action is ' + newAction);
}
if (isLocked(pendingOperation)) {
condenseAction = 'add';
}
return condenseAction;
}
|
javascript
|
{
"resource": ""
}
|
q3899
|
getOperationForInsertingLog
|
train
|
function getOperationForInsertingLog(tableName, action, item) {
return api.getMetadata(tableName, action, item).then(function(metadata) {
return {
tableName: operationTableName,
action: 'upsert',
data: {
id: ++maxId,
tableName: tableName,
action: action,
itemId: item[idPropertyName],
metadata: metadata
}
};
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.