_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q51500
|
train
|
function(forceRefresh) {
if (cachedProjectData && !forceRefresh) {
Logger.debug('ProjectsService: returning cached project data');
return $q.when(cachedProjectData);
}
Logger.debug('ProjectsService: listing projects, force refresh', forceRefresh);
return DataService.list(projectsVersion, {}).then(function(projectData) {
cachedProjectData = projectData;
return projectData;
}, function(error) {
// If the request fails, don't try to list projects again without `forceRefresh`.
cachedProjectData = DataService.createData([]);
cachedProjectDataIncomplete = true;
return $q.reject();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51501
|
train
|
function(params, stateData) {
// Handle an error response from the OAuth server
if (params.error) {
authLogger.log("RedirectLoginService.finish(), error", params.error, params.error_description, params.error_uri);
return $q.reject({
error: params.error,
error_description: params.error_description,
error_uri: params.error_uri
});
}
// Handle an access_token fragment response
if (params.access_token) {
return $q.when({
token: params.access_token,
ttl: params.expires_in,
then: stateData.then,
verified: stateData.verified
});
}
// No token and no error is invalid
return $q.reject({
error: "invalid_request",
error_description: "No API token returned"
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51502
|
train
|
function (notification) {
if (!notification.id) {
return false;
}
return _.some(notifications, function(next) {
return !next.hidden && notification.id === next.id;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51503
|
_factoryDomInit
|
train
|
function _factoryDomInit() {
// Add class to sliding elements
slidingElements.forEach( function( item ) {
addClass( item, slidingElementsClass );
});
// DOM Fallbacks when CSS transform 3d not available
if ( !has3d ) {
// No CSS 3d Transform fallback
addClass( document.documentElement, 'no-csstransforms3d' ); //Adds Modernizr-like class to HTML element when CSS 3D Transforms not available
}
// Add init class to body
addClass( body, initClass );
}
|
javascript
|
{
"resource": ""
}
|
q51504
|
train
|
function( el, options ) {
// Get length of instantiated Offsides array
var offsideId = instantiatedOffsides.length || 0,
// Instantiate new Offside instance
offsideInstance = createOffsideInstance( el, options, offsideId );
// If Offside instance is sccessfully created
if ( offsideInstance !== null ) {
// Push new instance into "instantiatedOffsides" array and return it
/*jshint -W093 */
return instantiatedOffsides[ offsideId ] = offsideInstance;
/*jshint +W093 */
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51505
|
train
|
function ( el, options ) {
/*
* When Offside is called for the first time,
* inject a singleton-factory object
* as a static method in "offside.factory".
*
* Offside factory serves the following purposes:
* - DOM initialization
* - Centralized Offside instances management and initialization
*/
if ( !singleton.getInstance.factory ) {
singleton.getInstance.factory = initOffsideFactory( options );
}
return singleton.getInstance.factory.getOffsideInstance( el, options );
}
|
javascript
|
{
"resource": ""
}
|
|
q51506
|
start
|
train
|
async function start() {
const numDimensions = 100;
const numPoints = 10000;
const data = generateData(numDimensions, numPoints);
const coordinates = await computeEmbedding(data, numPoints);
showEmbedding(coordinates);
}
|
javascript
|
{
"resource": ""
}
|
q51507
|
showEmbedding
|
train
|
function showEmbedding(data) {
const margin = {top: 20, right: 15, bottom: 60, left: 60};
const width = 800 - margin.left - margin.right;
const height = 800 - margin.top - margin.bottom;
const x = d3.scaleLinear().domain([0, 1]).range([0, width]);
const y = d3.scaleLinear().domain([0, 1]).range([height, 0]);
const chart = d3.select('body')
.append('svg')
.attr('width', width + margin.right + margin.left)
.attr('height', height + margin.top + margin.bottom)
.attr('class', 'chart');
const main =
chart.append('g')
.attr(
'transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('width', width)
.attr('height', height)
.attr('class', 'main');
const xAxis = d3.axisBottom(x);
main.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'main axis date')
.call(xAxis);
const yAxis = d3.axisLeft(y);
main.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'main axis date')
.call(yAxis);
const dots = main.append('g');
dots.selectAll('scatter-dots')
.data(data)
.enter()
.append('svg:circle')
.attr('cx', (d) => x(d[0]))
.attr('cy', (d) => y(d[1]))
.attr('stroke-width', 0.25)
.attr('stroke', '#1f77b4')
.attr('fill', 'none')
.attr('r', 5);
}
|
javascript
|
{
"resource": ""
}
|
q51508
|
extractEventHandlers
|
train
|
function extractEventHandlers(props) {
let result = {
eventHandlers: {},
options: {}
};
for (let key in props) {
if (ReactBrowserEventEmitter.registrationNameModules.hasOwnProperty(key)) {
result.eventHandlers[key] = props[key];
} else {
result.options[key] = props[key];
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q51509
|
render
|
train
|
function render(element) {
// Is the given element valid?
invariant(
ReactElement.isValidElement(element),
'render(): You must pass a valid ReactElement.'
);
const id = ReactInstanceHandles.createReactRootID(); // Creating a root id & creating the screen
const component = instantiateReactComponent(element); // Mounting the app
const transaction = ReactUpdates.ReactReconcileTransaction.getPooled();
ReactWWIDOperations.setRoot(new WorkerDomNodeStub('0', 'div', {}));
// The initial render is synchronous but any updates that happen during
// rendering, in componentWillMount or componentDidMount, will be batched
// according to the current batching strategy.
ReactUpdates.batchedUpdates(() => {
transaction.perform(() => {
component.mountComponent(id, transaction, {});
});
ReactUpdates.ReactReconcileTransaction.release(transaction);
});
return component._instance;
}
|
javascript
|
{
"resource": ""
}
|
q51510
|
train
|
function(max) {
// gives a number between 0 (inclusive) and max (exclusive)
var rand = crypto.randomBytes(1)[0];
while (rand >= 256 - (256 % max)) {
rand = crypto.randomBytes(1)[0];
}
return rand % max;
}
|
javascript
|
{
"resource": ""
}
|
|
q51511
|
onComment
|
train
|
function onComment(isBlock, text, _s, _e, sLoc, eLoc) {
var tRegex = /test\s*>\s*(.*)/i;
var aRegex = /#\s*(.*)/i;
var isTest = R.test(tRegex);
var extractTest = R.pipe(R.match(tRegex), R.last(), R.trim());
var isAssertion = R.test(aRegex);
var extractAssertion = R.pipe(R.match(aRegex), R.last(), R.trim());
var lastTestFound = R.last(tests);
var newTest;
function belongToTest(locLine, test) {
return (test === undefined) ? false : locLine - 1 === test.loc.endLine;
}
function createEmptyTest(title) {
return {
title: title || null,
loc: { startLine: sLoc.line, endLine: eLoc.line },
assertions: []
};
}
function addAssertionToTest(assertion, test) {
test.assertions.push(assertion);
test.loc.endLine = eLoc.line;
return test;
}
function setTestTitle(title, test) {
test.title = title;
return test;
}
function buildTest(test, string) {
if (isTest(string)) {
setTestTitle(extractTest(string), test);
} else if (isAssertion(string)) {
addAssertionToTest(extractAssertion(string), test);
}
return test;
}
if (!isBlock) {
if (isTest(text)) {
newTest = R.pipe(extractTest, createEmptyTest)(text);
tests.push(newTest);
} else if (isAssertion(text) && belongToTest(sLoc.line, lastTestFound)) {
addAssertionToTest(extractAssertion(text), lastTestFound);
}
}
if (isBlock && isTest(text)) {
newTest = R.reduce(buildTest, createEmptyTest(), R.split('\n', text));
tests.push(newTest);
}
}
|
javascript
|
{
"resource": ""
}
|
q51512
|
charCode
|
train
|
function charCode(chr) {
var esc = /^\\[xu](.+)/.exec(chr);
return esc ?
dec(esc[1]) :
chr.charCodeAt(chr.charAt(0) === '\\' ? 1 : 0);
}
|
javascript
|
{
"resource": ""
}
|
q51513
|
invertBmp
|
train
|
function invertBmp(range) {
var output = '';
var lastEnd = -1;
XRegExp.forEach(
range,
/(\\x..|\\u....|\\?[\s\S])(?:-(\\x..|\\u....|\\?[\s\S]))?/,
function(m) {
var start = charCode(m[1]);
if (start > (lastEnd + 1)) {
output += '\\u' + pad4(hex(lastEnd + 1));
if (start > (lastEnd + 2)) {
output += '-\\u' + pad4(hex(start - 1));
}
}
lastEnd = charCode(m[2] || m[1]);
}
);
if (lastEnd < 0xFFFF) {
output += '\\u' + pad4(hex(lastEnd + 1));
if (lastEnd < 0xFFFE) {
output += '-\\uFFFF';
}
}
return output;
}
|
javascript
|
{
"resource": ""
}
|
q51514
|
cacheInvertedBmp
|
train
|
function cacheInvertedBmp(slug) {
var prop = 'b!';
return (
unicode[slug][prop] ||
(unicode[slug][prop] = invertBmp(unicode[slug].bmp))
);
}
|
javascript
|
{
"resource": ""
}
|
q51515
|
augment
|
train
|
function augment(regex, captureNames, xSource, xFlags, isInternalOnly) {
var p;
regex[REGEX_DATA] = {
captureNames: captureNames
};
if (isInternalOnly) {
return regex;
}
// Can't auto-inherit these since the XRegExp constructor returns a nonprimitive value
if (regex.__proto__) {
regex.__proto__ = XRegExp.prototype;
} else {
for (p in XRegExp.prototype) {
// An `XRegExp.prototype.hasOwnProperty(p)` check wouldn't be worth it here, since this
// is performance sensitive, and enumerable `Object.prototype` or `RegExp.prototype`
// extensions exist on `regex.prototype` anyway
regex[p] = XRegExp.prototype[p];
}
}
regex[REGEX_DATA].source = xSource;
// Emulate the ES6 `flags` prop by ensuring flags are in alphabetical order
regex[REGEX_DATA].flags = xFlags ? xFlags.split('').sort().join('') : xFlags;
return regex;
}
|
javascript
|
{
"resource": ""
}
|
q51516
|
getNativeFlags
|
train
|
function getNativeFlags(regex) {
return hasFlagsProp ?
regex.flags :
// Explicitly using `RegExp.prototype.toString` (rather than e.g. `String` or concatenation
// with an empty string) allows this to continue working predictably when
// `XRegExp.proptotype.toString` is overridden
nativ.exec.call(/\/([a-z]*)$/i, RegExp.prototype.toString.call(regex))[1];
}
|
javascript
|
{
"resource": ""
}
|
q51517
|
runTokens
|
train
|
function runTokens(pattern, flags, pos, scope, context) {
var i = tokens.length,
leadChar = pattern.charAt(pos),
result = null,
match,
t;
// Run in reverse insertion order
while (i--) {
t = tokens[i];
if (
(t.leadChar && t.leadChar !== leadChar) ||
(t.scope !== scope && t.scope !== 'all') ||
(t.flag && flags.indexOf(t.flag) === -1)
) {
continue;
}
match = XRegExp.exec(pattern, t.regex, pos, 'sticky');
if (match) {
result = {
matchLength: match[0].length,
output: t.handler.call(context, match, scope, flags),
reparse: t.reparse
};
// Finished with token tests
break;
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q51518
|
setNatives
|
train
|
function setNatives(on) {
RegExp.prototype.exec = (on ? fixed : nativ).exec;
RegExp.prototype.test = (on ? fixed : nativ).test;
String.prototype.match = (on ? fixed : nativ).match;
String.prototype.replace = (on ? fixed : nativ).replace;
String.prototype.split = (on ? fixed : nativ).split;
features.natives = on;
}
|
javascript
|
{
"resource": ""
}
|
q51519
|
hoistFunctionDeclaration
|
train
|
function hoistFunctionDeclaration(ast, hoisteredFunctions) {
var key, child, startIndex = 0;
if (ast.body) {
var newBody = [];
if (ast.body.length > 0) { // do not hoister function declaration before J$.Fe or J$.Se
if (ast.body[0].type === 'ExpressionStatement') {
if (ast.body[0].expression.type === 'CallExpression') {
if (ast.body[0].expression.callee.object &&
ast.body[0].expression.callee.object.name === 'J$'
&& ast.body[0].expression.callee.property
&&
(ast.body[0].expression.callee.property.name === 'Se' || ast.body[0].
expression.callee.property.name === 'Fe')) {
newBody.push(ast.body[0]);
startIndex = 1;
}
}
}
}
for (var i = startIndex; i < ast.body.length; i++) {
if (ast.body[i].type === 'FunctionDeclaration') {
newBody.push(ast.body[i]);
if (newBody.length !== i + 1) {
hoisteredFunctions.push(ast.body[i].id.name);
}
}
}
for (var i = startIndex; i < ast.body.length; i++) {
if (ast.body[i].type !== 'FunctionDeclaration') {
newBody.push(ast.body[i]);
}
}
while (ast.body.length > 0) {
ast.body.pop();
}
for (var i = 0; i < newBody.length; i++) {
ast.body.push(newBody[i]);
}
} else {
//console.log(typeof ast.body);
}
for (key in ast) {
if (ast.hasOwnProperty(key)) {
child = ast[key];
if (typeof child === 'object' && child !== null && key !==
"scope") {
hoistFunctionDeclaration(child, hoisteredFunctions);
}
}
}
return ast;
}
|
javascript
|
{
"resource": ""
}
|
q51520
|
transformString
|
train
|
function transformString(code, visitorsPost, visitorsPre) {
// StatCollector.resumeTimer("parse");
// console.time("parse")
// var newAst = esprima.parse(code, {loc:true, range:true});
var newAst = acorn.parse(code, {locations: true, ecmaVersion: 6 });
// console.timeEnd("parse")
// StatCollector.suspendTimer("parse");
// StatCollector.resumeTimer("transform");
// console.time("transform")
addScopes(newAst);
var len = visitorsPost.length;
for (var i = 0; i < len; i++) {
newAst = astUtil.transformAst(newAst, visitorsPost[i], visitorsPre[i], astUtil.CONTEXT.RHS);
}
// console.timeEnd("transform")
// StatCollector.suspendTimer("transform");
// console.log(JSON.stringify(newAst,null," "));
return newAst;
}
|
javascript
|
{
"resource": ""
}
|
q51521
|
instrumentCode
|
train
|
function instrumentCode(options) {
var aret, skip = false;
var isEval = options.isEval,
code = options.code, thisIid = options.thisIid, inlineSource = options.inlineSource, url = options.url;
iidSourceInfo = {};
initializeIIDCounters(isEval);
instCodeFileName = options.instCodeFileName ? options.instCodeFileName : (options.isDirect?"eval":"evalIndirect");
origCodeFileName = options.origCodeFileName ? options.origCodeFileName : (options.isDirect?"eval":"evalIndirect");
if (sandbox.analysis && sandbox.analysis.instrumentCodePre) {
aret = sandbox.analysis.instrumentCodePre(thisIid, code, options.isDirect);
if (aret) {
code = aret.code;
skip = aret.skip;
}
}
if (!skip && typeof code === 'string' && code.indexOf(noInstr) < 0) {
try {
code = removeShebang(code);
iidSourceInfo = {};
var newAst;
if (Config.ENABLE_SAMPLING) {
newAst = transformString(code, [visitorCloneBodyPre, visitorRRPost, visitorOps, visitorMergeBodyPre], [undefined, visitorRRPre, undefined, undefined]);
} else {
newAst = transformString(code, [visitorRRPost, visitorOps], [visitorRRPre, undefined]);
}
// post-process AST to hoist function declarations (required for Firefox)
var hoistedFcts = [];
newAst = hoistFunctionDeclaration(newAst, hoistedFcts);
var newCode = esotope.generate(newAst, {comment: true ,parse: acorn.parse});
code = newCode + "\n" + noInstr + "\n";
} catch(ex) {
console.log("Failed to instrument", code);
throw ex;
}
}
var tmp = {};
tmp.nBranches = iidSourceInfo.nBranches = (condIid / IID_INC_STEP - 1) * 2;
tmp.originalCodeFileName = iidSourceInfo.originalCodeFileName = origCodeFileName;
tmp.instrumentedCodeFileName = iidSourceInfo.instrumentedCodeFileName = instCodeFileName;
if (url) {
tmp.url = iidSourceInfo.url = url;
}
if (isEval) {
tmp.evalSid = iidSourceInfo.evalSid = sandbox.sid;
tmp.evalIid = iidSourceInfo.evalIid = thisIid;
}
if (inlineSource) {
tmp.code = iidSourceInfo.code = options.code;
}
var prepend = JSON.stringify(iidSourceInfo);
var instCode;
if (options.inlineSourceMap) {
instCode = JALANGI_VAR + ".iids = " + prepend + ";\n" + code;
} else {
instCode = JALANGI_VAR + ".iids = " + JSON.stringify(tmp) + ";\n" + code;
}
if (isEval && sandbox.analysis && sandbox.analysis.instrumentCode) {
aret = sandbox.analysis.instrumentCode(thisIid, instCode, newAst, options.isDirect);
if (aret) {
instCode = aret.result;
}
}
return {code: instCode, instAST: newAst, sourceMapObject: iidSourceInfo, sourceMapString: prepend};
}
|
javascript
|
{
"resource": ""
}
|
q51522
|
R
|
train
|
function R(iid, name, val, flags) {
var aret;
var bFlags = decodeBitPattern(flags, 2); // [isGlobal, isScriptLocal]
if (sandbox.analysis && sandbox.analysis.read) {
aret = sandbox.analysis.read(iid, name, val, bFlags[0], bFlags[1]);
if (aret) {
val = aret.result;
}
}
return (lastComputedValue = val);
}
|
javascript
|
{
"resource": ""
}
|
q51523
|
A
|
train
|
function A(iid, base, offset, op, flags) {
var bFlags = decodeBitPattern(flags, 1); // [isComputed]
// avoid iid collision: make sure that iid+2 has the same source map as iid (@todo)
var oprnd1 = G(iid+2, base, offset, createBitPattern(bFlags[0], true, false));
return function (oprnd2) {
// still possible to get iid collision with a mem operation
var val = B(iid, op, oprnd1, oprnd2, createBitPattern(false, true, false));
return P(iid, base, offset, val, createBitPattern(bFlags[0], true));
};
}
|
javascript
|
{
"resource": ""
}
|
q51524
|
C2
|
train
|
function C2(iid, right) {
var aret, result;
// avoid iid collision; iid may not have a map in the sourcemap
result = B(iid+1, "===", switchLeft, right, createBitPattern(false, false, true));
if (sandbox.analysis && sandbox.analysis.conditional) {
aret = sandbox.analysis.conditional(iid, result);
if (aret) {
if (result && !aret.result) {
right = !right;
} else if (result && aret.result) {
right = switchLeft;
}
}
}
return (lastComputedValue = right);
}
|
javascript
|
{
"resource": ""
}
|
q51525
|
C
|
train
|
function C(iid, left) {
var aret;
if (sandbox.analysis && sandbox.analysis.conditional) {
aret = sandbox.analysis.conditional(iid, left);
if (aret) {
left = aret.result;
}
}
lastVal = left;
return (lastComputedValue = left);
}
|
javascript
|
{
"resource": ""
}
|
q51526
|
accumulateData
|
train
|
function accumulateData(chunk, enc, cb) {
this.data = this.data == null ? chunk : Buffer.concat([this.data,chunk]);;
cb();
}
|
javascript
|
{
"resource": ""
}
|
q51527
|
includedFile
|
train
|
function includedFile(fileName) {
var relativePath = fileName.substring(appDir.length + 1);
var result = false;
for (var i = 0; i < onlyIncludeList.length; i++) {
var prefix = onlyIncludeList[i];
if (relativePath.indexOf(prefix) === 0) {
result = true;
break;
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q51528
|
train
|
function () {
var outputDir = path.join(copyDir, jalangiRuntimeDir);
mkdirp.sync(outputDir);
var copyFile = function (srcFile) {
if (jalangiRoot) {
srcFile = path.join(jalangiRoot, srcFile);
}
var outputFile = path.join(outputDir, path.basename(srcFile));
fs.writeFileSync(outputFile, String(fs.readFileSync(srcFile)));
};
instUtil.headerSources.forEach(copyFile);
if (analyses) {
analyses.forEach(function (f) {
var outputFile = path.join(outputDir, path.basename(f));
fs.writeFileSync(outputFile, String(fs.readFileSync(f)));
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51529
|
setupConfig
|
train
|
function setupConfig(instHandler) {
var conf = J$.Config;
conf.INSTR_READ = instHandler.instrRead;
conf.INSTR_WRITE = instHandler.instrWrite;
conf.INSTR_GETFIELD = instHandler.instrGetfield;
conf.INSTR_PUTFIELD = instHandler.instrPutfield;
conf.INSTR_BINARY = instHandler.instrBinary;
conf.INSTR_PROPERTY_BINARY_ASSIGNMENT = instHandler.instrPropBinaryAssignment;
conf.INSTR_UNARY = instHandler.instrUnary;
conf.INSTR_LITERAL = instHandler.instrLiteral;
conf.INSTR_CONDITIONAL = instHandler.instrConditional;
}
|
javascript
|
{
"resource": ""
}
|
q51530
|
clearConfig
|
train
|
function clearConfig() {
var conf = J$.Config;
conf.INSTR_READ = null;
conf.INSTR_WRITE = null;
conf.INSTR_GETFIELD = null;
conf.INSTR_PUTFIELD = null;
conf.INSTR_BINARY = null;
conf.INSTR_PROPERTY_BINARY_ASSIGNMENT = null;
conf.INSTR_UNARY = null;
conf.INSTR_LITERAL = null;
conf.INSTR_CONDITIONAL = null;
}
|
javascript
|
{
"resource": ""
}
|
q51531
|
runChildAndCaptureOutput
|
train
|
function runChildAndCaptureOutput(forkedProcess) {
var stdout_parts = [], stdoutLength = 0, stderr_parts = [], stderrLength = 0,
deferred = Q.defer();
forkedProcess.stdout.on('data', function (data) {
stdout_parts.push(data);
stdoutLength += data.length;
});
forkedProcess.stderr.on('data', function (data) {
stderr_parts.push(data);
stderrLength += data.length;
});
forkedProcess.on('close', function (code) {
var child_stdout = convertToString(stdout_parts, stdoutLength),
child_stderr = convertToString(stderr_parts, stderrLength);
var resultVal = {
exitCode: code,
stdout: child_stdout,
stderr: child_stderr,
toString: function () {
return child_stderr;
}
};
if (code !== 0) {
deferred.reject(resultVal);
} else {
deferred.resolve(resultVal);
}
});
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
q51532
|
analyze
|
train
|
function analyze(script, clientAnalyses, initParam) {
var directJSScript = path.resolve(__dirname, "../commands/direct.js");
var cliArgs = [];
if (!script) {
throw new Error("must provide a script to analyze");
}
if (!clientAnalyses) {
throw new Error("must provide an analysis to run");
}
clientAnalyses.forEach(function (analysis) {
cliArgs.push('--analysis');
cliArgs.push(analysis);
});
if (initParam) {
Object.keys(initParam).forEach(function (k) {
cliArgs.push('--initParam')
cliArgs.push(k + ':' + initParam[k]);
});
}
cliArgs.push(script);
var proc = cp.fork(directJSScript, cliArgs, { silent: true });
return runChildAndCaptureOutput(proc);
}
|
javascript
|
{
"resource": ""
}
|
q51533
|
tryRemoteLog2
|
train
|
function tryRemoteLog2() {
trying = false;
remoteBuffer.shift();
if (remoteBuffer.length === 0) {
if (cb) {
cb();
cb = undefined;
}
}
tryRemoteLog();
}
|
javascript
|
{
"resource": ""
}
|
q51534
|
serialize
|
train
|
function serialize(root) {
// Stores a pointer to the most-recently encountered node representing a function or a
// top-level script. We need this stored pointer since a function expression or declaration
// has no associated IID, but we'd like to have the ASTs as entries in the table. Instead,
// we associate the AST with the IID for the corresponding function-enter or script-enter IID.
// We don't need a stack here since we only use this pointer at the next function-enter or script-enter,
// and there cannot be a nested function declaration in-between.
var parentFunOrScript = root;
var iidToAstTable = {};
function handleFun(node) {
parentFunOrScript = node;
}
var visitorPre = {
'Program':handleFun,
'FunctionDeclaration':handleFun,
'FunctionExpression':handleFun
};
function canMakeSymbolic(node) {
if (node.callee.object) {
var callee = node.callee;
// we can replace calls to J$ functions with a SymbolicReference iff they have an IID as their first
// argument. 'instrumentCode', 'getConcrete', and 'I' do not take an IID.
// TODO are we missing other cases?
if (callee.object.name === 'J$' && callee.property.name !== "instrumentCode" &&
callee.property.name !== "getConcrete" &&
callee.property.name !== "I" && node.arguments[0]) {
return true;
}
}
return false;
}
function setSerializedAST(iid, ast) {
var entry = iidToAstTable[iid];
if (!entry) {
entry = {};
iidToAstTable[iid] = entry;
}
entry.serializedAST = ast;
}
var visitorPost = {
'CallExpression':function (node) {
try {
if (node.callee.object && node.callee.object.name === 'J$' && (node.callee.property.name === 'Se' || node.callee.property.name === 'Fe')) {
// associate IID with the AST of the containing function / script
setSerializedAST(node.arguments[0].value, parentFunOrScript);
return node;
} else if (canMakeSymbolic(node)) {
setSerializedAST(node.arguments[0].value, node);
return {type:"SymbolicReference", value:node.arguments[0].value};
}
return node;
} catch (e) {
console.log(JSON.stringify(node));
throw e;
}
}
};
transformAst(root, visitorPost, visitorPre);
return iidToAstTable;
}
|
javascript
|
{
"resource": ""
}
|
q51535
|
computeTopLevelExpressions
|
train
|
function computeTopLevelExpressions(ast) {
var exprDepth = 0;
var exprDepthStack = [];
var topLevelExprs = [];
var visitorIdentifyTopLevelExprPre = {
"CallExpression":function (node) {
if (node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'Identifier' &&
node.callee.object.name === JALANGI_VAR) {
var funName = node.callee.property.name;
if ((exprDepth === 0 &&
(funName === 'A' ||
funName === 'P' ||
funName === 'G' ||
funName === 'R' ||
funName === 'W' ||
funName === 'H' ||
funName === 'T' ||
funName === 'Rt' ||
funName === 'B' ||
funName === 'U' ||
funName === 'C' ||
funName === 'C1' ||
funName === 'C2'
)) ||
(exprDepth === 1 &&
(funName === 'F' ||
funName === 'M'))) {
topLevelExprs.push(node.arguments[0].value);
}
exprDepth++;
} else if (node.callee.type === 'CallExpression' &&
node.callee.callee.type === 'MemberExpression' &&
node.callee.callee.object.type === 'Identifier' &&
node.callee.callee.object.name === JALANGI_VAR &&
(node.callee.callee.property.name === 'F' ||
node.callee.callee.property.name === 'M')) {
exprDepth++;
}
},
"FunctionExpression":function (node, context) {
exprDepthStack.push(exprDepth);
exprDepth = 0;
},
"FunctionDeclaration":function (node) {
exprDepthStack.push(exprDepth);
exprDepth = 0;
}
};
var visitorIdentifyTopLevelExprPost = {
"CallExpression":function (node) {
if (node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'Identifier' &&
node.callee.object.name === JALANGI_VAR) {
exprDepth--;
} else if (node.callee.type === 'CallExpression' &&
node.callee.callee.type === 'MemberExpression' &&
node.callee.callee.object.type === 'Identifier' &&
node.callee.callee.object.name === JALANGI_VAR &&
(node.callee.callee.property.name === 'F' ||
node.callee.callee.property.name === 'M')) {
exprDepth--;
}
return node;
},
"FunctionExpression":function (node, context) {
exprDepth = exprDepthStack.pop();
return node;
},
"FunctionDeclaration":function (node) {
exprDepth = exprDepthStack.pop();
return node;
}
};
transformAst(ast, visitorIdentifyTopLevelExprPost, visitorIdentifyTopLevelExprPre, CONTEXT.RHS);
return topLevelExprs;
}
|
javascript
|
{
"resource": ""
}
|
q51536
|
createFilenameForScript
|
train
|
function createFilenameForScript(url) {
// TODO make this much more robust
console.log("url:" + url);
var parsed = urlParser.parse(url);
if (inlineRegexp.test(url)) {
return parsed.hash.substring(1) + ".js";
} else {
return parsed.pathname.substring(parsed.pathname.lastIndexOf("/") + 1);
}
}
|
javascript
|
{
"resource": ""
}
|
q51537
|
train
|
function(uri) {
var original_segments = window.location.pathname.split('/');
var route_segments = uri.split('/');
var route_length = route_segments.length;
var params = {};
for (var i = 1; i < route_length; i++) {
if (route_segments[i].indexOf('{') !== -1) {
var name = route_segments[i].substr(1, route_segments[i].length-2);
params[name] = original_segments[i];
}
}
return params;
}
|
javascript
|
{
"resource": ""
}
|
|
q51538
|
train
|
function(uri) {
if (this._routes[uri] !== undefined) {
return uri;
}
for (var route in this._routes) {
if (this.is(route, uri)) {
return route;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q51539
|
train
|
function(uri) {
if (this.defined(uri)) {
history.pushState(null, null, uri);
var event = new CustomEvent('onRouteChange');
event.route = uri;
document.dispatchEvent(event, uri);
} else {
console.error('Route "' + uri + '" is not defined.');
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51540
|
iteratorFor
|
train
|
function iteratorFor(items) {
var iterator = {
next: function next() {
var value = items.shift();
return { done: value === undefined, value: value };
}
};
if (support.iterable) {
iterator[Symbol.iterator] = function () {
return iterator;
};
}
return iterator;
}
|
javascript
|
{
"resource": ""
}
|
q51541
|
addEventOnce
|
train
|
function addEventOnce(element, eventName, eventListener) {
var delay = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 500;
var timeout = 0;
return addEvent(element, eventName, function (e) {
clearTimeout(timeout);
timeout = setTimeout(function () {
eventListener(e);
}, delay);
});
}
|
javascript
|
{
"resource": ""
}
|
q51542
|
addEventKeyNavigation
|
train
|
function addEventKeyNavigation(element, items, itemSelectCallback) {
var itemSwitchCallback = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var currentItemIndex = null;
for (var k = 0; k < items.length; k++) {
if (items[k].hasAttribute('aria-selected')) {
currentItemIndex = k;
break;
}
}
/*let currentActiveItems = [];
for (let k = 0; k < items.length; k++) {
if (items[k].classList.contains(activeClass)) {
currentActiveItems.push(items[k]);
}
}*/
var _itemAdd = function _itemAdd() {
items[currentItemIndex].focus();
//items[currentItemIndex].classList.add(activeClass);
//items[currentItemIndex].setAttribute('aria-selected', 'true');
/*if (!BunnyElement.isInViewport(items[currentItemIndex])) {
BunnyElement.scrollTo(items[currentItemIndex], 400, -200);
}*/
//items[currentItemIndex].scrollIntoView(false);
if (itemSwitchCallback !== null) {
itemSwitchCallback(items[currentItemIndex]);
}
};
var _itemRemove = function _itemRemove() {
//items[currentItemIndex].classList.remove(activeClass);
//items[currentItemIndex].removeAttribute('aria-selected');
};
var handler = function handler(e) {
var c = e.keyCode;
var maxItemIndex = items.length - 1;
if (c === KEY_ENTER || c === KEY_SPACE) {
e.preventDefault();
if (currentItemIndex !== null) {
items[currentItemIndex].click();
itemSelectCallback(items[currentItemIndex]);
} else {
itemSelectCallback(null);
}
} else if (c === KEY_ESCAPE) {
e.preventDefault();
/*for (let k = 0; k < items.length; k++) {
if (currentActiveItems.indexOf(items[k]) === -1) {
// remove active state
items[k].classList.remove(activeClass);
items[k].removeAttribute('aria-selected');
} else {
// set active state
items[k].classList.add(activeClass);
items[k].setAttribute('aria-selected', 'true');
}
}*/
itemSelectCallback(false);
} else if (c === KEY_ARROW_UP || c === KEY_ARROW_LEFT) {
e.preventDefault();
if (currentItemIndex !== null && currentItemIndex > 0) {
_itemRemove();
currentItemIndex -= 1;
_itemAdd();
}
} else if (c === KEY_ARROW_DOWN || c === KEY_ARROW_RIGHT) {
e.preventDefault();
if (currentItemIndex === null) {
currentItemIndex = 0;
_itemAdd();
} else if (currentItemIndex < maxItemIndex) {
_itemRemove();
currentItemIndex += 1;
_itemAdd();
}
}
};
if (items.length > 0) {
element.addEventListener('keydown', handler);
}
return handler;
}
|
javascript
|
{
"resource": ""
}
|
q51543
|
checkPromise
|
train
|
function checkPromise(index) {
var res = cb(callbacks[index]); // actually calling callback
if (res instanceof Promise) {
res.then(function (cbRes) {
if (cbRes !== false) {
// keep going
if (index > 0) {
checkPromise(index - 1);
}
}
});
} else {
if (res !== false) {
// keep going
if (index > 0) {
checkPromise(index - 1);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51544
|
rgbaToColorMatrix
|
train
|
function rgbaToColorMatrix(red, green, blue) {
var alpha = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
var decToFloat = function decToFloat(value) {
return Math.round(value / 255 * 10) / 10;
};
var redFloat = decToFloat(red);
var greenFloat = decToFloat(green);
var blueFloat = decToFloat(blue);
var alphaFloat = decToFloat(alpha);
return '0 0 0 0 ' + redFloat + ' 0 0 0 0 ' + greenFloat + ' 0 0 0 0 ' + blueFloat + ' 0 0 0 1 ' + alphaFloat;
}
|
javascript
|
{
"resource": ""
}
|
q51545
|
syncUI
|
train
|
function syncUI(customSelect, defaultValue, isMultiple) {
var _this2 = this;
console.log(defaultValue, isMultiple);
var menuItems = this.getMenuItems(customSelect);
var tglBtn = this.getToggleBtn(customSelect);
var hasSelected = false;
[].forEach.call(menuItems, function (menuItem) {
if (defaultValue !== '') {
var value = _this2.getItemValue(menuItem);
if (isMultiple) {
for (var k = 0; k < defaultValue.length; k++) {
if (defaultValue[k] == value) {
_this2.setItemActive(menuItem);
hasSelected = true;
_this2.getOptionByValue(customSelect, value).selected = true;
break;
}
}
} else if (value == defaultValue) {
_this2.setItemActive(menuItem);
hasSelected = true;
_this2.getOptionByValue(customSelect, value).selected = true;
if (tglBtn.innerHTML === '') {
tglBtn.innerHTML = menuItem.innerHTML;
}
}
} else if (menuItem.hasAttribute('aria-selected')) {
_this2.setItemActive(menuItem);
hasSelected = true;
if (tglBtn.innerHTML === '') {
tglBtn.innerHTML = menuItem.innerHTML;
}
} else if (menuItem.classList.contains(_this2.Config.classNameActive)) {
_this2.setItemInactive(menuItem);
}
});
if (!hasSelected) {
this.setItemActive(menuItems[0]);
this.getHiddenSelect(customSelect).options[0].setAttribute('selected', '');
if (tglBtn.innerHTML === '') {
tglBtn.innerHTML = menuItems[0].innerHTML;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51546
|
getDefaultValue
|
train
|
function getDefaultValue(customSelect) {
var val = customSelect.getAttribute('value');
if (val === null) {
return '';
}
var firstChar = val[0];
if (firstChar === undefined) {
return '';
} else if (firstChar === '[') {
return JSON.parse(val);
}
return val;
}
|
javascript
|
{
"resource": ""
}
|
q51547
|
getSelectedValue
|
train
|
function getSelectedValue(customSelect) {
var hiddenSelect = this.UI.getHiddenSelect(customSelect);
if (this.isMultiple(customSelect)) {
var selectedOptions = [];
[].forEach.call(hiddenSelect.options, function (option) {
if (option.selected) {
selectedOptions.push(option.value);
}
});
return selectedOptions;
} else {
return hiddenSelect.options[hiddenSelect.selectedIndex].value;
}
}
|
javascript
|
{
"resource": ""
}
|
q51548
|
_attachChangeAndDefaultFileEvent
|
train
|
function _attachChangeAndDefaultFileEvent(form_id) {
var _this = this;
var elements = this._collection[form_id].getInputs();
[].forEach.call(elements, function (form_control) {
_this.__attachSingleChangeEvent(form_id, form_control);
_this.__observeSingleValueChange(form_id, form_control);
// set default file input value
if (form_control.type === 'file' && form_control.hasAttribute('value')) {
var url = form_control.getAttribute('value');
if (url !== '') {
_this.setFileFromUrl(form_id, form_control.name, url);
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
q51549
|
_parseFormControl
|
train
|
function _parseFormControl(form_id, form_control) {
var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
var type = this._collection[form_id].getInputType(form_control);
console.log(type);
// check if parser for specific input type exists and call it instead
var method = type.toLowerCase();
method = method.charAt(0).toUpperCase() + method.slice(1); // upper case first char
method = '_parseFormControl' + method;
if (value === undefined) {
method = method + 'Getter';
}
if (this[method] !== undefined) {
return this[method](form_id, form_control, value);
} else {
// call default parser
// if input with same name exists - override
if (value === undefined) {
return this._parseFormControlDefaultGetter(form_id, form_control);
} else {
this._parseFormControlDefault(form_id, form_control, value);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51550
|
download
|
train
|
function download(URL) {
var convert_to_blob = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var request = new XMLHttpRequest();
var p = new Promise(function (success, fail) {
request.onload = function () {
if (request.status === 200) {
var blob = request.response;
success(blob);
} else {
fail(request);
}
};
});
request.open('GET', URL, true);
if (convert_to_blob) {
request.responseType = 'blob';
}
request.send();
return p;
}
|
javascript
|
{
"resource": ""
}
|
q51551
|
base64ToBlob
|
train
|
function base64ToBlob(base64) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(base64.split(',')[1]);
// separate out the mime component
var mimeString = base64.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
return new Blob([ab], { type: mimeString });
}
|
javascript
|
{
"resource": ""
}
|
q51552
|
blobToBase64
|
train
|
function blobToBase64(blob) {
var reader = new FileReader();
var p = new Promise(function (success, fail) {
reader.onloadend = function () {
var base64 = reader.result;
success(base64);
};
reader.onerror = function (e) {
fail(e);
};
});
reader.readAsDataURL(blob);
return p;
}
|
javascript
|
{
"resource": ""
}
|
q51553
|
getBlobLocalURL
|
train
|
function getBlobLocalURL(blob) {
if (!(blob instanceof Blob || blob instanceof File)) {
throw new TypeError('Argument in BunnyFile.getBlobLocalURL() is not a Blob or File object');
}
return URL.createObjectURL(blob);
}
|
javascript
|
{
"resource": ""
}
|
q51554
|
scrollTo
|
train
|
function scrollTo(target) {
var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 500;
var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var rootElement = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : window;
return new Promise(function (onAnimationEnd) {
var element = void 0;
if (typeof target === 'string') {
element = document.querySelector(target);
} else if ((typeof target === 'undefined' ? 'undefined' : babelHelpers.typeof(target)) === 'object') {
element = target;
} else {
// number
element = null;
}
if (element !== null && element.offsetParent === null) {
// element is not visible, scroll to top of parent element
element = element.parentNode;
}
var start = rootElement === window ? window.pageYOffset : rootElement.scrollTop;
var distance = 0;
if (element !== null) {
distance = element.getBoundingClientRect().top;
} else {
// number
distance = target;
}
distance = distance + offset;
if (typeof duration === 'function') {
duration = duration(distance);
}
var timeStart = 0;
var timeElapsed = 0;
requestAnimationFrame(function (time) {
timeStart = time;
loop(time);
});
function setScrollYPosition(el, y) {
if (el === window) {
window.scrollTo(0, y);
} else {
el.scrollTop = y;
}
}
function loop(time) {
timeElapsed = time - timeStart;
setScrollYPosition(rootElement, easeInOutQuad(timeElapsed, start, distance, duration));
if (timeElapsed < duration) {
requestAnimationFrame(loop);
} else {
end();
}
}
function end() {
setScrollYPosition(rootElement, start + distance);
onAnimationEnd();
}
// Robert Penner's easeInOutQuad - http://robertpenner.com/easing/
function easeInOutQuad(t, b, c, d) {
t /= d / 2;
if (t < 1) return c / 2 * t * t + b;
t--;
return -c / 2 * (t * (t - 2) - 1) + b;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q51555
|
_bn_getFile
|
train
|
function _bn_getFile(input) {
// if there is custom file upload logic, for example, images are resized client-side
// generated Blobs should be assigned to fileInput._file
// and can be sent via ajax with FormData
// if file was deleted, custom field can be set to an empty string
// Bunny Validation detects if there is custom Blob assigned to file input
// and uses this file for validation instead of original read-only input.files[]
if (input._file !== undefined && input._file !== '') {
if (input._file instanceof Blob === false) {
console.error("Custom file for input " + input.name + " is not an instance of Blob");
return false;
}
return input._file;
}
return input.files[0] || false;
}
|
javascript
|
{
"resource": ""
}
|
q51556
|
image
|
train
|
function image(input) {
return new Promise(function (valid, invalid) {
if (input.getAttribute('type') === 'file' && input.getAttribute('accept').indexOf('image') > -1 && _bn_getFile(input) !== false) {
BunnyFile.getSignature(_bn_getFile(input)).then(function (signature) {
if (BunnyFile.isJpeg(signature) || BunnyFile.isPng(signature)) {
valid();
} else {
invalid({ signature: signature });
}
}).catch(function (e) {
invalid(e);
});
} else {
valid();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q51557
|
createErrorNode
|
train
|
function createErrorNode() {
var el = document.createElement(this.config.tagNameError);
el.classList.add(this.config.classError);
return el;
}
|
javascript
|
{
"resource": ""
}
|
q51558
|
removeErrorNode
|
train
|
function removeErrorNode(inputGroup) {
var el = this.getErrorNode(inputGroup);
if (el) {
el.parentNode.removeChild(el);
this.toggleErrorClass(inputGroup);
}
}
|
javascript
|
{
"resource": ""
}
|
q51559
|
removeErrorNodesFromSection
|
train
|
function removeErrorNodesFromSection(section) {
var _this = this;
[].forEach.call(this.getInputGroupsInSection(section), function (inputGroup) {
_this.removeErrorNode(inputGroup);
});
}
|
javascript
|
{
"resource": ""
}
|
q51560
|
setErrorMessage
|
train
|
function setErrorMessage(inputGroup, message) {
var errorNode = this.getErrorNode(inputGroup);
if (errorNode === false) {
// container for error message doesn't exists, create new
errorNode = this.createErrorNode();
this.toggleErrorClass(inputGroup);
this.insertErrorNode(inputGroup, errorNode);
}
// set or update error message
errorNode.textContent = message;
}
|
javascript
|
{
"resource": ""
}
|
q51561
|
getInputGroup
|
train
|
function getInputGroup(input) {
var el = input;
while ((el = el.parentNode) && !el.classList.contains(this.config.classInputGroup)) {}
return el;
}
|
javascript
|
{
"resource": ""
}
|
q51562
|
getInputsInSection
|
train
|
function getInputsInSection(node) {
var resolving = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var inputGroups = this.getInputGroupsInSection(node);
var inputs = void 0;
if (resolving) {
inputs = {
inputs: {},
invalidInputs: {},
length: 0,
unresolvedLength: 0,
invalidLength: 0
};
} else {
inputs = [];
}
for (var k = 0; k < inputGroups.length; k++) {
var input = this.getInput(inputGroups[k]);
if (input === false) {
console.error(inputGroups[k]);
throw new Error('Bunny Validation: Input group has no input');
}
if (resolving) {
inputs.inputs[k] = {
input: input,
isValid: null
};
inputs.length++;
inputs.unresolvedLength++;
} else {
inputs.push(input);
}
}
return inputs;
}
|
javascript
|
{
"resource": ""
}
|
q51563
|
getCurrentBranch
|
train
|
function getCurrentBranch(verbose) {
return Promise.resolve()
.then(execCmd.bind(null,
'git',
['symbolic-ref', 'HEAD', '-q'],
'problem getting current branch',
verbose
))
.catch(function() {
return '';
})
.then(function(result) {
return result.replace(new RegExp('^refs\/heads\/'), '');
});
}
|
javascript
|
{
"resource": ""
}
|
q51564
|
computeTextRadius
|
train
|
function computeTextRadius(lines) {
var textRadius = 0;
for (var i = 0, n = lines.length; i < n; ++i) {
var dx = lines[i].width / 2;
var dy = (Math.abs(i - n / 2 + 0.5) + 0.5) * DEFAULT_CANVAS_LINE_HEIGHT;
textRadius = Math.max(textRadius, Math.sqrt(dx * dx + dy * dy));
}
return textRadius;
}
|
javascript
|
{
"resource": ""
}
|
q51565
|
computeWords
|
train
|
function computeWords(text) {
var words = text.split(/\s+/g); // To hyphenate: /\s+|(?<=-)/
if (!words[words.length - 1]) words.pop();
if (!words[0]) words.shift();
return words;
}
|
javascript
|
{
"resource": ""
}
|
q51566
|
checkHtmlComponents
|
train
|
function checkHtmlComponents() {
var graphHTMLContainer = d3.select("#" + graph.containerId);
var taxonomyHTMLContainer = d3.select("#" + taxonomy.containerId);
var queryHTMLContainer = d3.select("#" + queryviewer.containerId);
var cypherHTMLContainer = d3.select("#" + cypherviewer.containerId);
var resultsHTMLContainer = d3.select("#" + result.containerId);
if (graphHTMLContainer.empty()) {
logger.debug("The page doesn't contain a container with ID = \"" + graph.containerId + "\" no graph area will be generated. This ID is defined in graph.containerId property.");
graph.isActive = false;
} else {
graph.isActive = true;
}
if (taxonomyHTMLContainer.empty()) {
logger.debug("The page doesn't contain a container with ID = \"" + taxonomy.containerId + "\" no taxonomy filter will be generated. This ID is defined in taxonomy.containerId property.");
taxonomy.isActive = false;
} else {
taxonomy.isActive = true;
}
if (queryHTMLContainer.empty()) {
logger.debug("The page doesn't contain a container with ID = \"" + queryviewer.containerId + "\" no query viewer will be generated. This ID is defined in queryviewer.containerId property.");
queryviewer.isActive = false;
} else {
queryviewer.isActive = true;
}
if (cypherHTMLContainer.empty()) {
logger.debug("The page doesn't contain a container with ID = \"" + cypherviewer.containerId + "\" no cypher query viewer will be generated. This ID is defined in cypherviewer.containerId property.");
cypherviewer.isActive = false;
} else {
cypherviewer.isActive = true;
}
if (resultsHTMLContainer.empty()) {
logger.debug("The page doesn't contain a container with ID = \"" + result.containerId + "\" no result area will be generated. This ID is defined in result.containerId property.");
result.isActive = false;
} else {
result.isActive = true;
}
}
|
javascript
|
{
"resource": ""
}
|
q51567
|
train
|
function (link) {
if (link.type === graph.link.LinkTypes.VALUE) {
// Links between node and list of values.
if (provider.node.isTextDisplayed(link.target)) {
// Don't display text on link if text is displayed on target node.
return "";
} else {
// No text is displayed on target node then the text is displayed on link.
return provider.node.getTextValue(link.target);
}
} else {
var targetName = "";
if (link.type === graph.link.LinkTypes.SEGMENT) {
targetName = " " + provider.node.getTextValue(link.target);
}
return link.label + targetName;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51568
|
train
|
function (link, element, attribute) {
if (link.type === graph.link.LinkTypes.VALUE) {
return "#525863";
} else {
var colorId = link.source.label + link.label + link.target.label;
var color = provider.colorScale(colorId);
if (attribute === "stroke") {
return provider.colorLuminance(color, -0.2);
}
return color;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51569
|
train
|
function (node) {
if (node.type === graph.node.NodeTypes.VALUE) {
return provider.node.getColor(node.parent);
} else {
var parentLabel = "";
if (node.hasOwnProperty("parent")) {
parentLabel = node.parent.label
}
var incomingRelation = node.parentRel || "";
var colorId = parentLabel + incomingRelation + node.label;
return provider.colorScale(colorId);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51570
|
train
|
function (node, element) {
var labelAsCSSName = node.label.replace(/[^0-9a-z\-_]/gi, '');
var cssClass = "ppt-node__" + element;
if (node.type === graph.node.NodeTypes.ROOT) {
cssClass = cssClass + "--root";
}
if (node.type === graph.node.NodeTypes.CHOOSE) {
cssClass = cssClass + "--choose";
}
if (node.type === graph.node.NodeTypes.GROUP) {
cssClass = cssClass + "--group";
}
if (node.type === graph.node.NodeTypes.VALUE) {
cssClass = cssClass + "--value";
}
if (node.value !== undefined && node.value.length > 0) {
cssClass = cssClass + "--value-selected";
}
if (node.count === 0) {
cssClass = cssClass + "--disabled";
}
return cssClass + " " + labelAsCSSName;
}
|
javascript
|
{
"resource": ""
}
|
|
q51571
|
train
|
function (node) {
var text = "";
var displayAttr = provider.node.getDisplayAttribute(node.label);
if (node.type === graph.node.NodeTypes.VALUE) {
if (displayAttr === query.NEO4J_INTERNAL_ID) {
text = "" + node.internalID;
} else {
text = "" + node.attributes[displayAttr];
}
} else {
if (node.value !== undefined && node.value.length > 0) {
if (displayAttr === query.NEO4J_INTERNAL_ID) {
var separator = "";
node.value.forEach(function (value) {
text += separator + value.internalID;
separator = " or ";
});
} else {
var separator = "";
node.value.forEach(function (value) {
text += separator + value.attributes[displayAttr];
separator = " or ";
});
}
} else {
text = node.label;
}
}
return text;
}
|
javascript
|
{
"resource": ""
}
|
|
q51572
|
train
|
function (node) {
var size = provider.node.getSize(node);
return [
{
"d": "M 0, 0 m -" + size + ", 0 a " + size + "," + size + " 0 1,0 " + 2 * size + ",0 a " + size + "," + size + " 0 1,0 -" + 2 * size + ",0",
"fill": "transparent",
"stroke": provider.node.getColor(node),
"stroke-width": "2px"
}
];
}
|
javascript
|
{
"resource": ""
}
|
|
q51573
|
getTransitionContainer
|
train
|
function getTransitionContainer(show) {
if (document.body.scrollHeight <= window.innerHeight) {
return lightboxTransitionContainer;
}
return document.body;
}
|
javascript
|
{
"resource": ""
}
|
q51574
|
loadLargerImgSrc
|
train
|
function loadLargerImgSrc(img, largerSize) {
if (img._preloaded) {
return;
}
const dummyImg = new Image();
dummyImg.srcset = img.srcset;
dummyImg.sizes = largerSize;
img._preloaded = true;
}
|
javascript
|
{
"resource": ""
}
|
q51575
|
upperBound
|
train
|
function upperBound(value, arr) {
let i = 0;
let j = arr.length - 1;
while (i < j) {
const m = (i + j) >> 1;
if (arr[m] > value) {
j = m;
} else {
i = m + 1;
}
}
return arr[i];
}
|
javascript
|
{
"resource": ""
}
|
q51576
|
sort
|
train
|
function sort(values, boxes, indices, left, right) {
if (left >= right) return;
const pivot = values[(left + right) >> 1];
let i = left - 1;
let j = right + 1;
while (true) {
do i++; while (values[i] < pivot);
do j--; while (values[j] > pivot);
if (i >= j) break;
swap(values, boxes, indices, i, j);
}
sort(values, boxes, indices, left, j);
sort(values, boxes, indices, j + 1, right);
}
|
javascript
|
{
"resource": ""
}
|
q51577
|
swap
|
train
|
function swap(values, boxes, indices, i, j) {
const temp = values[i];
values[i] = values[j];
values[j] = temp;
const k = 4 * i;
const m = 4 * j;
const a = boxes[k];
const b = boxes[k + 1];
const c = boxes[k + 2];
const d = boxes[k + 3];
boxes[k] = boxes[m];
boxes[k + 1] = boxes[m + 1];
boxes[k + 2] = boxes[m + 2];
boxes[k + 3] = boxes[m + 3];
boxes[m] = a;
boxes[m + 1] = b;
boxes[m + 2] = c;
boxes[m + 3] = d;
const e = indices[i];
indices[i] = indices[j];
indices[j] = e;
}
|
javascript
|
{
"resource": ""
}
|
q51578
|
Scaffold
|
train
|
function Scaffold(options) {
if (!(this instanceof Scaffold)) {
return new Scaffold(options);
}
Base.call(this);
this.use(utils.plugins());
this.is('scaffold');
options = options || {};
this.options = options;
this.targets = {};
if (Scaffold.isScaffold(options)) {
this.options = {};
foward(this, options);
this.addTargets(options);
return this;
} else {
foward(this, options);
}
}
|
javascript
|
{
"resource": ""
}
|
q51579
|
foward
|
train
|
function foward(app, options) {
if (typeof options.name === 'string') {
app.name = options.name;
delete options.name;
}
Scaffold.emit('scaffold', app);
emit('target', app, Scaffold);
emit('files', app, Scaffold);
}
|
javascript
|
{
"resource": ""
}
|
q51580
|
emit
|
train
|
function emit(name, a, b) {
a.on(name, b.emit.bind(b, name));
}
|
javascript
|
{
"resource": ""
}
|
q51581
|
sendTab
|
train
|
function sendTab(opt_shiftKey) {
var ev = null;
try {
ev = new KeyboardEvent('keydown', {
keyCode: 9,
which: 9,
key: 'Tab',
code: 'Tab',
keyIdentifier: 'U+0009',
shiftKey: !!opt_shiftKey,
bubbles: true
});
} catch (e) {
try {
// Internet Explorer
ev = document.createEvent('KeyboardEvent');
ev.initKeyboardEvent(
'keydown',
true,
true,
window,
'Tab',
0,
opt_shiftKey ? 'Shift' : '',
false,
'en'
)
} catch (e) {}
}
if (ev) {
try {
Object.defineProperty(ev, 'keyCode', { value: 9 });
} catch (e) {}
document.dispatchEvent(ev);
}
}
|
javascript
|
{
"resource": ""
}
|
q51582
|
train
|
function( vert, frag, prefix ){
this.ready = false;
prefix = ( prefix === undefined ) ? '' : prefix+'\n';
var gl = this.gl;
if( !( compileShader( gl, this.fShader, prefix + frag ) &&
compileShader( gl, this.vShader, prefix + vert ) ) ) {
return false;
}
gl.linkProgram(this.program);
if ( Program.debug && !gl.getProgramParameter(this.program, gl.LINK_STATUS)) {
warn(gl.getProgramInfoLog(this.program));
return false;
}
// delete old accessors
while (this.dyns.length>0) {
delete this[this.dyns.pop()];
}
this._cuid = (_UID++)|0;
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q51583
|
train
|
function() {
if( this.gl !== null ){
this.gl.deleteProgram( this.program );
this.gl.deleteShader( this.fShader );
this.gl.deleteShader( this.vShader );
this.gl = null;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51584
|
train
|
function( format, type, internal ){
this.format = format || this.gl.RGB;
this.internal = internal || this.format;
this.type = type || this.gl.UNSIGNED_BYTE;
}
|
javascript
|
{
"resource": ""
}
|
|
q51585
|
train
|
function( img ){
var gl = this.gl;
this.width = img.width;
this.height = img.height;
gl.bindTexture( T2D, this.id );
gl.texImage2D( T2D, 0, this.internal, this.format, this.type, img );
}
|
javascript
|
{
"resource": ""
}
|
|
q51586
|
train
|
function( unit ){
var gl = this.gl;
if( unit !== undefined ){
gl.activeTexture( gl.TEXTURE0 + (0|unit) );
}
gl.bindTexture( T2D, this.id );
}
|
javascript
|
{
"resource": ""
}
|
|
q51587
|
train
|
function( array ){
var gl = this.gl;
gl.bindBuffer( TGT, this.buffer );
gl.bufferData( TGT, array, this.usage );
gl.bindBuffer( TGT, null );
this.byteLength = ( array.byteLength === undefined ) ? array : array.byteLength;
this._computeLength();
}
|
javascript
|
{
"resource": ""
}
|
|
q51588
|
train
|
function( format, type, internal ){
var t = new Texture( this.gl, format, type, internal );
return this.attach( 0x8CE0, t );
}
|
javascript
|
{
"resource": ""
}
|
|
q51589
|
train
|
function( w, h ){
if( this.width !== w || this.height !== h ) {
this.width = w|0;
this.height = h|0;
this._allocate();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51590
|
_watchRuleFile
|
train
|
function _watchRuleFile(file, callback){
fs.watchFile(file, function(curr, prev){
log.warn('The rule file has been modified!');
callback();
});
}
|
javascript
|
{
"resource": ""
}
|
q51591
|
_loadResponderList
|
train
|
function _loadResponderList(responderListFilePath){
var filePath = responderListFilePath;
if(typeof filePath !== 'string'){
return null;
}
if(!fs.existsSync(responderListFilePath)){
throw new Error('File doesn\'t exist!');
}
if(!utils.isAbsolutePath(responderListFilePath)){
filePath = path.join(process.cwd(), filePath);
}
return _loadFile(filePath);
}
|
javascript
|
{
"resource": ""
}
|
q51592
|
_loadFile
|
train
|
function _loadFile(filename){
var module = require(filename);
delete require.cache[require.resolve(filename)];
return module;
}
|
javascript
|
{
"resource": ""
}
|
q51593
|
nproxy
|
train
|
function nproxy(port, options){
var nm;
if(typeof options.timeout === 'number'){
utils.reqTimeout = options.timeout;
utils.resTimeout = options.timeout;
}
if(typeof options.debug === 'boolean'){
log.isDebug = options.debug;
}
nm = require('./middlewares'); //nproxy middles
port = typeof port === 'number' ? port : DEFAULT_PORT;
app = connect();
if(typeof options.responderListFilePath !== 'undefined'){
app.use(nm.respond(options.responderListFilePath));
}
app.use(nm.forward());
httpServer = http.createServer(function(req, res){
req.type = 'http';
app(req, res);
}).listen(port);
proxyHttps();
log.info('NProxy started on ' + port + '!');
if (options.networks) {
log.info('Network interfaces:');
var interfaces = require('os').networkInterfaces();
for (var key in interfaces) {
log.info(key);
interfaces[key].forEach(function (item) {
log.info(' ' + item.address + '\t' + item.family);
});
}
}
return {
httpServer: httpServer
};
}
|
javascript
|
{
"resource": ""
}
|
q51594
|
proxyHttps
|
train
|
function proxyHttps(){
httpServer.on('connect', function(req, socket, upgradeHead){
var hostname = req.url.split(':')[0];
log.debug('Create internal https server for ' + hostname);
createInternalHttpsServer(hostname, function (err, httpsServerPort) {
if (err) {
log.error('Failed to create internal https proxy');
log.error(err);
return;
}
// get proxy https server
var netClient = net.createConnection(httpsServerPort);
netClient.on('connect', function(){
log.info('connect to https server successfully!');
socket.write( "HTTP/1.1 200 Connection established\r\nProxy-agent: Netscape-Proxy/1.1\r\n\r\n");
});
socket.on('data', function(chunk){
netClient.write(chunk);
});
socket.on('end', function(){
netClient.end();
});
socket.on('close', function(){
netClient.end();
});
socket.on('error', function(err){
log.error('socket error ' + err.message);
netClient.end();
});
netClient.on('data', function(chunk){
socket.write(chunk);
});
netClient.on('end', function(){
socket.end();
});
netClient.on('close', function(){
socket.end();
});
netClient.on('error', function(err){
log.error('netClient error ' + err.message);
socket.end();
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q51595
|
getAgentByUrl
|
train
|
function getAgentByUrl (requestUrl) {
if (!requestUrl) {
return null;
}
var parsedRequestUrl = url.parse(requestUrl);
var proxyUrl = getSystemProxyByUrl(parsedRequestUrl);
if (!proxyUrl) {
log.debug('No system proxy');
return null;
}
log.debug('Detect system proxy Url: ' + proxyUrl);
var parsedProxyUrl = url.parse(proxyUrl);
var tunnelOptions = getTunnelOptionsByProxy(parsedProxyUrl, parsedRequestUrl);
if (tunnelOptions) {
var tunnelFnName = getTunnelFnName(parsedProxyUrl, parsedRequestUrl);
log.debug('Tunnel name is ' + tunnelFnName);
return tunnel[tunnelFnName](tunnelOptions);
}
}
|
javascript
|
{
"resource": ""
}
|
q51596
|
_checkRootCA
|
train
|
function _checkRootCA () {
var caKeyFilePath = path.join(certDir, 'ca.key');
var caCrtFilePath = path.join(certDir, 'ca.crt');
var keysDir = path.join(__dirname, '..', 'keys');
if (!fs.existsSync(caKeyFilePath) || !fs.existsSync(caCrtFilePath)) {
log.debug('CA files do not exist');
log.debug('Copy CA files');
fse.copySync(path.join(keysDir, 'ca.key'), caKeyFilePath);
fse.copySync(path.join(keysDir, 'ca.crt'), caCrtFilePath);
}
}
|
javascript
|
{
"resource": ""
}
|
q51597
|
forward
|
train
|
function forward(){
return function forward(req, res, next){
var url = utils.processUrl(req);
var options = {
url: url,
method: req.method,
headers: req.headers
}
var buffers = [];
log.debug('forward: ' + url);
if(req.method === 'POST'){
req.on('data', function(chunk){
buffers.push(chunk);
});
req.on('end', function(){
options.data = Buffer.concat(buffers);
utils.request(options, function(err, data, proxyRes){
_forwardHandler(err, data, proxyRes, res);
});
});
}else{
utils.request(options, function(err, data, proxyRes){
_forwardHandler(err, data, proxyRes, res)
});
}
};
}
|
javascript
|
{
"resource": ""
}
|
q51598
|
respondFromCombo
|
train
|
function respondFromCombo(options, req, res, next){
var dir;
var src;
if(typeof options !== 'object' || typeof options === null){
log.warn('Options are invalid when responding from combo!');
next();
}
dir = typeof options.dir === 'undefined' ? null : options.dir;
src = Array.isArray(options.src) ? options.src : [];
if(dir !== null){
try{
fs.statSync(dir);
}catch(e){
throw e;
}
src = src.map(function(file){
return path.join(dir, file);
});
}
//Read the local files and concat together
if(src.length > 0){
utils.concat(src, function(err, data){
if(err){ throw err; }
res.statusCode = 200;
res.setHeader('Content-Length', data.length);
res.setHeader('Content-Type', mime.lookup(src[0]));
res.setHeader('Server', 'nproxy');
res.write(data);
res.end();
});
}
}
|
javascript
|
{
"resource": ""
}
|
q51599
|
responseTime
|
train
|
function responseTime (options) {
var opts = options || {}
if (typeof options === 'number') {
// back-compat single number argument
deprecate('number argument: use {digits: ' + JSON.stringify(options) + '} instead')
opts = { digits: options }
}
// get the function to invoke
var fn = typeof opts !== 'function'
? createSetHeader(opts)
: opts
return function responseTime (req, res, next) {
var startAt = process.hrtime()
onHeaders(res, function onHeaders () {
var diff = process.hrtime(startAt)
var time = diff[0] * 1e3 + diff[1] * 1e-6
fn(req, res, time)
})
next()
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.