_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q59600
|
getTemplatePath
|
validation
|
function getTemplatePath (folder, type) {
switch (type) {
case 'product':
return path.join(folder, 'product.html')
case 'company':
return path.join(folder, 'company.html')
}
}
|
javascript
|
{
"resource": ""
}
|
q59601
|
registerPartials
|
validation
|
function registerPartials (folder) {
const partialsFolder = path.join(folder, '_includes')
const partials = fs.readdirSync(partialsFolder)
.filter(isValidPartial)
.reduce((result, partial) => {
const ext = path.extname(partial)
const fileFullPath = path.join(partialsFolder, partial)
const data = fs.readFileSync(fileFullPath, 'utf-8')
// Store as `"filename without extension": content`.
result[path.basename(partial, ext)] = data
return result
}, {})
handlebars.registerPartial(partials)
}
|
javascript
|
{
"resource": ""
}
|
q59602
|
validation
|
function (image) {
const imageName = path.join('images', image)
const thumbName = path.join('images', `${image}.thumb.jpg`)
const thumbPath = path.join(destination, thumbName)
if (fs.existsSync(thumbPath)) return thumbName
return imageName
}
|
javascript
|
{
"resource": ""
}
|
|
q59603
|
createRelation
|
validation
|
function createRelation (type, product) {
return {
type,
text: product.presskit.title,
path: getAbsolutePageUrl(product.path, product.presskit.type)
}
}
|
javascript
|
{
"resource": ""
}
|
q59604
|
copyMandatoryFiles
|
validation
|
async function copyMandatoryFiles () {
const buildDir = createAndGetBuildFolder()
for (const f of assetsToCopy) {
const filepath = path.resolve(f)
// Get filename and dirname from the provided path.
const filename = path.basename(filepath)
const dirname = path.basename(path.dirname(filepath))
// Create the directory for this file if needed.
// ie. css/master.css needs a `css` directory.
const targetDir = path.join(buildDir, dirname)
sfs.createDir(targetDir)
// And copy the file.
const targetPath = path.join(targetDir, filename)
console.log('- ' + targetPath)
try {
await writeFilePromised(targetPath, await readFilePromised(filepath))
} catch (e) {
const msg = chalk.dim(`(${e.message})`)
console.error(`There was an error while copying ${chalk.bold(filename)}. ${msg}`)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q59605
|
isDataFile
|
validation
|
function isDataFile (filename) {
const ext = path.extname(filename)
const filenameWithoutExt = path.basename(filename, ext)
return filenameWithoutExt === 'data' && ext === '.xml'
}
|
javascript
|
{
"resource": ""
}
|
q59606
|
startWatcher
|
validation
|
function startWatcher (entryPoint, callback) {
if (config.commands.build.dev) {
// Delete the assets (CSS/etc.) before.
// They might not be there, but we must ensure that they are properly
// deleted.
//
// This is necessary, otherwise, remaining copied CSS files will have
// an higher priority than the ones provided by the server (from
// the `assets/` folder).
rimraf(path.join(createAndGetBuildFolder(), 'css'), () => {
installDevelopmentWatcher(entryPoint, callback)
})
} else {
installWatcher(entryPoint, callback)
}
}
|
javascript
|
{
"resource": ""
}
|
q59607
|
isEmpty
|
validation
|
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value) &&
(isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
isBuffer(value) || isTypedArray(value) || isArguments(value))) {
return !value.length;
}
var tag = getTag$1(value);
if (tag == mapTag$3 || tag == setTag$3) {
return !value.size;
}
if (isPrototype(value)) {
return !baseKeys(value).length;
}
for (var key in value) {
if (hasOwnProperty$c.call(value, key)) {
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q59608
|
initCloneByTag
|
validation
|
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag$2:
return cloneArrayBuffer(object);
case boolTag$2:
case dateTag$2:
return new Ctor(+object);
case dataViewTag$3:
return cloneDataView(object, isDeep);
case float32Tag$1: case float64Tag$1:
case int8Tag$1: case int16Tag$1: case int32Tag$1:
case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:
return cloneTypedArray(object, isDeep);
case mapTag$4:
return new Ctor;
case numberTag$2:
case stringTag$3:
return new Ctor(object);
case regexpTag$2:
return cloneRegExp(object);
case setTag$4:
return new Ctor;
case symbolTag$2:
return cloneSymbol(object);
}
}
|
javascript
|
{
"resource": ""
}
|
q59609
|
compileTS
|
validation
|
function compileTS (module) {
var exitCode = 0;
var tmpDir = path.join(options.tmpDir, "tsreq");
var relativeFolder = path.dirname(path.relative(process.cwd(), module.filename));
var jsname = path.join(tmpDir, relativeFolder, path.basename(module.filename, ".ts") + ".js");
if (!isModified(module.filename, jsname)) {
return jsname;
}
var argv = [
"node",
"tsc.js",
!! options.emitOnError ? "" : "--noEmitOnError",
"--nolib",
"--rootDir",
process.cwd(),
"--target",
options.targetES5 ? "ES5" : "ES3", !! options.moduleKind ? "--module" : "", !! options.moduleKind ? options.moduleKind : "",
"--outDir",
tmpDir,
libPath,
options.nodeLib ? path.resolve(__dirname, "typings/node.d.ts") : null,
module.filename
];
var proc = merge(merge({}, process), {
argv: compact(argv),
exit: function(code) {
if (code !== 0 && options.exitOnError) {
console.error('Fatal Error. Unable to compile TypeScript file. Exiting.');
process.exit(code);
}
exitCode = code;
}
});
var sandbox = {
process: proc,
require: require,
module: module,
Buffer: Buffer,
setTimeout: setTimeout,
clearTimeout: clearTimeout,
__filename: tsc
};
tscScript.runInNewContext(sandbox);
if (exitCode !== 0) {
throw new Error('Unable to compile TypeScript file.');
}
return jsname;
}
|
javascript
|
{
"resource": ""
}
|
q59610
|
toHexString
|
validation
|
function toHexString(num) {
var str = num.toString(16);
while (str.length < 2) {
str = '0' + str;
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q59611
|
resetStyles
|
validation
|
function resetStyles(stack) {
var stackClone = stack.slice(0);
stack.length = 0;
return stackClone.reverse().map(function (tag) {
return '</' + tag + '>';
}).join('');
}
|
javascript
|
{
"resource": ""
}
|
q59612
|
range
|
validation
|
function range(low, high) {
const results = [];
for (var j = low; j <= high; j++) {
results.push(j);
}
return results;
}
|
javascript
|
{
"resource": ""
}
|
q59613
|
categoryForCode
|
validation
|
function categoryForCode(code) {
code = parseInt(code, 10);
var result = null;
if (code === 0) {
result = 'all';
} else if (code === 1) {
result = 'bold';
} else if ((2 < code && code < 5)) {
result = 'underline';
} else if ((4 < code && code < 7)) {
result = 'blink';
} else if (code === 8) {
result = 'hide';
} else if (code === 9) {
result = 'strike';
} else if ((29 < code && code < 38) || code === 39 || (89 < code && code < 98)) {
result = 'foreground-color';
} else if ((39 < code && code < 48) || code === 49 || (99 < code && code < 108)) {
result = 'background-color';
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q59614
|
updateStickyStack
|
validation
|
function updateStickyStack(stickyStack, token, data) {
if (token !== 'text') {
stickyStack = stickyStack.filter(notCategory(categoryForCode(data)));
stickyStack.push({token: token, data: data, category: categoryForCode(data)});
}
return stickyStack;
}
|
javascript
|
{
"resource": ""
}
|
q59615
|
VFile
|
validation
|
function VFile(options) {
var prop
var index
var length
if (!options) {
options = {}
} else if (typeof options === 'string' || buffer(options)) {
options = {contents: options}
} else if ('message' in options && 'messages' in options) {
return options
}
if (!(this instanceof VFile)) {
return new VFile(options)
}
this.data = {}
this.messages = []
this.history = []
this.cwd = process.cwd()
// Set path related properties in the correct order.
index = -1
length = order.length
while (++index < length) {
prop = order[index]
if (own.call(options, prop)) {
this[prop] = options[prop]
}
}
// Set non-path related properties.
for (prop in options) {
if (order.indexOf(prop) === -1) {
this[prop] = options[prop]
}
}
}
|
javascript
|
{
"resource": ""
}
|
q59616
|
message
|
validation
|
function message(reason, position, origin) {
var filePath = this.path
var message = new VMessage(reason, position, origin)
if (filePath) {
message.name = filePath + ':' + message.name
message.file = filePath
}
message.fatal = false
this.messages.push(message)
return message
}
|
javascript
|
{
"resource": ""
}
|
q59617
|
getConfig
|
validation
|
function getConfig(projectDir, appName, env) {
if (!['dev', 'test', 'prod'].includes(env)) exit(`Incorrect env value: ${env}`);
process.env.NODE_ENV = {dev: 'development', test: 'testing', prod: 'production'}[env];
const configPath = path.join(projectDir, 'basys.json');
let projectConfig;
try {
projectConfig = fs.readFileSync(configPath, 'utf8');
} catch (e) {
exit(`Couldn't read configuration file ${configPath}\n`);
}
try {
projectConfig = JSON5.parse(projectConfig);
} catch (e) {
exit(
`Syntax error in ${configPath}: ${e.message}\n` +
'You can use JSON5 (https://json5.org) which is an extension of the JSON format, that includes:\n' +
' - comments,\n - unquoted and single-quoted object keys,\n - trailing commas,\n - single-quoted and multi-line strings.\n',
);
}
// BUG: Introduce some shortcuts for validating the configs, or use some library. App builder import function should do it.
if (!projectConfig || projectConfig.constructor !== Object) {
exit(`${configPath} value must be an object`);
}
if (!projectConfig.apps) exit("'apps' option must be provided in basys.json");
const appNames = Object.keys(projectConfig.apps);
if (appNames.length === 0) exit('At least one app must be defined in basys.json');
// BUG: validate that all appNames use allowed symbols only
if (!appName) {
if (appNames.length > 1) exit('App name must be specified');
appName = appNames[0];
}
if (!appNames.includes(appName)) {
exit(`Incorrect app name: '${appName}'. Available names are: '${appNames.join("', '")}'.`);
}
let config = projectConfig.apps[appName];
if (!['web', 'mobile', 'desktop'].includes(config.type)) {
exit(
`Incorrect ${appName} app type: '${
config.type
}'. Allowed values are: 'web', 'mobile', 'desktop'.`,
);
}
// Default app configuration
const defaultConfig = {
entry: null, // Path to UI entry file (relative to src/ directory)
favicon: null,
styles: [],
overrides: {},
caseSensitive: false,
sourceMap: false,
host: 'localhost',
// In dev env another free port will be determined if this one is occupied.
// In other envs the server will fail to start.
port: 8080,
poll: false, // dev env only, see https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
custom: {}, // Holds custom config options (shouldn't overlap with any built-in options)
};
if (config.type === 'web') {
Object.assign(defaultConfig, {
backendEntry: null, // Path to backend entry file (relative to src/ directory)
backendPort: 3000,
nodeVersion: env === 'dev' ? 'current' : '8.9',
browsers: ['> 0.5%', 'last 2 versions', 'Firefox ESR', 'not dead'],
// BUG: automatically detect the browsers available on developer's machine? (only relevant if web app is present)
// BUG: allow to override it via CLI arguments?
// BUG: support remote browsers
// Available values: 'chromium', 'chrome', 'chrome:headless', 'chrome-canary', 'ie', 'edge',
// 'firefox', 'firefox:headless', 'opera', 'safari'
testBrowsers: [],
});
}
// BUG: for mobile apps provide ios/android configuration, supported versions
if (config[env]) {
config = merge(config, config[env]);
delete config.dev;
delete config.test;
delete config.prod;
}
config = merge(defaultConfig, config);
// Validate that custom options don't overlap with any built-in options
for (const key in config.custom) {
if (key in config) exit(`Custom config option '${key}' is not allowed`);
}
const tempDir = path.join(projectDir, '.basys', appName, env);
fs.ensureDirSync(tempDir);
config = merge(config, {
appName,
env,
assetsPublicPath: '/', // BUG: maybe set it to '/static/'? don't expose to user?
tempDir,
projectDir,
distDir: env === 'prod' ? path.join(projectDir, 'dist', appName) : tempDir,
});
// BUG: Validate both config files (depending on env), if invalid raise a meaningful error (with a link to local or public docs?)
// Look at https://github.com/mozilla/node-convict , https://github.com/ianstormtaylor/superstruct
return config;
}
|
javascript
|
{
"resource": ""
}
|
q59618
|
codeConfig
|
validation
|
function codeConfig(config) {
const conf = Object.create(null);
for (const key in config.custom) {
conf[key] = config.custom[key];
}
for (const key of ['host', 'port', 'backendPort']) {
conf[key] = config[key];
}
return conf;
}
|
javascript
|
{
"resource": ""
}
|
q59619
|
validation
|
function (cb) {
/**
* This callback receives generated id
* @callback callback
* @param {Error} error - Error occurred during id generation
* @param {Buffer} id - Generated id
*/
var id = new Buffer(8), time = Date.now() - this.epoch;
id.fill(0);
// Generates id in the same millisecond as the previous id
if (time === this.lastTime) {
// If all sequence values (4096 unique values including 0) have been used
// to generate ids in the current millisecond (overflow is true) wait till next millisecond
if (this.overflow) {
overflowCond(this, cb);
return;
}
// Increase sequence counter
/*jslint bitwise: true */
this.seq = (this.seq + 1) & this.seqMask;
// sequence counter exceeded its max value (4095)
// - set overflow flag and wait till next millisecond
if (this.seq === 0) {
this.overflow = true;
overflowCond(this, cb);
return;
}
} else {
this.overflow = false;
this.seq = 0;
}
this.lastTime = time;
id.writeUInt32BE(((time & 0x3) << 22) | this.id | this.seq, 4);
id.writeUInt8(Math.floor(time / 4) & 0xFF, 4);
id.writeUInt16BE(Math.floor(time / FlakeId.POW10) & 0xFFFF, 2);
id.writeUInt16BE(Math.floor(time / FlakeId.POW26) & 0xFFFF, 0);
if (cb) {
process.nextTick(cb.bind(null, null, id));
}
else {
return id;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q59620
|
Route
|
validation
|
function Route(spec) {
var route;
if (this) {
// constructor called with new
route = this;
} else {
// constructor called as a function
route = Object.create(Route.prototype);
}
if (typeof spec === 'undefined') {
throw new Error('A route spec is required');
}
route.spec = spec;
route.ast = Parser.parse(spec);
return route;
}
|
javascript
|
{
"resource": ""
}
|
q59621
|
createVisitor
|
validation
|
function createVisitor(handlers) {
nodeTypes.forEach(function (nodeType) {
if (typeof handlers[nodeType] === 'undefined') {
throw new Error('No handler defined for ' + nodeType.displayName);
}
});
return {
/**
* Call the given handler for this node type
* @param {Object} node the AST node
* @param {Object} context context to pass through to handlers
* @return {Object}
*/
visit: function (node, context) {
return this.handlers[node.displayName].call(this, node, context);
},
handlers: handlers
};
}
|
javascript
|
{
"resource": ""
}
|
q59622
|
writeTop
|
validation
|
function writeTop(d, loc) {
if (d.indexOf('\n') != -1) {
throw 'Can not write content having \\n'
}
this.chunks.unshift(chunk(d, loc))
}
|
javascript
|
{
"resource": ""
}
|
q59623
|
updateIndent
|
validation
|
function updateIndent() {
var str = ''
for (var idx = 0; idx < this.indentLevel; idx++) {
str += this.indentUnit
}
this.currentIndent = str
}
|
javascript
|
{
"resource": ""
}
|
q59624
|
parseOpts
|
validation
|
function parseOpts(argv) {
var lastOpt, parsed, opts = {}
argv.forEach(function(arg){
parsed = rOption.exec(arg)
if (parsed) {
lastOpt = parsed[1]
opts[lastOpt] = true
return
}
opts[lastOpt] = arg
})
return opts
}
|
javascript
|
{
"resource": ""
}
|
q59625
|
run
|
validation
|
function run(opts) {
throwIfRequiredOption(opts, 'src')
// register `.ram` extension in nodejs modules
Module._extensions[util.ext] = function(module, filename) {
var content = fs.readFileSync(filename, 'utf8')
var result = ram.compile(content, {
filename: filename,
format: 'cjs',
})
module._compile(result.js, filename)
}
Module.prototype.load = function load(filename) {
var extension = path.extname(filename)
this.filename = filename
this.paths = Module._nodeModulePaths(path.dirname(filename))
Module._extensions[extension](this, filename)
return this.loaded = true
}
var src = opts['src']
var absolute = path.resolve(process.cwd(), src)
// globalize Ramda module to be used by loaded modules
Object.assign(global, R)
require(absolute)
}
|
javascript
|
{
"resource": ""
}
|
q59626
|
_eval
|
validation
|
function _eval(opts) {
throwIfRequiredOption(opts, 'src')
var src = opts['src']
// read from stdin
if (src === 'stdin') {
readFromStdin(function(src) {
run(src)
})
} else {
run(src)
}
function run(src) {
var fn = new Function('R', ram.compile(src, '<eval>').js)
fn(R)
}
}
|
javascript
|
{
"resource": ""
}
|
q59627
|
compile
|
validation
|
function compile(opts) {
var srcPath = opts['src'] || process.cwd()
var dstPath = opts['dst']
var format = opts['format'] || 'cjs'
var toStdout = dstPath === 'stdout'
var stat = fs.statSync(srcPath)
if (!srcPath) {
srcPath = path.cwd()
}
// calculate destiny path based on source path
if (!dstPath) {
dstPath = path.join(
path.dirname(srcPath),
path.basename(srcPath, util.ext) + (stat.isFile() ? '.js' : '')
)
}
if (stat.isFile()) {
compileFile(srcPath, dstPath, format, toStdout)
} else if (stat.isDirectory()) {
compileDir(srcPath, dstPath, format)
}
}
|
javascript
|
{
"resource": ""
}
|
q59628
|
compileFile
|
validation
|
function compileFile(srcPath, dstPath, format, toStdout) {
if (! fs.existsSync(dstPath)) {
makePath(dstPath)
}
fs.readFile(srcPath, 'utf8', function(err, data) {
if (err) throw err
var cwd = process.cwd()
var smapDstPath = dstPath + '.map'
var smapSrcPath = path.relative(
path.dirname(
path.join(cwd, dstPath)),
path.join(cwd, srcPath))
var result = ram.compile(data, {
filename : srcPath,
format : format,
sourceMap: !toStdout,
sourceMapCfg: {
source: smapSrcPath,
sourceContent: data
}
})
if (toStdout) {
process.stdout.write(result.js + '\n')
return
}
if (result.js) {
result.js = result.js + '\n//# sourceMappingURL=' + path.basename(dstPath) + '.map'
fs.writeFile(dstPath, result.js, 'utf8', function(err) {
if (err) throw err
})
}
if (result.sourceMap) {
fs.writeFile(smapDstPath, result.sourceMap, 'utf8', function(err) {
if (err) throw err
})
}
})
}
|
javascript
|
{
"resource": ""
}
|
q59629
|
makePath
|
validation
|
function makePath(dirPath) {
dirPath = path.dirname(dirPath).split(path.sep)
dirPath.reduce(function(dirPath, p) {
dirPath = path.join(dirPath, p)
if (! fs.existsSync(dirPath)) {
try {
fs.mkdirSync(dirPath)
} catch (e) {
throw 'Could not make path ' + dirPath
}
}
return dirPath
}, '')
}
|
javascript
|
{
"resource": ""
}
|
q59630
|
readFromStdin
|
validation
|
function readFromStdin(cb) {
var chunks = []
var stdin = process.stdin
stdin.resume()
stdin.setEncoding('utf8')
stdin.on('data', function (chunk) {
chunks.push(chunk)
})
stdin.on('end', function() {
cb(chunks.join(' '))
})
}
|
javascript
|
{
"resource": ""
}
|
q59631
|
isRIdent
|
validation
|
function isRIdent(node) {
return node &&
node.type &&
node.type === T.IDENT &&
node.content === 'R'
}
|
javascript
|
{
"resource": ""
}
|
q59632
|
srcToChunks
|
validation
|
function srcToChunks(src, opts, ctx) {
opts = opts || {}
var ast = parse(src, opts)
// check semantic
var errors = semantic.checkAst(ast, ctx)
// there is semantic errors?
if (errors) {
if (opts.printErrors !== false) {
errors.forEach(function(e){
console.error(e)
})
}
return
// everything ok
} else {
return compiler.astToChunks(ast, ctx, opts.format)
}
}
|
javascript
|
{
"resource": ""
}
|
q59633
|
chunksToSourceMap
|
validation
|
function chunksToSourceMap(chunks, cfg) {
var loc
var outLine = 0
var outColumn = 0
var smap = sourcemap.newSourceMap()
var acc = ''
chunks.forEach(function(chunk) {
if (chunk.content === '\n') {
outLine = outLine + 1
outColumn = 0
}
loc = chunk.loc
if (loc) {
smap.add(
// jison line tracking is 1 based,
// source maps reads it as 0 based
loc.firstLine - 1,
loc.firstColumn,
outLine,
outColumn
)
}
if (chunk.content !== '\n') {
outColumn = outColumn + chunk.content.length
}
})
return smap.generate(cfg)
}
|
javascript
|
{
"resource": ""
}
|
q59634
|
parse
|
validation
|
function parse(src, opts) {
var parser = new Parser()
parser.yy = {parseError: util.parseError, filename: opts.filename}
return parser.parse(src)
}
|
javascript
|
{
"resource": ""
}
|
q59635
|
writeCommonJSStub
|
validation
|
function writeCommonJSStub(ast, ctx) {
// Granular require for each Ramda function, for minimal bundle size
ctx.newLineTop()
Object.keys(ctx.usedRamdaFns).forEach(function(key) {
ctx.newLineTop()
ctx.writeTop('var ' + key + ' = require(\'ramda/src/' + key + '\')')
})
ctx.newLine()
ctx.newLine()
if (ast.exportedDefault) {
ctx.write('module.exports = ' + ast.exportedDefault)
} else {
ast.exportedVars.forEach(function(name, idx, arr){
ctx.write('exports.' + name + ' = ' + name)
if (idx < arr.length - 1) {
ctx.newLine()
}
})
}
}
|
javascript
|
{
"resource": ""
}
|
q59636
|
writeIIFEStub
|
validation
|
function writeIIFEStub(ctx) {
writeRamdaFunctionAsGlobalStub(ctx)
ctx.writeTop(';(function () {')
ctx.newLine()
ctx.newLine()
ctx.write('})()')
}
|
javascript
|
{
"resource": ""
}
|
q59637
|
writeRamdaFunctionAsGlobalStub
|
validation
|
function writeRamdaFunctionAsGlobalStub(ctx) {
ctx.newLineTop()
ctx.newLineTop()
Object.keys(ctx.usedRamdaFns).forEach(function(key) {
ctx.newLineTop()
ctx.writeTop('var ' + key + ' = R.' + key)
})
}
|
javascript
|
{
"resource": ""
}
|
q59638
|
validation
|
function(hdr) {
//The content of this header doesn’t affect us
//since all it does is tell us details of how
//the sender will ZDLE-encode binary data. Our
//ZDLE parser doesn’t need to know in advance.
sess._next_subpacket_handler = function(spkt) {
sess._next_subpacket_handler = null;
sess._consume_ZSINIT_data(spkt);
sess._send_header('ZACK');
sess._next_header_handler = between_files_handler;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q59639
|
send_files
|
validation
|
function send_files(session, files, options) {
if (!options) options = {};
//Populate the batch in reverse order to simplify sending
//the remaining files/bytes components.
var batch = [];
var total_size = 0;
for (var f=files.length - 1; f>=0; f--) {
var fobj = files[f];
total_size += fobj.size;
batch[f] = {
obj: fobj,
name: fobj.name,
size: fobj.size,
mtime: new Date(fobj.lastModified),
files_remaining: files.length - f,
bytes_remaining: total_size,
};
}
var file_idx = 0;
function promise_callback() {
var cur_b = batch[file_idx];
if (!cur_b) {
return Promise.resolve(); //batch done!
}
file_idx++;
return session.send_offer(cur_b).then( function after_send_offer(xfer) {
if (options.on_offer_response) {
options.on_offer_response(cur_b.obj, xfer);
}
if (xfer === undefined) {
return promise_callback(); //skipped
}
return new Promise( function(res) {
var reader = new FileReader();
//This really shouldn’t happen … so let’s
//blow up if it does.
reader.onerror = function reader_onerror(e) {
console.error("file read error", e);
throw("File read error: " + e);
};
var piece;
reader.onprogress = function reader_onprogress(e) {
//Some browsers (e.g., Chrome) give partial returns,
//while others (e.g., Firefox) don’t.
if (e.target.result) {
piece = new Uint8Array(e.target.result, xfer.get_offset())
_check_aborted(session);
xfer.send(piece);
if (options.on_progress) {
options.on_progress(cur_b.obj, xfer, piece);
}
}
};
reader.onload = function reader_onload(e) {
piece = new Uint8Array(e.target.result, xfer, piece)
_check_aborted(session);
xfer.end(piece).then( function() {
if (options.on_progress && piece.length) {
options.on_progress(cur_b.obj, xfer, piece);
}
if (options.on_file_complete) {
options.on_file_complete(cur_b.obj, xfer);
}
//Resolve the current file-send promise with
//another promise. That promise resolves immediately
//if we’re done, or with another file-send promise
//if there’s more to send.
res( promise_callback() );
} );
};
reader.readAsArrayBuffer(cur_b.obj);
} );
} );
}
return promise_callback();
}
|
javascript
|
{
"resource": ""
}
|
q59640
|
strip_ignored_bytes
|
validation
|
function strip_ignored_bytes(octets) {
for (var o=octets.length-1; o>=0; o--) {
switch (octets[o]) {
case XON:
case XON_HIGH:
case XOFF:
case XOFF_HIGH:
octets.splice(o, 1);
continue;
}
}
return octets;
}
|
javascript
|
{
"resource": ""
}
|
q59641
|
find_subarray
|
validation
|
function find_subarray(haystack, needle) {
var h=0, n;
var start = Date.now();
HAYSTACK:
while (h !== -1) {
h = haystack.indexOf( needle[0], h );
if (h === -1) break HAYSTACK;
for (n=1; n<needle.length; n++) {
if (haystack[h + n] !== needle[n]) {
h++;
continue HAYSTACK;
}
}
return h;
}
return -1;
}
|
javascript
|
{
"resource": ""
}
|
q59642
|
registerAction
|
validation
|
function registerAction(resource) {
return client.sendCommand({
id: Lime.Guid(),
method: Lime.CommandMethod.SET,
type: 'application/vnd.iris.eventTrack+json',
uri: '/event-track',
resource: resource
})
.catch(e => console.log(e));
}
|
javascript
|
{
"resource": ""
}
|
q59643
|
parse_status_block
|
validation
|
function parse_status_block(block) {
var match;
var parsed = {};
if ((match = block.match(/bssid=([A-Fa-f0-9:]{17})/))) {
parsed.bssid = match[1].toLowerCase();
}
if ((match = block.match(/freq=([0-9]+)/))) {
parsed.frequency = parseInt(match[1], 10);
}
if ((match = block.match(/mode=([^\s]+)/))) {
parsed.mode = match[1];
}
if ((match = block.match(/key_mgmt=([^\s]+)/))) {
parsed.key_mgmt = match[1].toLowerCase();
}
if ((match = block.match(/[^b]ssid=([^\n]+)/))) {
parsed.ssid = match[1];
}
if ((match = block.match(/[^b]pairwise_cipher=([^\n]+)/))) {
parsed.pairwise_cipher = match[1];
}
if ((match = block.match(/[^b]group_cipher=([^\n]+)/))) {
parsed.group_cipher = match[1];
}
if ((match = block.match(/p2p_device_address=([A-Fa-f0-9:]{17})/))) {
parsed.p2p_device_address = match[1];
}
if ((match = block.match(/wpa_state=([^\s]+)/))) {
parsed.wpa_state = match[1];
}
if ((match = block.match(/ip_address=([^\n]+)/))) {
parsed.ip = match[1];
}
if ((match = block.match(/[^_]address=([A-Fa-f0-9:]{17})/))) {
parsed.mac = match[1].toLowerCase();
}
if ((match = block.match(/uuid=([^\n]+)/))) {
parsed.uuid = match[1];
}
if ((match = block.match(/[^s]id=([0-9]+)/))) {
parsed.id = parseInt(match[1], 10);
}
return parsed;
}
|
javascript
|
{
"resource": ""
}
|
q59644
|
parse_command_interface
|
validation
|
function parse_command_interface(callback) {
return function(error, stdout, stderr) {
if (error) {
callback(error);
} else {
var output = parse_command_block(stdout.trim());
if (output.result === 'FAIL') {
callback(new Error(output.result));
} else {
callback(error, parse_command_block(stdout.trim()));
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
q59645
|
parse_scan_results
|
validation
|
function parse_scan_results(block) {
var match;
var results = [];
var lines;
lines = block.split('\n').map(function(item) { return item + "\n"; });
lines.forEach(function(entry){
var parsed = {};
if ((match = entry.match(/([A-Fa-f0-9:]{17})\t/))) {
parsed.bssid = match[1].toLowerCase();
}
if ((match = entry.match(/\t([\d]+)\t+/))) {
parsed.frequency = parseInt(match[1], 10);
}
if ((match = entry.match(/([-][0-9]+)\t/))) {
parsed.signalLevel = parseInt(match[1], 10);
}
if ((match = entry.match(/\t(\[.+\])\t/))) {
parsed.flags = match[1];
}
if ((match = entry.match(/\t([^\t]{1,32}(?=\n))/))) {
parsed.ssid = match[1];
}
if(!(Object.keys(parsed).length === 0 && parsed.constructor === Object)){
results.push(parsed);
}
});
return results;
}
|
javascript
|
{
"resource": ""
}
|
q59646
|
parse_scan_results_interface
|
validation
|
function parse_scan_results_interface(callback) {
return function(error, stdout, stderr) {
if (error) {
callback(error);
} else {
callback(error, parse_scan_results(stdout.trim()));
}
};
}
|
javascript
|
{
"resource": ""
}
|
q59647
|
parse_status_block
|
validation
|
function parse_status_block(block) {
var match;
var parsed = {
interface: block.match(/^([^\s]+)/)[1]
};
if ((match = block.match(/Link encap:\s*([^\s]+)/))) {
parsed.link = match[1].toLowerCase();
}
if ((match = block.match(/HWaddr\s+([^\s]+)/))) {
parsed.address = match[1].toLowerCase();
}
if ((match = block.match(/inet6\s+addr:\s*([^\s]+)/))) {
parsed.ipv6_address = match[1];
}
if ((match = block.match(/inet\s+addr:\s*([^\s]+)/))) {
parsed.ipv4_address = match[1];
}
if ((match = block.match(/Bcast:\s*([^\s]+)/))) {
parsed.ipv4_broadcast = match[1];
}
if ((match = block.match(/Mask:\s*([^\s]+)/))) {
parsed.ipv4_subnet_mask = match[1];
}
if ((match = block.match(/UP/))) {
parsed.up = true;
}
if ((match = block.match(/BROADCAST/))) {
parsed.broadcast = true;
}
if ((match = block.match(/RUNNING/))) {
parsed.running = true;
}
if ((match = block.match(/MULTICAST/))) {
parsed.multicast = true;
}
if ((match = block.match(/LOOPBACK/))) {
parsed.loopback = true;
}
return parsed;
}
|
javascript
|
{
"resource": ""
}
|
q59648
|
parse_status
|
validation
|
function parse_status(callback) {
return function(error, stdout, stderr) {
if (error) callback(error);
else callback(error,
stdout.trim().split('\n\n').map(parse_status_block));
};
}
|
javascript
|
{
"resource": ""
}
|
q59649
|
expand_r
|
validation
|
function expand_r(options, lines, prefix) {
Object.getOwnPropertyNames(options).forEach(function(key) {
var full = prefix.concat(key);
var value = options[key];
if (Array.isArray(value)) {
value.forEach(function(val) {
lines.push(full.concat(val).join(' '));
});
}
else if (typeof(value) == 'object') {
expand_r(value, lines, full);
}
else {
lines.push(full.concat(value).join(' '));
}
});
}
|
javascript
|
{
"resource": ""
}
|
q59650
|
parse_status_block
|
validation
|
function parse_status_block(block) {
var match;
// Skip out of the block is invalid
if (!block) return;
var parsed = {
interface: block.match(/^([^\s]+)/)[1]
};
if ((match = block.match(/Access Point:\s*([A-Fa-f0-9:]{17})/))) {
parsed.access_point = match[1].toLowerCase();
}
if ((match = block.match(/Frequency[:|=]\s*([0-9\.]+)/))) {
parsed.frequency = parseFloat(match[1]);
}
if ((match = block.match(/IEEE\s*([^\s]+)/))) {
parsed.ieee = match[1].toLowerCase();
}
if ((match = block.match(/Mode[:|=]\s*([^\s]+)/))) {
parsed.mode = match[1].toLowerCase();
}
if ((match = block.match(/Noise level[:|=]\s*(-?[0-9]+)/))) {
parsed.noise = parseInt(match[1], 10);
}
if ((match = block.match(/Link Quality[:|=]\s*([0-9]+)/))) {
parsed.quality = parseInt(match[1], 10);
}
if ((match = block.match(/Sensitivity[:|=]\s*([0-9]+)/))) {
parsed.sensitivity = parseInt(match[1], 10);
}
if ((match = block.match(/Signal level[:|=]\s*(-?[0-9]+)/))) {
parsed.signal = parseInt(match[1], 10);
}
if ((match = block.match(/ESSID[:|=]\s*"([^"]+)"/))) {
parsed.ssid = match[1];
}
if ((match = block.match(/unassociated/))) {
parsed.unassociated = true;
}
return parsed;
}
|
javascript
|
{
"resource": ""
}
|
q59651
|
parse_scan
|
validation
|
function parse_scan(show_hidden, callback) {
return function(error, stdout, stderr) {
if (error) callback(error);
else
if (show_hidden) {
callback(error, stdout
.split(/Cell [0-9]+ -/)
.map(parse_cell)
.filter(has_keys)
.sort(by_signal));
} else {
callback(error, stdout
.split(/Cell [0-9]+ -/)
.map(parse_cell)
.filter(has_ssid)
.sort(by_signal));
}
};
}
|
javascript
|
{
"resource": ""
}
|
q59652
|
createItemContent
|
validation
|
function createItemContent(cfg, item) {
var data = item.children || cfg.data;
var frag = document.createDocumentFragment();
var label = _.el('span');
var iconPrepend = _.el('i');
var iconAppend = _.el('i');
var prependClasses = ['fa'];
var appendClasses = ['fa'];
// prepended icon
if (data) {
prependClasses.push('fa-folder');
} else if (item.type === 'github-url') {
prependClasses.push('fa-github');
} else {
prependClasses.push('fa-file-o');
}
_.addClass(iconPrepend, prependClasses);
// text label
_.append(label, [iconPrepend, _.text(item.label)]);
frag.appendChild(label);
// appended icon
if (data) {
appendClasses.push('fa-caret-right');
} else if ('url' in item) {
appendClasses.push('fa-external-link');
}
_.addClass(iconAppend, appendClasses);
frag.appendChild(iconAppend);
return frag;
}
|
javascript
|
{
"resource": ""
}
|
q59653
|
closest
|
validation
|
function closest(element, test) {
var el = element;
while (el) {
if (test(el)) {
return el;
}
el = el.parentNode;
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q59654
|
addClass
|
validation
|
function addClass(element, className) {
var classNames = className;
function _addClass(el, cn) {
if (!el.className) {
el.className = cn;
} else if (!hasClass(el, cn)) {
if (el.classList) {
el.classList.add(cn);
} else {
el.className += ' ' + cn;
}
}
}
if (!isArray(className)) {
classNames = className.trim().split(/\s+/);
}
classNames.forEach(_addClass.bind(null, element));
return element;
}
|
javascript
|
{
"resource": ""
}
|
q59655
|
removeClass
|
validation
|
function removeClass(element, className) {
var classNames = className;
function _removeClass(el, cn) {
var classRegex;
if (el.classList) {
el.classList.remove(cn);
} else {
classRegex = new RegExp('(?:^|\\s)' + cn + '(?!\\S)', 'g');
el.className = el.className.replace(classRegex, '').trim();
}
}
if (!isArray(className)) {
classNames = className.trim().split(/\s+/);
}
classNames.forEach(_removeClass.bind(null, element));
return element;
}
|
javascript
|
{
"resource": ""
}
|
q59656
|
hasClass
|
validation
|
function hasClass(element, className) {
if (!element || !('className' in element)) {
return false;
}
return element.className.split(/\s+/).indexOf(className) !== -1;
}
|
javascript
|
{
"resource": ""
}
|
q59657
|
nextSiblings
|
validation
|
function nextSiblings(element) {
var next = element.nextSibling;
var siblings = [];
while (next) {
siblings.push(next);
next = next.nextSibling;
}
return siblings;
}
|
javascript
|
{
"resource": ""
}
|
q59658
|
previousSiblings
|
validation
|
function previousSiblings(element) {
var prev = element.previousSibling;
var siblings = [];
while (prev) {
siblings.push(prev);
prev = prev.previousSibling;
}
return siblings;
}
|
javascript
|
{
"resource": ""
}
|
q59659
|
uniqueCountryData
|
validation
|
function uniqueCountryData(data, type, parent) {
var hash = data.reduce(function each(prev, curr) {
if (!(curr[type] in prev)) {
if (parent) {
if (parent.label === curr[parent.type]) {
prev[curr[type]] = curr;
}
} else if (curr[type]) {
prev[curr[type]] = curr;
}
}
return prev;
}, {});
return Object.keys(hash).map(function each(item) {
return extend(hash[item], {
label: item,
type: type === 'name' ? 'country' : type
});
});
}
|
javascript
|
{
"resource": ""
}
|
q59660
|
validation
|
function (el) {
var className = el.className
var listClass = className.split(' ')
this.classList = listClass
this.el = el
}
|
javascript
|
{
"resource": ""
}
|
|
q59661
|
validation
|
function (el) {
this.el = el
if(typeof el.classList !== 'undefined') {
// if classList support
this.old = false
} else {
// browser class unsupport classList
this.classList = new nativeClasList(el)
this.old = true
}
}
|
javascript
|
{
"resource": ""
}
|
|
q59662
|
validation
|
function (obj, src) {
var result = false
var key
for (key in obj) {
if (obj.hasOwnProperty(key) && key === src) result = true
}
return result
}
|
javascript
|
{
"resource": ""
}
|
|
q59663
|
validation
|
function (v) {
var result = 0
var key
for (key in v) {
v.hasOwnProperty(key) && result++
}
return result
}
|
javascript
|
{
"resource": ""
}
|
|
q59664
|
validation
|
function (el, check) {
var cls = el.classList
var size = cls.length
var result = false
var i = 0
for (i; i < size; i++) {
if (cls[i].toString() === check) result = true
}
return result
}
|
javascript
|
{
"resource": ""
}
|
|
q59665
|
validation
|
function () {
var self = this;
console.log('starting capture...');
var req = get_req();
req.onreadystatechange = function start_capture_response () {
if (req.readyState === 4) {
if (req.status == 200) {
console.log('started.');
jQuery("#start").hide();
jQuery("#stop").show();
htracr.ui.pulse_logo();
} else {
var error = eval("(" + req.responseText + ")");
alert("Sorry, I can't start the sniffer; it says \"" +
error.message + "\"."
);
console.log("start problem: " + error);
}
}
};
req.open("POST", "/start", true);
req.send("");
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q59666
|
validation
|
function () {
var self = this;
console.log('stopping capture...');
var req = get_req();
req.onreadystatechange = function stop_capture_response () {
if (req.readyState === 4) {
self.update_state();
console.log('stopped.');
jQuery("#stop").hide();
jQuery("#start").show();
htracr.ui.unpulse_logo(true);
}
};
req.open("POST", "/stop", true);
req.send("");
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q59667
|
validation
|
function () {
var self = this;
console.log('updating...');
var req = get_req();
req.onreadystatechange = function update_state_response () {
if (req.readyState === 4) {
if (req.status === 200) {
var capture = JSON.parse(req.responseText);
if (capture.error) {
alert(capture.error.message);
}
htracr.ui.update(capture);
console.log('updated.');
} else {
console.log('no updates.');
}
}
};
req.open("GET", "/conns", true);
req.send("");
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q59668
|
validation
|
function () {
var self = this;
console.log('clearing...');
var req = get_req();
req.onreadystatechange = function clear_state_response () {
if (req.readyState === 4) {
htracr.ui.clear();
}
};
req.open("POST", "/clear", true);
req.send("");
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q59669
|
get_req
|
validation
|
function get_req () {
var self = this;
var req;
if (window.XMLHttpRequest) {
try {
req = new XMLHttpRequest();
} catch(e1) {
req = false;
}
} else if (window.ActiveXObject) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e2) {
req = false;
}
}
return req;
}
|
javascript
|
{
"resource": ""
}
|
q59670
|
validation
|
function (capture) {
var self = this;
self.clear();
self.capture = capture;
self.capture_idx = index_capture(capture);
self.render();
}
|
javascript
|
{
"resource": ""
}
|
|
q59671
|
validation
|
function () {
var self = this;
self.clear_ui();
self.resize();
self.draw_scale();
self.capture_idx.servers.forEach(function (bundle) {
var server_name = bundle[0];
var conn_ids = bundle[1];
var i;
self.y += self.server_pad;
self.draw_server_label(server_name);
self.y += self.server_pad;
conn_ids.forEach(function (conn_id) {
var conn = self.capture.sessions[server_name][conn_id];
htracr.connection(conn).draw(
di, [server_name, conn_id, undefined, 0]);
i = 0;
conn.http_reqs.forEach(function (http_req) {
var msg = htracr.http_msg(http_req);
msg.kind = "req";
msg.draw(di, [server_name, conn_id, 'http_reqs', i]);
i += 1;
});
i = 0;
conn.http_ress.forEach(function (http_req) {
var msg = htracr.http_msg(http_req);
msg.kind = "res";
msg.draw(di, [server_name, conn_id, 'http_ress', i]);
i += 1;
});
i = 0;
conn.packets.forEach(function (packet) {
var pkt = htracr.packet(packet);
pkt.draw(di, [server_name, conn_id, 'packets', i]);
i += 1;
});
self.y += self.conn_pad;
});
self.draw_referers();
self.draw_locations();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q59672
|
validation
|
function() {
var self = this;
var idx = self.capture_idx;
self.w = (
(idx.end - idx.start) / 1000 * self.pix_per_sec) +
margin[1] + margin[3];
self.h = margin[0] + margin[2];
for (var s in idx.servers) {
self.h += (self.server_pad * 2);
self.h += ((idx.servers[s][1].length) * self.conn_pad);
}
console.log("resizing to " + self.w + " x " + self.h);
paper.setSize(self.w, self.h);
labels.setSize(self.label_w, self.h);
}
|
javascript
|
{
"resource": ""
}
|
|
q59673
|
validation
|
function () {
var self = this;
var start_x = time_x(self.capture_idx.start);
var end_x = time_x(self.capture_idx.end);
var end_y = self.h - margin[2];
var end_attrs = {
stroke: "#666",
"stroke-width": "1"
};
var label_attrs = {
fill: "white",
"font-size": "16",
"opacity": ".5"
};
paper.path(
"M" + start_x + "," + margin[0] + " " +
"L" + start_x + "," + end_y).attr(end_attrs);
var m;
if (self.pix_per_sec <= 1000) {
m = 1000;
} else if (self.pix_per_sec <= 2000) {
m = 500;
} else if (self.pix_per_sec <= 3500) {
m = 250;
} else if (self.pix_per_sec <= 5000) {
m = 100;
} else {
m = 50;
}
for (var i = self.capture_idx.start; i < self.capture_idx.end; i += m) {
var i_x = time_x(i);
paper.path(
"M" + i_x + "," + margin[0] + " " +
"L" + i_x + "," + end_y
).attr({
stroke: "#444",
"stroke-width": "1"
});
paper.text(i_x, end_y + 10,
((i - self.capture_idx.start) / 1000) + "s").attr(label_attrs);
paper.text(i_x, margin[0] - 20,
((i - self.capture_idx.start) / 1000) + "s").attr(label_attrs);
}
paper.path(
"M" + end_x + "," + margin[0] + " " +
"L" + end_x + "," + end_y
).attr(end_attrs);
}
|
javascript
|
{
"resource": ""
}
|
|
q59674
|
validation
|
function (val) {
var self = this;
console.log("zooming to " + val + "...");
self.pix_per_sec = val;
self.render();
}
|
javascript
|
{
"resource": ""
}
|
|
q59675
|
validation
|
function (start, end, y_adj, attrs) {
var start_x = time_x(start) || margin[3];
var end_x = time_x(end) || ui.w - margin[1];
var y = ui.y + y_adj;
var e = paper.path(
"M" + start_x + "," + y + " " +
"L" + end_x + "," + y
).attr(attrs || {});
return e;
}
|
javascript
|
{
"resource": ""
}
|
|
q59676
|
validation
|
function (when, len, attrs) {
var x = time_x(when);
var end_y = ui.y + len;
var e = paper.path(
"M" + x + "," + ui.y + " " +
"L" + x + "," + end_y
).attr(attrs || {});
return e;
}
|
javascript
|
{
"resource": ""
}
|
|
q59677
|
validation
|
function (name, value, cursor, single) {
if (value) {
if (! htracr.ui.urls[name]) {
ui.urls[name] = {};
}
if (single === true) {
ui.urls[name][value] = cursor;
} else {
if (! ui.urls[name][value]) {
ui.urls[name][value] = [];
}
ui.urls[name][value].push(cursor);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q59678
|
time_x
|
validation
|
function time_x (t) {
var self = this;
if (t === null) {
return null;
}
var delta = t - ui.capture_idx.start;
if (delta < 0) {
console.log('Negative delta for time ' + t);
}
var pix = delta * ui.pix_per_sec / 1000;
var x = margin[3] + pix;
return x;
}
|
javascript
|
{
"resource": ""
}
|
q59679
|
wmic
|
validation
|
function wmic(callback) {
var args = ['PROCESS', 'get', 'ParentProcessId,ProcessId'];
var options = {windowsHide: true, windowsVerbatimArguments: true};
bin('wmic', args, options, function(err, stdout, code) {
if (err) {
callback(err);
return;
}
if (code !== 0) {
callback(new Error('pidtree wmic command exited with code ' + code));
return;
}
// Example of stdout
//
// ParentProcessId ProcessId
// 0 777
try {
stdout = stdout.split(os.EOL);
var list = [];
for (var i = 1; i < stdout.length; i++) {
stdout[i] = stdout[i].trim();
if (!stdout[i]) continue;
stdout[i] = stdout[i].split(/\s+/);
stdout[i][0] = parseInt(stdout[i][0], 10); // PPID
stdout[i][1] = parseInt(stdout[i][1], 10); // PID
list.push(stdout[i]);
}
callback(null, list);
} catch (error) {
callback(error);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q59680
|
list
|
validation
|
function list(PID, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
if (typeof options !== 'object') {
options = {};
}
PID = parseInt(PID, 10);
if (isNaN(PID) || PID < -1) {
callback(new TypeError('The pid provided is invalid'));
return;
}
getAll(function(err, list) {
if (err) {
callback(err);
return;
}
// If the user wants the whole list just return it
if (PID === -1) {
for (var i = 0; i < list.length; i++) {
list[i] = options.advanced
? {ppid: list[i][0], pid: list[i][1]}
: (list[i] = list[i][1]);
}
callback(null, list);
return;
}
var root;
for (var l = 0; l < list.length; l++) {
if (list[l][1] === PID) {
root = options.advanced ? {ppid: list[l][0], pid: PID} : PID;
break;
}
if (list[l][0] === PID) {
root = options.advanced ? {pid: PID} : PID; // Special pids like 0 on *nix
}
}
if (!root) {
callback(new Error('No maching pid found'));
return;
}
// Build the adiacency Hash Map (pid -> [children of pid])
var tree = {};
while (list.length > 0) {
var e = list.pop();
if (tree[e[0]]) {
tree[e[0]].push(e[1]);
} else {
tree[e[0]] = [e[1]];
}
}
// Starting by the PID provided by the user, traverse the tree using the
// adiacency Hash Map until the whole subtree is visited.
// Each pid encountered while visiting is added to the pids array.
var idx = 0;
var pids = [root];
while (idx < pids.length) {
var curpid = options.advanced ? pids[idx++].pid : pids[idx++];
if (!tree[curpid]) continue;
var len = tree[curpid].length;
for (var j = 0; j < len; j++) {
pids.push(
options.advanced
? {ppid: curpid, pid: tree[curpid][j]}
: tree[curpid][j]
);
}
delete tree[curpid];
}
if (!options.root) {
pids.shift(); // Remove root
}
callback(null, pids);
});
}
|
javascript
|
{
"resource": ""
}
|
q59681
|
list
|
validation
|
function list(pid, options, callback) {
if (typeof options === 'function') {
callback = options;
options = undefined;
}
if (typeof callback === 'function') {
pidtree(pid, options, callback);
return;
}
return pify(pidtree, pid, options);
}
|
javascript
|
{
"resource": ""
}
|
q59682
|
get
|
validation
|
function get(callback) {
if (file === undefined) {
callback(
new Error(
os.platform() +
' is not supported yet, please open an issue (https://github.com/simonepri/pidtree)'
)
);
}
var list = require('./' + file);
list(callback);
}
|
javascript
|
{
"resource": ""
}
|
q59683
|
run
|
validation
|
function run(cmd, args, options, done) {
if (typeof options === 'function') {
done = options;
options = undefined;
}
var executed = false;
var ch = spawn(cmd, args, options);
var stdout = '';
var stderr = '';
ch.stdout.on('data', function(d) {
stdout += d.toString();
});
ch.stderr.on('data', function(d) {
stderr += d.toString();
});
ch.on('error', function(err) {
if (executed) return;
executed = true;
done(new Error(err));
});
ch.on('close', function(code) {
if (executed) return;
executed = true;
if (stderr) {
return done(new Error(stderr));
}
done(null, stdout, code);
});
}
|
javascript
|
{
"resource": ""
}
|
q59684
|
ps
|
validation
|
function ps(callback) {
var args = ['-A', '-o', 'ppid,pid'];
bin('ps', args, function(err, stdout, code) {
if (err) return callback(err);
if (code !== 0) {
return callback(new Error('pidtree ps command exited with code ' + code));
}
// Example of stdout
//
// PPID PID
// 1 430
// 430 432
// 1 727
// 1 7166
try {
stdout = stdout.split(os.EOL);
var list = [];
for (var i = 1; i < stdout.length; i++) {
stdout[i] = stdout[i].trim();
if (!stdout[i]) continue;
stdout[i] = stdout[i].split(/\s+/);
stdout[i][0] = parseInt(stdout[i][0], 10); // PPID
stdout[i][1] = parseInt(stdout[i][1], 10); // PID
list.push(stdout[i]);
}
callback(null, list);
} catch (error) {
callback(error);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q59685
|
bootstrap
|
validation
|
function bootstrap () {
var server = RPC.apply(null, arguments)
var io = server.io
var allQueries = []
Object.keys(models).forEach(function (modelName) {
var model = models[modelName]
model._exposeCallback(server)
})
io.use(function (socket, next) {
const registeredLQs = {}
socket.moonridge = {
registeredLQs: registeredLQs,
user: {privilege_level: 0}
} // default privilege level for any connected client
socket.on('disconnect', function () {
// clearing out liveQueries listeners
debug(socket.id, ' socket disconnected, cleaning up LQ listeners')
for (var LQId in registeredLQs) {
var LQ = registeredLQs[LQId]
LQ.removeListener(socket)
}
})
next()
})
server.expose({
MR: {
getModels: function () {
return Object.keys(models)
},
deAuthorize: function () {
this.moonridge.user = {privilege_level: 0} // for logging users out
}
}
})
if (process.env.MOONRIDGE_HEALTH === '1') {
// this reveals any data that you use in queries to the public, so it should not be used in production when dealing with sensitive data
server.expose({
MR: {
getHealth: function () {
var allModels = {}
var index = allQueries.length
while (index--) {
var modelQueriesForSerialization = {}
var model = allQueries[index]
for (var LQ in model.queries) {
modelQueriesForSerialization[LQ] = Object.keys(model.queries[LQ].listeners).length
}
allModels[model.modelName] = modelQueriesForSerialization
}
return {
pid: process.pid,
memory: process.memoryUsage(),
uptime: process.uptime(), // in seconds
liveQueries: allModels // key is LQ.clientQuery and value is number of listening clients
}
}
}
})
}
return server
}
|
javascript
|
{
"resource": ""
}
|
q59686
|
validation
|
function (socket) {
if (this.listeners[socket.id]) {
delete this.listeners[socket.id]
if (Object.keys(this.listeners).length === 0) {
this.destroy() // this will delete a liveQuery from liveQueries
}
} else {
return new Error('no listener present on LQ ' + this.qKey)
}
}
|
javascript
|
{
"resource": ""
}
|
|
q59687
|
modelInstance
|
validation
|
function modelInstance(data){
var self = this;
// Add any user supplied schema instance methods.
if(schema){
_.assign(self, schema.methods);
}
Model.call(self, data);
}
|
javascript
|
{
"resource": ""
}
|
q59688
|
validation
|
function(assemble, next) {
grunt.verbose.writeln('Validating options');
if (utils.endsWithDot(assemble.options.ext)) {
grunt.warn('Invalid ext "' + assemble.options.ext + '". ext cannot end with a period.');
done(false);
}
// find an engine to use
assemble.options.engine = assemble.options.engine || 'handlebars';
grunt.verbose.ok('>> Current engine:'.yellow, assemble.options.engine);
assemble.engine.load(assemble.options.engine);
var initializeEngine = function(engine, options) { engine.init(options, { grunt: grunt, assemble: assemble }); };
assemble.options.initializeEngine = assemble.options.initializeEngine || initializeEngine;
var registerFunctions = function(engine) { engine.registerFunctions(); };
assemble.options.registerFunctions = assemble.options.registerFunctions || registerFunctions;
var registerPartial = function(engine, filename, content) { engine.registerPartial(filename, content); };
assemble.options.registerPartial = assemble.options.registerPartial || registerPartial;
assemble.partials = file.expand(assemble.options.partials);
if (_.isArray(assemble.options.dataFiles) && assemble.options.dataFiles.length > 0) {
assemble.dataFiles = file.expand(assemble.options.dataFiles);
//assemble.options.data = {};
}
// Expand layout into layoutFiles if a glob pattern is specified
if (assemble.options.layouts) {
assemble.layoutFiles = file.expand({filter: 'isFile'}, assemble.options.layouts);
}
if (assemble.layoutFiles && assemble.layoutFiles.length !== 0) {
grunt.verbose.writeln('Found layout files:'.yellow, assemble.layoutFiles);
} else {
assemble.layoutFiles = null;
}
assemble.options.initializeEngine(assemble.engine, assemble.options);
assemble.options.registerFunctions(assemble.engine);
next(assemble);
}
|
javascript
|
{
"resource": ""
}
|
|
q59689
|
validation
|
function(buildDone) {
// if there is a pages property, build the pages contained therein.
if (assemble.options.pages) {
_.forOwn(assemble.options.pages, function(fileInfo, filename) {
if (!filename || filename.length === 0) {
grunt.warn('Pages need a filename.');
buildDone();
return false;
}
if (!buildPage(filename, fileInfo)) {
buildDone();
return false;
}
});
}
buildDone();
}
|
javascript
|
{
"resource": ""
}
|
|
q59690
|
crossBrowser
|
validation
|
function crossBrowser(property, value, prefix) {
function ucase(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
var vendor = ['webkit', 'moz', 'ms', 'o'],
properties = {};
for (var i = 0; i < vendor.length; i++) {
if (prefix) {
value = value.replace(prefix, '-' + vendor[i] + '-' + prefix);
}
properties[ucase(vendor[i]) + ucase(property)] = value;
}
properties[property] = value;
return properties;
}
|
javascript
|
{
"resource": ""
}
|
q59691
|
validation
|
function (success, fail, args, env) {
var result = new PluginResult(args, env);
resultObjs[result.callbackId] = result;
args = JSON.parse(decodeURIComponent(args["input"]));
vibration.getInstance().vibration_request(result.callbackId, args);
result.noResult(true);
}
|
javascript
|
{
"resource": ""
}
|
|
q59692
|
validation
|
function (success, fail, args, env) {
var result = new PluginResult(args, env);
resultObjs[result.callbackId] = result;
readCallback = result.callbackId;
var views = qnx.webplatform.getWebViews();
var handle = null;
var group = null;
var z = -1;
for (var i = 0; i < views.length; i++) {
if (views[i].visible && views[i].zOrder > z){
z = views[i].zOrder;
group = views[i].windowGroup;
handle = views[i].jsScreenWindowHandle;
}
}
if (handle !== null) {
var values = { group: group, handle: handle };
result.ok(barcodescanner.getInstance().startRead(result.callbackId, values), true);
} else {
result.error("Failed to find window handle", false);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q59693
|
validation
|
function (success, fail, args, env) {
var result = new PluginResult(args, env);
result.ok(passwordCrypto.getInstance().ping(), false);
}
|
javascript
|
{
"resource": ""
}
|
|
q59694
|
validation
|
function(id) {
console.log('XXXX Received Event: ' + id);
$("#btnStartMonitor").prop('disabled', false);
$("#btnStopMonitor").prop('disabled', true);
btLeHandler.initialise();
}
|
javascript
|
{
"resource": ""
}
|
|
q59695
|
validation
|
function (success, fail, args, env) {
var result = new PluginResult(args, env);
args = JSON.parse(decodeURIComponent(args["input"]));
result.ok(gseCrypto.getInstance().hash(result.callbackId, args), false);
}
|
javascript
|
{
"resource": ""
}
|
|
q59696
|
validation
|
function (success, fail, args) {
args = JSON.parse(decodeURIComponent(args["input"]));
// look for the UIWebView in the set of WebViews.
var views = qnx.webplatform.getWebViews();
var handle = null;
var z = -1;
for (var i = 0; i < views.length; i++) {
if (views[i].visible && views[i].zOrder > z){
z = views[i].zOrder;
handle = views[i].jsScreenWindowHandle;
}
}
if (handle !== null) {
var values = { value: args, handle: handle };
success(preventsleep.getInstance().setPreventSleep(values));
} else {
success("Unable to get window handle");
}
}
|
javascript
|
{
"resource": ""
}
|
|
q59697
|
validation
|
function (success, fail, args, env) {
var result = new PluginResult(args, env);
result.ok(simpleBtSppPlugin.getInstance().initialiseBluetooth(), false);
}
|
javascript
|
{
"resource": ""
}
|
|
q59698
|
validation
|
function (success, fail, args) {
args = JSON.parse(decodeURIComponent(args["input"]));
vibration.getInstance().vibration_request(args);
success();
}
|
javascript
|
{
"resource": ""
}
|
|
q59699
|
validation
|
function (success, fail, args, env) {
var result = new PluginResult(args, env);
if (!initialiseBluetoothCallbackId) {
initialiseBluetoothCallbackId = result.callbackId;
resultObjs[result.callbackId] = result;
result.ok(simpleXpBeaconPlugin.getInstance().initialiseBluetooth(result.callbackId), true);
} else {
result.error("Initialise Bluetooth failure", false);
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.