_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q24000
|
OperationInfo
|
train
|
function OperationInfo(properties) {
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q24001
|
train
|
function (fn, time, context) {
var lock, args, wrapperFn, later;
later = function () {
// reset lock and call if queued
lock = false;
if (args) {
wrapperFn.apply(context, args);
args = false;
}
};
wrapperFn = function () {
if (lock) {
// called too soon, queue to call later
args = arguments;
} else {
// call and lock until later
fn.apply(context, arguments);
setTimeout(later, time);
lock = true;
}
};
return wrapperFn;
}
|
javascript
|
{
"resource": ""
}
|
|
q24002
|
processResult
|
train
|
function processResult(context, lang, langJson, stringXmlJson) {
var path = require('path');
var q = require('q');
var deferred = q.defer();
var mapObj = {};
// create a map to the actual string
_.forEach(stringXmlJson.resources.string, function (val) {
if (_.has(val, "$") && _.has(val["$"], "name")) {
mapObj[val["$"].name] = val;
}
});
var langJsonToProcess = _.assignIn(langJson.config_android, langJson.app, langJson.app_android);
//now iterate through langJsonToProcess
_.forEach(langJsonToProcess, function (val, key) {
// positional string format is in Mac OS X format. change to android format
val = val.replace(/\$@/gi, "$s");
val = val.replace(/\'/gi, "\\'");
if (_.has(mapObj, key)) {
// mapObj contains key. replace key
mapObj[key]["_"] = val;
} else {
// add by inserting
stringXmlJson.resources.string.push({
_: val,
'$': {name: key}
});
}
});
//save to disk
var langDir = getLocalizationDir(context, lang);
var filePath = getLocalStringXmlPath(context, lang);
fs.ensureDir(langDir, function (err) {
if (err) {
throw err;
}
fs.writeFile(filePath, buildXML(stringXmlJson), {encoding: 'utf8'}, function (err) {
if (err) throw err;
console.log('Saved:' + filePath);
return deferred.resolve();
});
});
function buildXML(obj) {
var builder = new xml2js.Builder();
builder.options.renderOpts.indent = '\t';
var x = builder.buildObject(obj);
return x.toString();
}
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
q24003
|
writeSeedBatch
|
train
|
function writeSeedBatch(dynamodbWriteFunction, tableName, seeds) {
const params = {
RequestItems: {
[tableName]: seeds.map((seed) => ({
PutRequest: {
Item: seed,
},
})),
},
};
return new BbPromise((resolve, reject) => {
// interval lets us know how much time we have burnt so far. This lets us have a backoff mechanism to try
// again a few times in case the Database resources are in the middle of provisioning.
let interval = 0;
function execute(interval) {
setTimeout(() => dynamodbWriteFunction(params, (err) => {
if (err) {
if (err.code === "ResourceNotFoundException" && interval <= 5000) {
execute(interval + 1000);
} else {
reject(err);
}
} else {
resolve();
}
}), interval);
}
execute(interval);
});
}
|
javascript
|
{
"resource": ""
}
|
q24004
|
writeSeeds
|
train
|
function writeSeeds(dynamodbWriteFunction, tableName, seeds) {
if (!dynamodbWriteFunction) {
throw new Error("dynamodbWriteFunction argument must be provided");
}
if (!tableName) {
throw new Error("table name argument must be provided");
}
if (!seeds) {
throw new Error("seeds argument must be provided");
}
if (seeds.length > 0) {
const seedChunks = _.chunk(seeds, MAX_MIGRATION_CHUNK);
return BbPromise.map(
seedChunks,
(chunk) => writeSeedBatch(dynamodbWriteFunction, tableName, chunk),
{ concurrency: MIGRATION_SEED_CONCURRENCY }
)
.then(() => console.log("Seed running complete for table: " + tableName));
}
}
|
javascript
|
{
"resource": ""
}
|
q24005
|
fileExists
|
train
|
function fileExists(fileName) {
return new BbPromise((resolve) => {
fs.exists(fileName, (exists) => resolve(exists));
});
}
|
javascript
|
{
"resource": ""
}
|
q24006
|
unmarshalBuffer
|
train
|
function unmarshalBuffer(json) {
_.forEach(json, function(value, key) {
// Null check to prevent creation of Buffer when value is null
if (value !== null && value.type==="Buffer") {
json[key]= new Buffer(value.data);
}
});
return json;
}
|
javascript
|
{
"resource": ""
}
|
q24007
|
getSeedsAtLocation
|
train
|
function getSeedsAtLocation(location) {
// load the file as JSON
const result = require(location);
// Ensure the output is an array
if (Array.isArray(result)) {
return _.forEach(result, unmarshalBuffer);
} else {
return [ unmarshalBuffer(result) ];
}
}
|
javascript
|
{
"resource": ""
}
|
q24008
|
locateSeeds
|
train
|
function locateSeeds(sources, cwd) {
sources = sources || [];
cwd = cwd || process.cwd();
const locations = sources.map((source) => path.join(cwd, source));
return BbPromise.map(locations, (location) => {
return fileExists(location).then((exists) => {
if(!exists) {
throw new Error("source file " + location + " does not exist");
}
return getSeedsAtLocation(location);
});
// Smash the arrays together
}).then((seedArrays) => [].concat.apply([], seedArrays));
}
|
javascript
|
{
"resource": ""
}
|
q24009
|
spawnNodeWithId
|
train
|
function spawnNodeWithId (factory, callback) {
waterfall([(cb) => factory.spawnNode(cb), identify], callback)
}
|
javascript
|
{
"resource": ""
}
|
q24010
|
spawnNodes
|
train
|
function spawnNodes (n, factory, callback) {
timesSeries(n, (_, cb) => factory.spawnNode(cb), callback)
}
|
javascript
|
{
"resource": ""
}
|
q24011
|
spawnNodesWithId
|
train
|
function spawnNodesWithId (n, factory, callback) {
spawnNodes(n, factory, (err, nodes) => {
if (err) return callback(err)
map(nodes, identify, callback)
})
}
|
javascript
|
{
"resource": ""
}
|
q24012
|
train
|
function (insertPath, level) {
var node = insertPath[level],
M = node.children.length,
m = this._minEntries;
this._chooseSplitAxis(node, m, M);
var splitIndex = this._chooseSplitIndex(node, m, M);
var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
newNode.height = node.height;
newNode.leaf = node.leaf;
calcBBox(node, this.toBBox);
calcBBox(newNode, this.toBBox);
if (level) insertPath[level - 1].children.push(newNode);
else this._splitRoot(node, newNode);
}
|
javascript
|
{
"resource": ""
}
|
|
q24013
|
train
|
function (node, m, M) {
var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
xMargin = this._allDistMargin(node, m, M, compareMinX),
yMargin = this._allDistMargin(node, m, M, compareMinY);
// if total distributions margin value is minimal for x, sort by minX,
// otherwise it's already sorted by minY
if (xMargin < yMargin) node.children.sort(compareMinX);
}
|
javascript
|
{
"resource": ""
}
|
|
q24014
|
train
|
function (node, m, M, compare) {
node.children.sort(compare);
var toBBox = this.toBBox,
leftBBox = distBBox(node, 0, m, toBBox),
rightBBox = distBBox(node, M - m, M, toBBox),
margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
i, child;
for (i = m; i < M - m; i++) {
child = node.children[i];
extend(leftBBox, node.leaf ? toBBox(child) : child);
margin += bboxMargin(leftBBox);
}
for (i = M - m - 1; i >= m; i--) {
child = node.children[i];
extend(rightBBox, node.leaf ? toBBox(child) : child);
margin += bboxMargin(rightBBox);
}
return margin;
}
|
javascript
|
{
"resource": ""
}
|
|
q24015
|
calcBBox
|
train
|
function calcBBox(node, toBBox) {
distBBox(node, 0, node.children.length, toBBox, node);
}
|
javascript
|
{
"resource": ""
}
|
q24016
|
distBBox
|
train
|
function distBBox(node, k, p, toBBox, destNode) {
if (!destNode) destNode = createNode(null);
destNode.minX = Infinity;
destNode.minY = Infinity;
destNode.maxX = -Infinity;
destNode.maxY = -Infinity;
for (var i = k, child; i < p; i++) {
child = node.children[i];
extend(destNode, node.leaf ? toBBox(child) : child);
}
return destNode;
}
|
javascript
|
{
"resource": ""
}
|
q24017
|
multiSelect
|
train
|
function multiSelect(arr, left, right, n, compare) {
var stack = [left, right],
mid;
while (stack.length) {
right = stack.pop();
left = stack.pop();
if (right - left <= n) continue;
mid = left + Math.ceil((right - left) / n / 2) * n;
quickselect(arr, mid, left, right, compare);
stack.push(left, mid, mid, right);
}
}
|
javascript
|
{
"resource": ""
}
|
q24018
|
jumpToState
|
train
|
function jumpToState () {
return ({ merged, nodeId, excludeTypes }) => {
state.focusedNodeId = nodeId
state.control.merged = merged
state.typeFilters.enableInlinable = !merged
state.key.enableOptUnopt = !merged
// Diff type exclude state to reach the one described by the entry
const oldExclude = state.typeFilters.exclude
const newExclude = new Set(excludeTypes)
oldExclude.forEach((name) => {
if (!newExclude.has(name)) {
flamegraph.typeShow(name)
}
})
newExclude.forEach((name) => {
if (!oldExclude.has(name)) {
flamegraph.typeHide(name)
}
})
state.typeFilters.exclude = newExclude
state.typeFilters.bgs = state.control.tiers
? highlightTypeFilters()
: state.typeFilters.unhighlighted
flamegraph.renderTree(merged ? state.trees.merged : state.trees.unmerged)
const { idsToNodes } = merged ? mergedTags : unmergedTags
flamegraph.zoom(idsToNodes.get(nodeId))
emit(state)
}
}
|
javascript
|
{
"resource": ""
}
|
q24019
|
tagNodesWithIds
|
train
|
function tagNodesWithIds (data) {
let id = 0
const idsToNodes = new Map()
const nodesToIds = new Map()
tagNodes(data)
return {
idsToNodes,
nodesToIds
}
function tag (node) {
idsToNodes.set(id, node)
nodesToIds.set(node, id)
id++
}
function tagNodes (node) {
tag(node)
if (node.children) node.children.forEach(tagNodes)
}
}
|
javascript
|
{
"resource": ""
}
|
q24020
|
fixLines
|
train
|
function fixLines (line) {
// Node 11+ are fine
if (nodeMajorV > 10) return line
// Work around a bug in Node 10's V8 --preprocess -j that breaks strings containing \\
if (nodeMajorV === 10) {
// Look for backslashes that aren't escaping a unicode character code, like \\u01a2
// Small risk of false positives e.g. is C:\\Users\\u2bfab\\ unicode, or a U2 fan?
// So, restrict to basic multilingual (4 char) only. No hieroglyphs or ancient Mayan.
const startPath = line.search(/\\(?!u[0-9A-Fa-f]{4})/)
if (startPath === -1) return line
// Replace any \\ that's not part of a unicode escape character
const replaceRegex = /\\(?!u[0-9A-Fa-f]{4})/g
// \u005c is the unicode escape for the \ char
return line.slice(0, startPath) + line.slice(startPath).replace(replaceRegex, '\\u005c')
}
if (nodeMajorV < 10) {
// In regexs, Node 8 (and 9) hard-escapes unicode and doubles \\ to \\\\
if (!line.match(/^code-creation,RegExp/)) return line
// Normal buffer decoding, String.normalize() etc doesn't work here, brute force needed
const escapedUnicode = line.match(/(\\u[0-9A-Fa-f]{4})+/g)
if (escapedUnicode) {
for (const match of escapedUnicode) {
line = line.replace(match, JSON.parse(`"${match}"`))
}
}
return line.replace(/\\\\/g, '\\')
}
}
|
javascript
|
{
"resource": ""
}
|
q24021
|
padNumbersToEqualLength
|
train
|
function padNumbersToEqualLength(arr) {
var maxLen = 0;
var strings = arr.map(function(n) {
var str = n.toString();
maxLen = Math.max(maxLen, str.length);
return str;
});
return strings.map(function(s) { return common.padLeft(s, maxLen); });
}
|
javascript
|
{
"resource": ""
}
|
q24022
|
strcpy
|
train
|
function strcpy(dest, src, offset) {
var origDestLen = dest.length;
var start = dest.slice(0, offset);
var end = dest.slice(offset + src.length);
return (start + src + end).substr(0, origDestLen);
}
|
javascript
|
{
"resource": ""
}
|
q24023
|
appendLine
|
train
|
function appendLine(num, content, prefix) {
sb.append(prefix + lineNumbers[num] + ' | ' + content + '\n');
}
|
javascript
|
{
"resource": ""
}
|
q24024
|
Extend
|
train
|
function Extend(superGrammar, name, body) {
this.superGrammar = superGrammar;
this.name = name;
this.body = body;
var origBody = superGrammar.rules[name].body;
this.terms = [body, origBody];
}
|
javascript
|
{
"resource": ""
}
|
q24025
|
ASemantics
|
train
|
function ASemantics(matchResult) {
if (!(matchResult instanceof MatchResult)) {
throw new TypeError(
'Semantics expected a MatchResult, but got ' + common.unexpectedObjToString(matchResult));
}
if (matchResult.failed()) {
throw new TypeError('cannot apply Semantics to ' + matchResult.toString());
}
var cst = matchResult._cst;
if (cst.grammar !== grammar) {
throw new Error(
"Cannot use a MatchResult from grammar '" + cst.grammar.name +
"' with a semantics for '" + grammar.name + "'");
}
var inputStream = new InputStream(matchResult.input);
return s.wrap(cst, inputStream.interval(matchResult._cstOffset, matchResult.input.length));
}
|
javascript
|
{
"resource": ""
}
|
q24026
|
Attribute
|
train
|
function Attribute(name, actionDict, builtInDefault) {
this.name = name;
this.formals = [];
this.actionDict = actionDict;
this.builtInDefault = builtInDefault;
}
|
javascript
|
{
"resource": ""
}
|
q24027
|
train
|
function(what, name, actionDict) {
function isSpecialAction(a) {
return a === '_iter' || a === '_terminal' || a === '_nonterminal' || a === '_default';
}
var problems = [];
for (var k in actionDict) {
var v = actionDict[k];
if (!isSpecialAction(k) && !(k in this.rules)) {
problems.push("'" + k + "' is not a valid semantic action for '" + this.name + "'");
} else if (typeof v !== 'function') {
problems.push(
"'" + k + "' must be a function in an action dictionary for '" + this.name + "'");
} else {
var actual = v.length;
var expected = this._topDownActionArity(k);
if (actual !== expected) {
problems.push(
"Semantic action '" + k + "' has the wrong arity: " +
'expected ' + expected + ', got ' + actual);
}
}
}
if (problems.length > 0) {
var prettyProblems = problems.map(function(problem) { return '- ' + problem; });
var error = new Error(
"Found errors in the action dictionary of the '" + name + "' " + what + ':\n' +
prettyProblems.join('\n'));
error.problems = problems;
throw error;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q24028
|
train
|
function(str) {
var app;
if (str.indexOf('<') === -1) {
// simple application
app = new pexprs.Apply(str);
} else {
// parameterized application
var cst = ohmGrammar.match(str, 'Base_application');
app = buildGrammar(cst, {});
}
// Ensure that the application is valid.
if (!(app.ruleName in this.rules)) {
throw errors.undeclaredRule(app.ruleName, this.name);
}
var formals = this.rules[app.ruleName].formals;
if (formals.length !== app.args.length) {
var source = this.rules[app.ruleName].source;
throw errors.wrongNumberOfParameters(app.ruleName, formals.length, app.args.length, source);
}
return app;
}
|
javascript
|
{
"resource": ""
}
|
|
q24029
|
train
|
function(pos, expr) {
var posInfo = this.memoTable[pos];
if (posInfo && expr.ruleName) {
var memoRec = posInfo.memo[expr.toMemoKey()];
if (memoRec && memoRec.traceEntry) {
var entry = memoRec.traceEntry.cloneWithExpr(expr);
entry.isMemoized = true;
return entry;
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q24030
|
train
|
function(pos, expr, succeeded, bindings) {
if (expr instanceof pexprs.Apply) {
var app = this.currentApplication();
var actuals = app ? app.args : [];
expr = expr.substituteParams(actuals);
}
return this.getMemoizedTraceEntry(pos, expr) ||
new Trace(this.input, pos, this.inputStream.pos, expr, succeeded, bindings, this.trace);
}
|
javascript
|
{
"resource": ""
}
|
|
q24031
|
binaryExpression
|
train
|
function binaryExpression(first, ops, rest) {
if (associativity[ops[0]] === 'L') {
const applyLeft = (x, y) => new BinaryExpression(x, ops.shift(), y);
return [first].concat(rest).reduce(applyLeft);
} else {
const applyRight = (x, y) => new BinaryExpression(y, ops.pop(), x);
return [first].concat(rest).reduceRight(applyRight);
}
}
|
javascript
|
{
"resource": ""
}
|
q24032
|
makeTree
|
train
|
function makeTree(left, ops, rights, minPrecedence = 0) {
while (ops.length > 0 && precedence[ops[0]] >= minPrecedence) {
let op = ops.shift();
let right = rights.shift();
while (ops.length > 0 && (precedence[ops[0]] > precedence[op] ||
associativity[ops[0]] === 'R' && precedence[ops[0]] === precedence[op])) {
right = makeTree(right, ops, rights, precedence[ops[0]]);
}
left = new BinaryExpression(left, op, right);
}
return left;
}
|
javascript
|
{
"resource": ""
}
|
q24033
|
getInputExcerpt
|
train
|
function getInputExcerpt(input, pos, len) {
var excerpt = asEscapedString(input.slice(pos, pos + len));
// Pad the output if necessary.
if (excerpt.length < len) {
return excerpt + common.repeat(' ', len - excerpt.length).join('');
}
return excerpt;
}
|
javascript
|
{
"resource": ""
}
|
q24034
|
getScriptElementContents
|
train
|
function getScriptElementContents(el) {
if (!isElement(el)) {
throw new TypeError('Expected a DOM Node, got ' + common.unexpectedObjToString(el));
}
if (el.type !== 'text/ohm-js') {
throw new Error('Expected a script tag with type="text/ohm-js", got ' + el);
}
return el.getAttribute('src') ? load(el.getAttribute('src')) : el.innerHTML;
}
|
javascript
|
{
"resource": ""
}
|
q24035
|
train
|
function(that) {
if (this.sourceString !== that.sourceString) {
throw errors.intervalSourcesDontMatch();
} else if (this.startIdx === that.startIdx && this.endIdx === that.endIdx) {
// `this` and `that` are the same interval!
return [
];
} else if (this.startIdx < that.startIdx && that.endIdx < this.endIdx) {
// `that` splits `this` into two intervals
return [
new Interval(this.sourceString, this.startIdx, that.startIdx),
new Interval(this.sourceString, that.endIdx, this.endIdx)
];
} else if (this.startIdx < that.endIdx && that.endIdx < this.endIdx) {
// `that` contains a prefix of `this`
return [
new Interval(this.sourceString, that.endIdx, this.endIdx)
];
} else if (this.startIdx < that.startIdx && that.startIdx < this.endIdx) {
// `that` contains a suffix of `this`
return [
new Interval(this.sourceString, this.startIdx, that.startIdx)
];
} else {
// `that` and `this` do not overlap
return [
this
];
}
}
|
javascript
|
{
"resource": ""
}
|
|
q24036
|
train
|
function(that) {
if (this.sourceString !== that.sourceString) {
throw errors.intervalSourcesDontMatch();
}
assert(this.startIdx >= that.startIdx && this.endIdx <= that.endIdx,
'other interval does not cover this one');
return new Interval(this.sourceString,
this.startIdx - that.startIdx,
this.endIdx - that.startIdx);
}
|
javascript
|
{
"resource": ""
}
|
|
q24037
|
flattenIterNodes
|
train
|
function flattenIterNodes(nodes) {
var result = [];
for (var i = 0; i < nodes.length; ++i) {
if (nodes[i]._node.ctorName === '_iter') {
result.push.apply(result, flattenIterNodes(nodes[i].children));
} else {
result.push(nodes[i]);
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q24038
|
duplicateRuleDeclaration
|
train
|
function duplicateRuleDeclaration(ruleName, grammarName, declGrammarName, optSource) {
var message = "Duplicate declaration for rule '" + ruleName +
"' in grammar '" + grammarName + "'";
if (grammarName !== declGrammarName) {
message += " (originally declared in '" + declGrammarName + "')";
}
return createError(message, optSource);
}
|
javascript
|
{
"resource": ""
}
|
q24039
|
wrongNumberOfParameters
|
train
|
function wrongNumberOfParameters(ruleName, expected, actual, source) {
return createError(
'Wrong number of parameters for rule ' + ruleName +
' (expected ' + expected + ', got ' + actual + ')',
source);
}
|
javascript
|
{
"resource": ""
}
|
q24040
|
wrongNumberOfArguments
|
train
|
function wrongNumberOfArguments(ruleName, expected, actual, expr) {
return createError(
'Wrong number of arguments for rule ' + ruleName +
' (expected ' + expected + ', got ' + actual + ')',
expr.source);
}
|
javascript
|
{
"resource": ""
}
|
q24041
|
invalidParameter
|
train
|
function invalidParameter(ruleName, expr) {
return createError(
'Invalid parameter to rule ' + ruleName + ': ' + expr + ' has arity ' + expr.getArity() +
', but parameter expressions must have arity 1',
expr.source);
}
|
javascript
|
{
"resource": ""
}
|
q24042
|
log_level_plus
|
train
|
function log_level_plus(logLevel) {
let index = log_levels.indexOf(logLevel)
if (index < 0) {
return []
} else {
return log_levels.slice(index, log_levels.length)
}
}
|
javascript
|
{
"resource": ""
}
|
q24043
|
api_act
|
train
|
function api_act() {
var argsarr = new Array(arguments.length)
for (var l = 0; l < argsarr.length; ++l) {
argsarr[l] = arguments[l]
}
var self = this
var spec = Common.build_message(self, argsarr, 'reply:f?', self.fixedargs)
var msg = spec.msg
var reply = spec.reply
if (opts.$.debug.act_caller || opts.$.test) {
msg.caller$ =
'\n Action call arguments and location: ' +
(new Error(Util.inspect(msg).replace(/\n/g, '')).stack + '\n')
.replace(/Error: /, '')
.replace(/.*\/gate-executor\.js:.*\n/g, '')
.replace(/.*\/seneca\.js:.*\n/g, '')
.replace(/.*\/seneca\/lib\/.*\.js:.*\n/g, '')
}
do_act(self, msg, reply)
return self
}
|
javascript
|
{
"resource": ""
}
|
q24044
|
api_close
|
train
|
function api_close(done) {
var seneca = this
var safe_done = _.once(function(err) {
if (_.isFunction(done)) {
return done.call(seneca, err)
}
})
// don't try to close twice
if (seneca.flags.closed) {
return safe_done()
}
seneca.ready(do_close)
var close_timeout = setTimeout(do_close, opts.$.close_delay)
function do_close() {
clearTimeout(close_timeout)
if (seneca.flags.closed) {
return safe_done()
}
// TODO: remove in 4.x
seneca.closed = true
seneca.flags.closed = true
// cleanup process event listeners
_.each(opts.$.system.close_signals, function(active, signal) {
if (active) {
process.removeListener(signal, private$.handle_close)
}
})
seneca.log.debug({
kind: 'close',
notice: 'start',
callpoint: callpoint()
})
seneca.act('role:seneca,cmd:close,closing$:true', function(err) {
seneca.log.debug(errlog(err, { kind: 'close', notice: 'end' }))
seneca.removeAllListeners('act-in')
seneca.removeAllListeners('act-out')
seneca.removeAllListeners('act-err')
seneca.removeAllListeners('pin')
seneca.removeAllListeners('after-pin')
seneca.removeAllListeners('ready')
seneca.private$.history.close()
if (seneca.private$.status_interval) {
clearInterval(seneca.private$.status_interval)
}
return safe_done(err)
})
}
return seneca
}
|
javascript
|
{
"resource": ""
}
|
q24045
|
make_private
|
train
|
function make_private() {
return {
stats: {
start: Date.now(),
act: {
calls: 0,
done: 0,
fails: 0,
cache: 0
},
actmap: {}
},
actdef: {},
transport: {
register: []
},
plugins: {},
ignore_plugins: {}
}
}
|
javascript
|
{
"resource": ""
}
|
q24046
|
adapter
|
train
|
function adapter (context, payload) {
var when = payload.when.toString()
var kind = pad(payload.kind || '-', 8).toUpperCase()
var type = pad(payload.case || '-', 8).toUpperCase()
var text = payload.pattern || payload.notice || '-'
console.log(when, kind, type, text)
}
|
javascript
|
{
"resource": ""
}
|
q24047
|
inward_act_cache
|
train
|
function inward_act_cache(ctxt, data) {
var so = ctxt.options
var meta = data.meta
var actid = meta.id
var private$ = ctxt.seneca.private$
if (actid != null && so.history.active) {
var actdetails = private$.history.get(actid)
if (actdetails) {
private$.stats.act.cache++
var latest = actdetails.result[actdetails.result.length - 1] || {}
var out = {
kind: latest.err ? 'error' : 'result',
result: latest.res || null,
error: latest.err || null,
log: {
level: 'debug',
data: {
kind: 'act',
case: 'CACHE',
cachetime: latest.when
}
}
}
ctxt.cached$ = true
return out
}
}
}
|
javascript
|
{
"resource": ""
}
|
q24048
|
getSqSegDist
|
train
|
function getSqSegDist(p, p1, p2) {
var x = p1.x,
y = p1.y,
dx = p2.x - x,
dy = p2.y - y;
if (dx !== 0 || dy !== 0) {
var t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
x = p2.x;
y = p2.y;
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = p.x - x;
dy = p.y - y;
return dx * dx + dy * dy;
}
|
javascript
|
{
"resource": ""
}
|
q24049
|
simplifyRadialDist
|
train
|
function simplifyRadialDist(points, sqTolerance) {
var prevPoint = points[0],
newPoints = [prevPoint],
point;
for (var i = 1, len = points.length; i < len; i++) {
point = points[i];
if (getSqDist(point, prevPoint) > sqTolerance) {
newPoints.push(point);
prevPoint = point;
}
}
if (prevPoint !== point) newPoints.push(point);
return newPoints;
}
|
javascript
|
{
"resource": ""
}
|
q24050
|
simplifyDouglasPeucker
|
train
|
function simplifyDouglasPeucker(points, sqTolerance) {
var last = points.length - 1;
var simplified = [points[0]];
simplifyDPStep(points, 0, last, sqTolerance, simplified);
simplified.push(points[last]);
return simplified;
}
|
javascript
|
{
"resource": ""
}
|
q24051
|
isExpression
|
train
|
function isExpression(node) {
switch (node.type) {
case Syntax.AssignmentExpression:
case Syntax.ArrayExpression:
case Syntax.ArrayPattern:
case Syntax.BinaryExpression:
case Syntax.CallExpression:
case Syntax.ConditionalExpression:
case Syntax.ClassExpression:
case Syntax.ExportBatchSpecifier:
case Syntax.ExportSpecifier:
case Syntax.FunctionExpression:
case Syntax.Identifier:
case Syntax.ImportDefaultSpecifier:
case Syntax.ImportNamespaceSpecifier:
case Syntax.ImportSpecifier:
case Syntax.Literal:
case Syntax.LogicalExpression:
case Syntax.MemberExpression:
case Syntax.MethodDefinition:
case Syntax.ModuleSpecifier:
case Syntax.NewExpression:
case Syntax.ObjectExpression:
case Syntax.ObjectPattern:
case Syntax.Property:
case Syntax.SequenceExpression:
case Syntax.ThisExpression:
case Syntax.UnaryExpression:
case Syntax.UpdateExpression:
case Syntax.YieldExpression:
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q24052
|
isStatement
|
train
|
function isStatement(node) {
switch (node.type) {
case Syntax.BlockStatement:
case Syntax.BreakStatement:
case Syntax.CatchClause:
case Syntax.ContinueStatement:
case Syntax.ClassDeclaration:
case Syntax.ClassBody:
case Syntax.DirectiveStatement:
case Syntax.DoWhileStatement:
case Syntax.DebuggerStatement:
case Syntax.EmptyStatement:
case Syntax.ExpressionStatement:
case Syntax.ForStatement:
case Syntax.ForInStatement:
case Syntax.ForOfStatement:
case Syntax.FunctionDeclaration:
case Syntax.IfStatement:
case Syntax.LabeledStatement:
case Syntax.Program:
case Syntax.ReturnStatement:
case Syntax.SwitchStatement:
case Syntax.SwitchCase:
case Syntax.ThrowStatement:
case Syntax.TryStatement:
case Syntax.VariableDeclaration:
case Syntax.VariableDeclarator:
case Syntax.WhileStatement:
case Syntax.WithStatement:
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q24053
|
flattenToString
|
train
|
function flattenToString(arr) {
var i, iz, elem, result = '';
for (i = 0, iz = arr.length; i < iz; ++i) {
elem = arr[i];
result += isArray(elem) ? flattenToString(elem) : elem;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q24054
|
toSourceNodeWhenNeeded
|
train
|
function toSourceNodeWhenNeeded(generated, node) {
if (!sourceMap) {
// with no source maps, generated is either an
// array or a string. if an array, flatten it.
// if a string, just return it
if (isArray(generated)) {
return flattenToString(generated);
} else {
return generated;
}
}
if (node == null) {
if (generated instanceof SourceNode) {
return generated;
} else {
node = {};
}
}
if (node.loc == null) {
return new SourceNode(null, null, sourceMap, generated, node.name || null);
}
return new SourceNode(node.loc.start.line, node.loc.start.column, (sourceMap === true ? node.loc.source || null : sourceMap), generated, node.name || null);
}
|
javascript
|
{
"resource": ""
}
|
q24055
|
fillArray
|
train
|
function fillArray(low, high, step, def) {
step = step || 1;
var i = [], x;
for (x = low; x <= high; x += step) {
i[x] = def === undefined ? x : (typeof def === 'function' ? def(x) : def);
}
return i;
}
|
javascript
|
{
"resource": ""
}
|
q24056
|
createData
|
train
|
function createData() {
var x, y, d = [];
for (x = 0; x < 100; x += 1) {
d[x] = {};
for (y = 0; y < 20; y += 1) {
d[x][y] = y * x;
}
}
return d;
}
|
javascript
|
{
"resource": ""
}
|
q24057
|
checkScrollBoxVisibility
|
train
|
function checkScrollBoxVisibility() {
self.scrollBox.horizontalBarVisible = (self.style.width !== 'auto' && dataWidth > self.scrollBox.width && self.style.overflowX !== 'hidden')
|| self.style.overflowX === 'scroll';
self.scrollBox.horizontalBoxVisible = dataWidth > self.scrollBox.width;
self.scrollBox.verticalBarVisible = (self.style.height !== 'auto' && dataHeight > self.scrollBox.height && self.style.overflowY !== 'hidden')
|| self.style.overflowY === 'scroll';
self.scrollBox.verticalBoxVisible = dataHeight > self.scrollBox.height;
}
|
javascript
|
{
"resource": ""
}
|
q24058
|
createTopic
|
train
|
function createTopic(env, callback) {
sns.createTopic({
Name: `${params.app}-${env}-${params.event}`,
},
function _createTopic(err) {
if (err) {
console.log(err)
}
setTimeout(callback, 0)
})
}
|
javascript
|
{
"resource": ""
}
|
q24059
|
filter
|
train
|
function filter(p) {
if (filters.length === 0)
return true
let predicate = false
filters.forEach(section=> {
let current = path.join('src', section)
if (p.startsWith(current)) {
predicate = true
}
})
return predicate
}
|
javascript
|
{
"resource": ""
}
|
q24060
|
start
|
train
|
function start(callback) {
let handle = {close(){server.close()}}
check(function _check(err, inUse) {
if (err) throw err
if (inUse) {
server = {close(){}}
init(callback)
}
else {
server = dynalite({
createTableMs: 0
}).listen(5000, function _server(err) {
if (err) {
// if we err then the db has been started elsewhere..
// just try to continue
console.log(err)
}
init(callback)
})
}
})
return handle
}
|
javascript
|
{
"resource": ""
}
|
q24061
|
start
|
train
|
function start(callback) {
let {arc} = readArc()
let close = x=> !x
// if .arc has events and we're not clobbering with ARC_LOCAL flag
if (arc.events || arc.queues) {
// start a little web server
let server = http.createServer(function listener(req, res) {
let body = ''
req.on('data', chunk => {
body += chunk.toString()
})
req.on('end', () => {
let message = JSON.parse(body)
if (req.url === '/queues') {
message.arcType = 'queue'
} else if (req.url === '/events' || req.url === '/') {
message.arcType = 'event'
} else {
res.statusCode = 404
res.end('not found')
console.log(chalk.red.dim('event bus 404 for URL ' + req.url))
return
}
console.log(chalk.grey.dim('@' + message.arcType), chalk.green.dim(JSON.stringify(JSON.parse(body), null, 2)))
// spawn a fork of the node process
let subprocess = fork(path.join(__dirname, '_subprocess.js'))
subprocess.send(message)
subprocess.on('message', function _message(msg) {
console.log(chalk.grey.dim(msg.text))
})
res.statusCode = 200
res.end('ok')
})
})
// ends our little web server
close = function _closer() {
try {
server.close()
}
catch(e) {
console.log('swallowing server.close error in sandbox events', e)
}
}
// start listening on 3334
server.listen(3334, callback ? callback: x=>!x)
}
else {
callback()
}
return {close}
}
|
javascript
|
{
"resource": ""
}
|
q24062
|
_readArc
|
train
|
function _readArc(callback) {
let parsed = readArc()
arc = parsed.arc
inventory(arc, null, function _arc(err, result) {
if (err) callback(err)
else {
pathToCode = result.localPaths
callback()
}
})
}
|
javascript
|
{
"resource": ""
}
|
q24063
|
copy
|
train
|
function copy(source, destination, callback) {
cp(source, destination, {overwrite: true}, function done(err) {
if (err) callback(err)
else callback()
})
}
|
javascript
|
{
"resource": ""
}
|
q24064
|
listTopics
|
train
|
function listTopics(next, done) {
let params = next? {NextToken:next} : {}
sns.listTopics(params, function _listTopics(err, result) {
if (err) {
done(err)
}
else {
// keep track of our current iteration
let index = 0
let tidy = t=> t.TopicArn.split(':').reverse().shift()
// iterate the topics seeking our name
result.Topics.map(tidy).forEach(t=> {
if (t === name) {
found = result.Topics[index].TopicArn
}
index += 1
})
// if there are more pages walk those
let more = result.NextToken && !found
if (more) {
listTopics(result.NextToken, done)
}
else {
// otherwise we're done walking
done()
}
}
})
}
|
javascript
|
{
"resource": ""
}
|
q24065
|
read
|
train
|
function read(callback) {
let raw = fs.readFileSync(thing.path).toString()
//let json = thing.path.split('.').reverse()[0] === 'json'
// TODO add support for role.yaml
let policies = JSON.parse(raw).policies
callback(null, policies || [])
}
|
javascript
|
{
"resource": ""
}
|
q24066
|
removes
|
train
|
function removes(result, callback) {
let fns = result.AttachedPolicies.map(p=> {
return function maybeRemove(callback) {
let PolicyArn = p.PolicyArn
if (policies.includes(PolicyArn)) {
callback()
}
else {
iam.detachRolePolicy({
RoleName,
PolicyArn
}, callback)
}
}
})
series(fns, callback)
}
|
javascript
|
{
"resource": ""
}
|
q24067
|
adds
|
train
|
function adds(result, callback) {
let fns = policies.map(PolicyArn=> {
return function maybeAdd(callback) {
iam.attachRolePolicy({
RoleName,
PolicyArn
}, callback)
}
})
series(fns, callback)
}
|
javascript
|
{
"resource": ""
}
|
q24068
|
_read
|
train
|
function _read(callback) {
glob(path.join(process.cwd(), pathToCode, '/*'), {dot:true}, callback)
}
|
javascript
|
{
"resource": ""
}
|
q24069
|
createIntegration
|
train
|
function createIntegration(callback) {
setTimeout(function throttle() {
let uri = `arn:aws:apigateway:${region}:lambda:path/2015-03-31/functions/${arn}/invocations`
// console.log(api)
gateway.createIntegration({
ApiId: api.ApiId,
IntegrationMethod: 'POST',
IntegrationType: 'AWS_PROXY',
IntegrationUri: uri
}, callback)
}, 1000)
}
|
javascript
|
{
"resource": ""
}
|
q24070
|
createRoute
|
train
|
function createRoute(result, callback) {
setTimeout(function throttle() {
gateway.createRoute({
ApiId: api.ApiId,
RouteKey,
Target: `integrations/${integrationId}`
}, callback)
}, 1000)
}
|
javascript
|
{
"resource": ""
}
|
q24071
|
getBucket
|
train
|
function getBucket(env, static) {
let staging
let production
static.forEach(thing=> {
if (thing[0] === 'staging') {
staging = thing[1]
}
if (thing[0] === 'production') {
production = thing[1]
}
})
if (env === 'staging')
return staging
if (env === 'production')
return production
}
|
javascript
|
{
"resource": ""
}
|
q24072
|
reads
|
train
|
function reads(callback) {
parallel({
cert(callback) {
acm.listCertificates({}, callback)
},
apis(callback) {
gw.getRestApis({
limit: 500,
}, callback)
}
}, callback)
}
|
javascript
|
{
"resource": ""
}
|
q24073
|
getRecordSetsAndDomains
|
train
|
function getRecordSetsAndDomains(result, callback) {
HostedZoneId = result.HostedZones.find(i=>i.Name === `${domain}.`).Id
parallel({
apis(callback) {
gateway.getDomainNames({
limit: 500,
}, callback)
},
records(callback) {
route53.listResourceRecordSets({
HostedZoneId,
}, callback)
}
}, callback)
}
|
javascript
|
{
"resource": ""
}
|
q24074
|
stringify
|
train
|
function stringify(arc) {
let fmtTbl = obj=> {
let name = Object.keys(obj)[0]
let keys = Object.keys(obj[name])
let result = `${name}\n`
keys.forEach(key=> {
let val = obj[name][key]
result += ` ${key} ${val}\n`
})
return result
}
let str = `@app\n${arc.app[0]}\n`
/////////////////////////////////
if (arc.http.length > 0)
str += `\n@http\n` + arc.http.map(tuple=> tuple.join(' ') + '\n').join('')
if (arc.events.length > 0)
str += `\n@events\n` + arc.events.join('\n') + '\n'
if (arc.queues.length > 0)
str += `\n@queues\n` + arc.queues.join('\n') + '\n'
if (arc.scheduled.length > 0)
str += `\n@scheduled\n` + arc.scheduled.map(v=> v.join(' ')).join('\n') + '\n'
if (arc.tables.length > 0)
str += `\n@tables\n` + arc.tables.map(fmtTbl).join('\n')
if (arc.aws.length > 0)
str += `\n@aws\n` + arc.aws.map(tuple=> tuple.join(' ') + '\n').join('')
//////////
return str
}
|
javascript
|
{
"resource": ""
}
|
q24075
|
_createRole
|
train
|
function _createRole(callback) {
var iam = new aws.IAM
iam.createRole({
AssumeRolePolicyDocument: JSON.stringify({
Version: '2012-10-17',
Statement: [{
Sid: '',
Effect: 'Allow',
Principal: {
Service: 'lambda.amazonaws.com'
},
Action: 'sts:AssumeRole'
}]
}),
Path: '/',
RoleName,
},
function done(err, result) {
if (err) throw err
var policies = [
'arn:aws:iam::aws:policy/AmazonS3FullAccess',
'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess',
'arn:aws:iam::aws:policy/AmazonSNSFullAccess',
'arn:aws:iam::aws:policy/AmazonSQSFullAccess',
'arn:aws:iam::aws:policy/service-role/AWSLambdaSQSQueueExecutionRole',
'arn:aws:iam::aws:policy/AmazonAPIGatewayInvokeFullAccess',
].map(PolicyArn=> {
return function _attachPolicy(callback) {
iam.attachRolePolicy({
RoleName,
PolicyArn,
}, callback)
}
})
policies.push(function _putPolicy(callback) {
iam.putRolePolicy({
PolicyDocument: JSON.stringify({
'Version': '2012-10-17',
'Statement': [{
'Effect': 'Allow',
'Action': [
'logs:CreateLogGroup',
'logs:CreateLogStream',
'logs:PutLogEvents',
'logs:DescribeLogStreams'
],
'Resource': 'arn:aws:logs:*:*:*'
}]
}, null, 2),
PolicyName: 'ArcLambdaCloudwatchPolicy',
RoleName
}, callback)
})
parallel(policies, function _done(err) {
if (err) throw err
// the latency magic numbers is a weirder part of cloud
setTimeout(function _fakeLatency() {
callback(null, result.Role)
}, 9999)
})
})
}
|
javascript
|
{
"resource": ""
}
|
q24076
|
getName
|
train
|
function getName(tuple) {
if (Array.isArray(tuple)) {
var verb = tuple[0]
var path = getLambdaName(tuple[1])
return [`${app}-production-${verb}${path}`, `${app}-staging-${verb}${path}`]
}
else {
var path = getLambdaName(tuple)
return [`${app}-production-get${path}`, `${app}-staging-get${path}`]
}
}
|
javascript
|
{
"resource": ""
}
|
q24077
|
getSystemName
|
train
|
function getSystemName(tuple) {
if (Array.isArray(tuple)) {
var verb = tuple[0]
var path = getLambdaName(tuple[1])
return `${verb}${path}`
}
else {
var path = getLambdaName(tuple)
return `get${path}`
}
}
|
javascript
|
{
"resource": ""
}
|
q24078
|
getLegacyName
|
train
|
function getLegacyName(tuple) {
if (Array.isArray(tuple)) {
var verb = tuple[0]
var path = getLegacyLambdaName(tuple[1])
return [`${app}-production-${verb}${path}`, `${app}-staging-${verb}${path}`]
}
else {
var path = getLegacyLambdaName(tuple)
return [`${app}-production-get${path}`, `${app}-staging-get${path}`]
}
}
|
javascript
|
{
"resource": ""
}
|
q24079
|
getLegacySystemName
|
train
|
function getLegacySystemName(tuple) {
if (Array.isArray(tuple)) {
var verb = tuple[0]
var path = getLegacyLambdaName(tuple[1])
return `${verb}${path}`
}
else {
var path = getLegacyLambdaName(tuple)
return `get${path}`
}
}
|
javascript
|
{
"resource": ""
}
|
q24080
|
getScheduledName
|
train
|
function getScheduledName(arr) {
var name = arr.slice(0).shift()
return [`${app}-production-${name}`, `${app}-staging-${name}`]
}
|
javascript
|
{
"resource": ""
}
|
q24081
|
train
|
function(type, base_class) {
if (!base_class.prototype) {
throw "Cannot register a simple object, it must be a class with a prototype";
}
base_class.type = type;
if (LiteGraph.debug) {
console.log("Node registered: " + type);
}
var categories = type.split("/");
var classname = base_class.name;
var pos = type.lastIndexOf("/");
base_class.category = type.substr(0, pos);
if (!base_class.title) {
base_class.title = classname;
}
//info.name = name.substr(pos+1,name.length - pos);
//extend class
if (base_class.prototype) {
//is a class
for (var i in LGraphNode.prototype) {
if (!base_class.prototype[i]) {
base_class.prototype[i] = LGraphNode.prototype[i];
}
}
}
Object.defineProperty(base_class.prototype, "shape", {
set: function(v) {
switch (v) {
case "default":
delete this._shape;
break;
case "box":
this._shape = LiteGraph.BOX_SHAPE;
break;
case "round":
this._shape = LiteGraph.ROUND_SHAPE;
break;
case "circle":
this._shape = LiteGraph.CIRCLE_SHAPE;
break;
case "card":
this._shape = LiteGraph.CARD_SHAPE;
break;
default:
this._shape = v;
}
},
get: function(v) {
return this._shape;
},
enumerable: true
});
var prev = this.registered_node_types[type];
this.registered_node_types[type] = base_class;
if (base_class.constructor.name) {
this.Nodes[classname] = base_class;
}
if (LiteGraph.onNodeTypeRegistered) {
LiteGraph.onNodeTypeRegistered(type, base_class);
}
if (prev && LiteGraph.onNodeTypeReplaced) {
LiteGraph.onNodeTypeReplaced(type, base_class, prev);
}
//warnings
if (base_class.prototype.onPropertyChange) {
console.warn(
"LiteGraph node class " +
type +
" has onPropertyChange method, it must be called onPropertyChanged with d at the end"
);
}
if (base_class.supported_extensions) {
for (var i in base_class.supported_extensions) {
this.node_types_by_file_extension[
base_class.supported_extensions[i].toLowerCase()
] = base_class;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q24082
|
train
|
function(
name,
func,
param_types,
return_type,
properties
) {
var params = Array(func.length);
var code = "";
var names = LiteGraph.getParameterNames(func);
for (var i = 0; i < names.length; ++i) {
code +=
"this.addInput('" +
names[i] +
"'," +
(param_types && param_types[i]
? "'" + param_types[i] + "'"
: "0") +
");\n";
}
code +=
"this.addOutput('out'," +
(return_type ? "'" + return_type + "'" : 0) +
");\n";
if (properties) {
code +=
"this.properties = " + JSON.stringify(properties) + ";\n";
}
var classobj = Function(code);
classobj.title = name.split("/").pop();
classobj.desc = "Generated from " + func.name;
classobj.prototype.onExecute = function onExecute() {
for (var i = 0; i < params.length; ++i) {
params[i] = this.getInputData(i);
}
var r = func.apply(this, params);
this.setOutputData(0, r);
};
this.registerNodeType(name, classobj);
}
|
javascript
|
{
"resource": ""
}
|
|
q24083
|
train
|
function(type, title, options) {
var base_class = this.registered_node_types[type];
if (!base_class) {
if (LiteGraph.debug) {
console.log(
'GraphNode type "' + type + '" not registered.'
);
}
return null;
}
var prototype = base_class.prototype || base_class;
title = title || base_class.title || type;
var node = null;
if (LiteGraph.catch_exceptions) {
try {
node = new base_class(title);
} catch (err) {
console.error(err);
return null;
}
} else {
node = new base_class(title);
}
node.type = type;
if (!node.title && title) {
node.title = title;
}
if (!node.properties) {
node.properties = {};
}
if (!node.properties_info) {
node.properties_info = [];
}
if (!node.flags) {
node.flags = {};
}
if (!node.size) {
node.size = node.computeSize();
}
if (!node.pos) {
node.pos = LiteGraph.DEFAULT_POSITION.concat();
}
if (!node.mode) {
node.mode = LiteGraph.ALWAYS;
}
//extra options
if (options) {
for (var i in options) {
node[i] = options[i];
}
}
return node;
}
|
javascript
|
{
"resource": ""
}
|
|
q24084
|
train
|
function(category, filter) {
var r = [];
for (var i in this.registered_node_types) {
var type = this.registered_node_types[i];
if (filter && type.filter && type.filter != filter) {
continue;
}
if (category == "") {
if (type.category == null) {
r.push(type);
}
} else if (type.category == category) {
r.push(type);
}
}
return r;
}
|
javascript
|
{
"resource": ""
}
|
|
q24085
|
train
|
function() {
var categories = { "": 1 };
for (var i in this.registered_node_types) {
if (
this.registered_node_types[i].category &&
!this.registered_node_types[i].skip_list
) {
categories[this.registered_node_types[i].category] = 1;
}
}
var result = [];
for (var i in categories) {
result.push(i);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q24086
|
train
|
function(obj, target) {
if (obj == null) {
return null;
}
var r = JSON.parse(JSON.stringify(obj));
if (!target) {
return r;
}
for (var i in r) {
target[i] = r[i];
}
return target;
}
|
javascript
|
{
"resource": ""
}
|
|
q24087
|
LLink
|
train
|
function LLink(id, type, origin_id, origin_slot, target_id, target_slot) {
this.id = id;
this.type = type;
this.origin_id = origin_id;
this.origin_slot = origin_slot;
this.target_id = target_id;
this.target_slot = target_slot;
this._data = null;
this._pos = new Float32Array(2); //center
}
|
javascript
|
{
"resource": ""
}
|
q24088
|
isInsideBounding
|
train
|
function isInsideBounding(p, bb) {
if (
p[0] < bb[0][0] ||
p[1] < bb[0][1] ||
p[0] > bb[1][0] ||
p[1] > bb[1][1]
) {
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q24089
|
hex2num
|
train
|
function hex2num(hex) {
if (hex.charAt(0) == "#") {
hex = hex.slice(1);
} //Remove the '#' char - if there is one.
hex = hex.toUpperCase();
var hex_alphabets = "0123456789ABCDEF";
var value = new Array(3);
var k = 0;
var int1, int2;
for (var i = 0; i < 6; i += 2) {
int1 = hex_alphabets.indexOf(hex.charAt(i));
int2 = hex_alphabets.indexOf(hex.charAt(i + 1));
value[k] = int1 * 16 + int2;
k++;
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q24090
|
num2hex
|
train
|
function num2hex(triplet) {
var hex_alphabets = "0123456789ABCDEF";
var hex = "#";
var int1, int2;
for (var i = 0; i < 3; i++) {
int1 = triplet[i] / 16;
int2 = triplet[i] % 16;
hex += hex_alphabets.charAt(int1) + hex_alphabets.charAt(int2);
}
return hex;
}
|
javascript
|
{
"resource": ""
}
|
q24091
|
inner_onclick
|
train
|
function inner_onclick(e) {
var value = this.value;
var close_parent = true;
if (that.current_submenu) {
that.current_submenu.close(e);
}
//global callback
if (options.callback) {
var r = options.callback.call(
this,
value,
options,
e,
that,
options.node
);
if (r === true) {
close_parent = false;
}
}
//special cases
if (value) {
if (
value.callback &&
!options.ignore_item_callbacks &&
value.disabled !== true
) {
//item callback
var r = value.callback.call(
this,
value,
options,
e,
that,
options.extra
);
if (r === true) {
close_parent = false;
}
}
if (value.submenu) {
if (!value.submenu.options) {
throw "ContextMenu submenu needs options";
}
var submenu = new that.constructor(value.submenu.options, {
callback: value.submenu.callback,
event: e,
parentMenu: that,
ignore_item_callbacks:
value.submenu.ignore_item_callbacks,
title: value.submenu.title,
extra: value.submenu.extra,
autoopen: options.autoopen
});
close_parent = false;
}
}
if (close_parent && !that.lock) {
that.close();
}
}
|
javascript
|
{
"resource": ""
}
|
q24092
|
GraphInput
|
train
|
function GraphInput() {
this.addOutput("", "");
this.name_in_graph = "";
this.properties = {};
var that = this;
Object.defineProperty(this.properties, "name", {
get: function() {
return that.name_in_graph;
},
set: function(v) {
if (v == "" || v == that.name_in_graph || v == "enabled") {
return;
}
if (that.name_in_graph) {
//already added
that.graph.renameInput(that.name_in_graph, v);
} else {
that.graph.addInput(v, that.properties.type);
}
that.name_widget.value = v;
that.name_in_graph = v;
},
enumerable: true
});
Object.defineProperty(this.properties, "type", {
get: function() {
return that.outputs[0].type;
},
set: function(v) {
if (v == "event") {
v = LiteGraph.EVENT;
}
that.outputs[0].type = v;
if (that.name_in_graph) {
//already added
that.graph.changeInputType(
that.name_in_graph,
that.outputs[0].type
);
}
that.type_widget.value = v;
},
enumerable: true
});
this.name_widget = this.addWidget(
"text",
"Name",
this.properties.name,
function(v) {
if (!v) {
return;
}
that.properties.name = v;
}
);
this.type_widget = this.addWidget(
"text",
"Type",
this.properties.type,
function(v) {
v = v || "";
that.properties.type = v;
}
);
this.widgets_up = true;
this.size = [180, 60];
}
|
javascript
|
{
"resource": ""
}
|
q24093
|
GraphOutput
|
train
|
function GraphOutput() {
this.addInput("", "");
this.name_in_graph = "";
this.properties = {};
var that = this;
Object.defineProperty(this.properties, "name", {
get: function() {
return that.name_in_graph;
},
set: function(v) {
if (v == "" || v == that.name_in_graph) {
return;
}
if (that.name_in_graph) {
//already added
that.graph.renameOutput(that.name_in_graph, v);
} else {
that.graph.addOutput(v, that.properties.type);
}
that.name_widget.value = v;
that.name_in_graph = v;
},
enumerable: true
});
Object.defineProperty(this.properties, "type", {
get: function() {
return that.inputs[0].type;
},
set: function(v) {
if (v == "action" || v == "event") {
v = LiteGraph.ACTION;
}
that.inputs[0].type = v;
if (that.name_in_graph) {
//already added
that.graph.changeOutputType(
that.name_in_graph,
that.inputs[0].type
);
}
that.type_widget.value = v || "";
},
enumerable: true
});
this.name_widget = this.addWidget(
"text",
"Name",
this.properties.name,
function(v) {
if (!v) {
return;
}
that.properties.name = v;
}
);
this.type_widget = this.addWidget(
"text",
"Type",
this.properties.type,
function(v) {
v = v || "";
that.properties.type = v;
}
);
this.widgets_up = true;
this.size = [180, 60];
}
|
javascript
|
{
"resource": ""
}
|
q24094
|
Sequencer
|
train
|
function Sequencer() {
this.addInput("", LiteGraph.ACTION);
this.addInput("", LiteGraph.ACTION);
this.addInput("", LiteGraph.ACTION);
this.addInput("", LiteGraph.ACTION);
this.addInput("", LiteGraph.ACTION);
this.addInput("", LiteGraph.ACTION);
this.addOutput("", LiteGraph.EVENT);
this.addOutput("", LiteGraph.EVENT);
this.addOutput("", LiteGraph.EVENT);
this.addOutput("", LiteGraph.EVENT);
this.addOutput("", LiteGraph.EVENT);
this.addOutput("", LiteGraph.EVENT);
this.size = [120, 30];
this.flags = { horizontal: true, render_box: false };
}
|
javascript
|
{
"resource": ""
}
|
q24095
|
MathFormula
|
train
|
function MathFormula() {
this.addInput("x", "number");
this.addInput("y", "number");
this.addOutput("", "number");
this.properties = { x: 1.0, y: 1.0, formula: "x+y" };
this.code_widget = this.addWidget(
"text",
"F(x,y)",
this.properties.formula,
function(v, canvas, node) {
node.properties.formula = v;
}
);
this.addWidget("toggle", "allow", LiteGraph.allow_scripts, function(v) {
LiteGraph.allow_scripts = v;
});
this._func = null;
}
|
javascript
|
{
"resource": ""
}
|
q24096
|
LGraphTextureScaleOffset
|
train
|
function LGraphTextureScaleOffset() {
this.addInput("in", "Texture");
this.addInput("scale", "vec2");
this.addInput("offset", "vec2");
this.addOutput("out", "Texture");
this.properties = {
offset: vec2.fromValues(0, 0),
scale: vec2.fromValues(1, 1),
precision: LGraphTexture.DEFAULT
};
}
|
javascript
|
{
"resource": ""
}
|
q24097
|
LGraphExposition
|
train
|
function LGraphExposition() {
this.addInput("in", "Texture");
this.addInput("exp", "number");
this.addOutput("out", "Texture");
this.properties = { exposition: 1, precision: LGraphTexture.LOW };
this._uniforms = { u_texture: 0, u_exposition: 1 };
}
|
javascript
|
{
"resource": ""
}
|
q24098
|
onDirectory
|
train
|
function onDirectory() {
var this_SendStream = this;
if (!/\/$/.test(reqUrl.pathname)) {
// No trailing slash? Redirect to add one
res.writeHead(301, {
'Location': reqUrl.pathname + '/' + (reqUrl.search || '')
});
res.end();
deferred.resolve(true);
return;
}
var indexPath = path.normalize(path.join(
self.$root, unescape(this.path), 'index.html'));
fs.exists(indexPath, function(exists) {
if (exists) {
// index.html exists, just serve that. This is the same as
// the below call except without onDirectory and without
// .index(false)
send(req, suffix, {root: self.$root})
.on('error', onError)
.on('stream', onStream)
.pipe(res);
deferred.resolve(true);
} else {
// Either serve up 404, or the directory auto-index
if (!self.$dirIndex) {
deferred.resolve(null);
} else {
deferred.resolve(
self.$autoindex_p(req, res, this_SendStream.path, self.$blacklist)
);
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
q24099
|
error500
|
train
|
function error500(req, res, errorText, detail, templateDir, consoleLogFile, appSpec) {
fsutil.safeTail_p(consoleLogFile, 8192)
.fail(function(consoleLog) {
return;
})
.then(function(consoleLog) {
render.sendPage(res, 500, 'An error has occurred', {
template: 'error-500',
templateDir: templateDir,
vars: {
message: errorText,
detail: detail,
console: (appSpec && appSpec.settings.appDefaults.sanitizeErrors) ? null : consoleLog
}
});
})
.fail(function(err) {
logger.error('Failed to render error 500 page: ' + err.message);
})
.fin(function() {
try {
res.end();
} catch(err) {
logger.error('Error while cleaning up response: ' + err);
}
})
.done();
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.