_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q38900 | common | train | function common(words) {
return _.map(words, function(o) {
return o.word.toLowerCase();
}).sort();
} | javascript | {
"resource": ""
} |
q38901 | filter | train | function filter(unparsed) {
var cmds = this.commands()
, alias = this.finder.getCommandByName;
var i, l = unparsed.length;
for(i = 0;i < l;i++) {
//console.log('unparsed filter %s', unparsed[i]);
if(alias(unparsed[i], cmds)) {
unparsed.splice(i, 1);
i--;
l--;
}
}
//console.log('return %j', unparsed);
return unparsed;
} | javascript | {
"resource": ""
} |
q38902 | startUp | train | function startUp(dir) {
var config = {
jcr_root: dir,
servers: [{
host: commander.host || "http://localhost:4502",
username: commander.username || "admin",
password: commander.password || "admin"
}]
};
//create a new instance
var sling2JCR = new sling2jcr_1.Sling2JCR(config.servers);
sling2JCR.login().then(function (servers) {
//watch the files under the jcr_root folder, or any sub directory under it. Files not under a sub directory of jcr_root won't be synchronized.
watch(config.jcr_root, function (filePath) {
if (fs.existsSync(filePath)) {
if (fs.statSync(filePath).isFile()) {
sling2JCR.process(filePath);
}
}
else {
sling2JCR.process(filePath, true);
}
});
}).catch(function (error) {
console.log(error);
});
} | javascript | {
"resource": ""
} |
q38903 | crudable | train | function crudable(flowthingsWs) {
return {
create: function(obj, params, responseHandler, cb) {
if (typeof params === 'function') {
cb = responseHandler; responseHandler = params; params = {};
} else if (!params) {
params = {};
}
baseWs(flowthingsWs, this.objectType, 'create', {value: obj},
{msgId: params.msgId, responseHandler: responseHandler, cb: cb});
},
read: function(id, params, responseHandler, cb) {
if (typeof params === 'function') {
cb = responseHandler; responseHandler = params; params = {};
} else if (!params) {
params = {};
}
id = fixDropId(id, this);
baseWs(flowthingsWs, this.objectType, 'find', {id: id},
{msgId: params.msgId, responseHandler: responseHandler, cb: cb});
},
update: function(id, obj, params, responseHandler, cb) {
if (typeof params === 'function') {
cb = responseHandler; responseHandler = params; params = {};
} else if (!params) {
params = {};
}
id = fixDropId(id, this);
baseWs(flowthingsWs, this.objectType, 'update', {id: id, value: obj},
{msgId: params.msgId, responseHandler: responseHandler, cb: cb});
},
delete: function(id, params, responseHandler, cb) {
if (typeof params === 'function') {
cb = responseHandler; responseHandler = params; params = {};
} else if (!params) {
params = {};
}
id = fixDropId(id, this);
baseWs(flowthingsWs, this.objectType, this.objectType, 'delete', {id: id},
{msgId: params.msgId, responseHandler: responseHandler, cb: cb});
}
};
} | javascript | {
"resource": ""
} |
q38904 | dropCreate | train | function dropCreate(flowthingsWs) {
return {
create: function(drop, params, responseHandler, cb) {
if (typeof params === 'function') {
cb = responseHandler; responseHandler = params; params = {};
} else if (!params) {
params = {};
}
if (this.flowId.charAt(0) === '/') {
drop.path = this.flowId;
}
baseWs(flowthingsWs, this.objectType, 'create',
{flowId: this.flowId, value: drop},
{msgId: params.msgId, responseHandler: responseHandler, cb: cb});
},
};
} | javascript | {
"resource": ""
} |
q38905 | train | function(req, res, next) {
/**
* If you want to redirect to another controller, uncomment
*/
var controllers = [];
fs.readdir(__dirname + '/', function(err, files) {
if (err) {
throw err;
}
files.forEach(function(file) {
if(/\.js$/i.test(file)) {
if (file !== "AppsController.js") {
controllers.push(file.replace('Controller.js', '').toLowerCase());
}
}
});
res.render('app', {
controllers: controllers
});
});
} | javascript | {
"resource": ""
} | |
q38906 | _mkdirp | train | function _mkdirp (directory, mode, callback) {
if ("undefined" === typeof directory) {
throw new ReferenceError("missing \"directory\" argument");
}
else if ("string" !== typeof directory) {
throw new TypeError("\"directory\" argument is not a string");
}
else if ("" === directory.trim()) {
throw new Error("\"directory\" argument is empty");
}
else if ("undefined" !== typeof callback && "number" !== typeof mode) {
throw new TypeError("\"mode\" argument is not a number");
}
else if ("undefined" === typeof callback && "undefined" === typeof mode) {
throw new ReferenceError("missing \"callback\" argument");
}
else if ("function" !== typeof callback && "function" !== typeof mode) {
throw new TypeError("\"callback\" argument is not a function");
}
else {
let _callback = callback;
let _mode = mode;
if ("undefined" === typeof _callback) {
_callback = mode;
_mode = DEFAULT_OPTION;
}
isDirectoryProm(directory).then((exists) => {
return exists ? Promise.resolve() : Promise.resolve().then(() => {
const SUB_DIRECTORY = dirname(directory);
return isDirectoryProm(SUB_DIRECTORY).then((_exists) => {
return _exists ? new Promise((resolve, reject) => {
mkdir(directory, _mode, (err) => {
return err ? reject(err) : resolve();
});
}) : new Promise((resolve, reject) => {
_mkdirp(SUB_DIRECTORY, _mode, (err) => {
return err ? reject(err) : mkdir(directory, _mode, (_err) => {
return _err ? reject(_err) : resolve();
});
});
});
});
});
}).then(() => {
_callback(null);
}).catch(callback);
}
} | javascript | {
"resource": ""
} |
q38907 | diff | train | function diff(req, res) {
// defined and loaded commands
var cmds = this.execs
// map of all standard top-level commands
, map = Constants.MAP
// output multi bulk reply list
, list = []
, k;
for(k in map) {
if(!cmds[k]) list.push(k);
}
res.send(null, list);
} | javascript | {
"resource": ""
} |
q38908 | reload | train | function reload(req, res) {
var log = this.log;
if(Persistence.loading) {
return res.send(new Error('database load in progress'));
}
Persistence.load(this.state.store, this.state.conf,
function onLoad(err, time, diff, version) {
if(err) return log.warning('db reload error: %s', err.message);
log.notice(
'db reloaded by DEBUG RELOAD: %s seconds (v%s)', time, version);
}
);
res.send(null, Constants.OK);
} | javascript | {
"resource": ""
} |
q38909 | Ellipse | train | function Ellipse(x, y, width, height)
{
/**
* @member {number}
* @default 0
*/
this.x = x || 0;
/**
* @member {number}
* @default 0
*/
this.y = y || 0;
/**
* @member {number}
* @default 0
*/
this.width = width || 0;
/**
* @member {number}
* @default 0
*/
this.height = height || 0;
/**
* The type of the object, mainly used to avoid `instanceof` checks
*
* @member {number}
*/
this.type = CONST.SHAPES.ELIP;
} | javascript | {
"resource": ""
} |
q38910 | apiError | train | function apiError(err) {
var f = testProbe ? testProbe : anomaly.anomaly
f.apply(this, Array.prototype.slice.call(arguments))
} | javascript | {
"resource": ""
} |
q38911 | train | function (done) {
var root = node_path.join(__dirname, 'templates', template);
fs.exists(root, function(exists){
if(exists){
template_root = root;
}else{
template_root = node_path.join(DIR_CUSTOM_TEMPLATES, template)
}
done(null);
});
} | javascript | {
"resource": ""
} | |
q38912 | train | function (done) {
var p = clone(pkg);
delete p.devDependencies;
var content = JSON.stringify(p, null, 2);
write_if_not_exists('package.json', content, done);
} | javascript | {
"resource": ""
} | |
q38913 | extensionMatches | train | function extensionMatches (filename) {
var extname = path.extname(filename);
if (extname) {
return extname === extension;
}
return true;
} | javascript | {
"resource": ""
} |
q38914 | handleDirectoryOrFile | train | function handleDirectoryOrFile (filename) {
var absolutePath = path.join(dir, recursePath, filename),
relativePath = path.join(recursePath, filename);
if (fs.statSync(absolutePath).isDirectory()) {
find(dir, extension, relativePath).forEach(addFileToOutput);
} else {
addFileToOutput(new File(relativePath));
}
} | javascript | {
"resource": ""
} |
q38915 | listClassMethods | train | function listClassMethods (Model) {
var classMethods = Object.keys(Model.schema.statics);
for (var method in Model) {
if (!isPrivateMethod(method) && isFunction(Model[method])) {
classMethods.push(method);
}
}
return classMethods;
} | javascript | {
"resource": ""
} |
q38916 | clone | train | function clone(obj) {
if (typeof obj !== 'object') {
return obj;
}
var ret;
if (util.isArray(obj)) {
ret = [];
obj.forEach(function (val) {
ret.push(clone(val));
});
return ret;
}
ret = {};
Object.keys(obj).forEach(function (key) {
ret[key] = clone(obj[key]);
});
return ret;
} | javascript | {
"resource": ""
} |
q38917 | extend | train | function extend(a, b, noClone) { // A extends B
a = a || {};
if (typeof a !== 'object') {
return noClone ? b : clone(b);
}
if (typeof b !== 'object') {
return b;
}
if (!noClone) {
a = clone(a);
}
Object.keys(b).forEach(function (key) {
if (!a.hasOwnProperty(key) ||
(!(typeof b[key] === 'object' && b[key].length === undefined && b[key].constructor.name === 'Folder') &&
(typeof b[key] !== 'function'))) { // Simple types
a[key] = b[key];
} else { // Complex types
a[key] = extend(a[key], b[key], noClone);
}
});
return a;
} | javascript | {
"resource": ""
} |
q38918 | readCertsSync | train | function readCertsSync(paths) {
var opts = {};
if (!(paths instanceof Array))
throw new TypeError("readCertsSync expects Array argument");
switch (paths.length) {
case 1:
opts.pfx = fs.readFileSync(paths[0]);
break;
case 2:
opts.cert = fs.readFileSync(paths[0]);
opts.key = fs.readFileSync(paths[1]);
break;
default:
opts.cert = fs.readFileSync(paths[0]);
opts.key = fs.readFileSync(paths[1]);
opts.ca = [];
paths.slice(2).forEach(function(path) {
opts.ca.push(fs.readFileSync(path));
});
}
return opts;
} | javascript | {
"resource": ""
} |
q38919 | readCerts | train | function readCerts(paths, done) {
if (!(paths instanceof Array))
throw new TypeError("readCertsSync expects Array argument");
async.map(paths, fs.readFile, function(err, files) {
var opts = {};
if (err) done(err);
else switch (files.length) {
case 1:
opts.pfx = files[0];
break;
case 2:
opts.cert = files[0];
opts.key = files[1];
break;
default:
opts.cert = files[0];
opts.key = files[1];
opts.ca = files.slice(2);
}
done(null, opts);
});
} | javascript | {
"resource": ""
} |
q38920 | expressResponseError_silent | train | function expressResponseError_silent(response, message) {
let errorMessage = "there was an error in the request";
if(message)
errorMessage = message
response.json({ success: false, error: errorMessage });
} | javascript | {
"resource": ""
} |
q38921 | expressResponseError | train | function expressResponseError(response, error, message) {
let errorMessage = "there was an error in the request";
if(message)
errorMessage = message
response.json({ success: false, error: errorMessage });
console.error(error);
} | javascript | {
"resource": ""
} |
q38922 | properize | train | function properize(word, options) {
options = _.extend({inflect: false}, options);
if (!/\./.test(word)) {
word = changeCase(word);
if (options.inflect === false) {
return word;
}
return inflection.singularize(word);
}
return word;
} | javascript | {
"resource": ""
} |
q38923 | chop | train | function chop(keywords) {
return keywords.slice(0)
.reduce(function(acc, ele) {
acc = acc.concat(ele.split('-'));
return acc;
}, []);
} | javascript | {
"resource": ""
} |
q38924 | changeCase | train | function changeCase(str) {
if (str == null) return '';
str = String(str);
str = str.replace(/\./g, 'zzz')
str = str.replace(/_/g, '-')
str = str.replace(/([A-Z]+)/g, function (_, $1) {
return '-' + $1.toLowerCase();
});
str = str.replace(/[^a-z-]+/g, '-')
str = str.replace(/^[-\s]+|[-\s]+$/g, '');
str = str.replace(/zzz/g, '.');
return str;
} | javascript | {
"resource": ""
} |
q38925 | sanitize | train | function sanitize(arr, opts) {
return _.reduce(arr, function (acc, keywords) {
keywords = keywords.split(' ').filter(Boolean);
return acc.concat(keywords).map(function (keyword, i) {
if (opts && opts.sanitize) {
return opts.sanitize(keyword, i, keywords);
}
return keyword.toLowerCase();
}).sort();
}, []);
} | javascript | {
"resource": ""
} |
q38926 | uniq | train | function uniq(arr) {
if (arr == null || arr.length === 0) {
return [];
}
return _.reduce(arr, function(acc, ele) {
var letter = exclusions.singleLetters;
if (acc.indexOf(ele) === -1 && letter.indexOf(ele) === -1) {
acc.push(ele);
}
return acc;
}, []);
} | javascript | {
"resource": ""
} |
q38927 | copy | train | function copy (from, to) {
return Object.assign(
function (context) {
return function (prevConfig) {
context.copyPlugin = context.copyPlugin || {patterns: []}
// Merge the provided simple pattern into the config
context.copyPlugin = _extends({}, context.copyPlugin, {
patterns: [].concat(context.copyPlugin.patterns, [
{from: from, to: to},
]),
})
// Don't alter the config yet
return prevConfig
}
},
{post: postConfig}
)
} | javascript | {
"resource": ""
} |
q38928 | copyPattern | train | function copyPattern (pattern) {
return Object.assign(
function (context) {
return function (prevConfig) {
context.copyPlugin = context.copyPlugin || {patterns: []}
// Merge the provided advanced pattern into the config
context.copyPlugin = _extends({}, context.copyPlugin, {
patterns: [].concat(context.copyPlugin.patterns, [pattern]),
})
// Don't alter the config yet
return prevConfig
}
},
{post: postConfig}
)
} | javascript | {
"resource": ""
} |
q38929 | copyOptions | train | function copyOptions (options) {
return Object.assign(
function (context) {
return function (prevConfig) {
context.copyPlugin = context.copyPlugin || {}
// Merge the provided copy plugin config into the context
context.copyPlugin = _extends({}, context.copyPlugin, {
options: options,
})
// Don't alter the config yet
return prevConfig
}
},
{post: postConfig}
)
} | javascript | {
"resource": ""
} |
q38930 | postConfig | train | function postConfig (context, _ref) {
var merge = _ref.merge
return function (prevConfig) {
var _context$copyPlugin = context.copyPlugin,
patterns = _context$copyPlugin.patterns,
options = _context$copyPlugin.options
var plugin = new _copyWebpackPlugin2.default(patterns, options)
return merge({plugins: [plugin]})
}
} | javascript | {
"resource": ""
} |
q38931 | train | function( mElement, aArray ) {
for( var i=0; i<aArray.length; i++ )
if( aArray[i]==mElement )
return i;
return -1;
} | javascript | {
"resource": ""
} | |
q38932 | train | function() {
var v = [];
for( var i in this )
if( typeof this[i]=="function" && this[i].__virtual )
v.push( i );
if( v.length )
createClass.log( 'error', 'INCOMPLETE CLASS '+this.__className+' HAS AT LEAST ONE PURE VIRTUAL FUNCTION: '+v.join(", ") );
} | javascript | {
"resource": ""
} | |
q38933 | stringReduce | train | function stringReduce (string, reducerCallback, initialValue) {
if (string.length === 0) {
assertErr(initialValue, TypeError, 'Reduce of empty string with no initial value')
return initialValue
}
var initialValuePassed = arguments.length === 3
var result
var startIndex
if (initialValuePassed) {
// initial value, initialize reduce state
result = initialValue
startIndex = 0
} else {
// no initial value
if (string.length === 1) {
return string.charAt(0)
}
// no initial value, initialize reduce state
result = string.charAt(0)
startIndex = 1
}
for (var i = startIndex; i < string.length; i++) {
result = reducerCallback(result, string.charAt(i), i, string)
}
return result
} | javascript | {
"resource": ""
} |
q38934 | handleAny | train | function handleAny (obj) {
if (isPromiseAlike(obj)) {
return obj.then(handleAny)
} else if (isPlainObject(obj)) {
return handleObject(obj)
} else if (Object.prototype.toString.call(obj) === '[object Array]') {
return handleArray(obj)
} else {
return new Promise(function (resolve, reject) {
return resolve(obj)
})
}
} | javascript | {
"resource": ""
} |
q38935 | execute | train | function execute(req, res) {
var value = req.db.getKey(req.args[0], req);
if(value === undefined) return res.send(null, null);
var buf = dump(
{value: value}, value.rtype || Constants.TYPE_NAMES.STRING, null);
res.send(null, buf);
} | javascript | {
"resource": ""
} |
q38936 | assertFiles | train | function assertFiles(expectedNumFiles, tmpDir, callback) {
function countFiles() {
var numFiles = 0;
grunt.file.recurse(tmpDir, function(abspath, rootdir, subdir, filename) {
numFiles++;
});
return numFiles === expectedNumFiles;
}
var interval = setInterval(function() {
if (countFiles()) {
clearInterval(interval);
callback();
}
}, 100);
} | javascript | {
"resource": ""
} |
q38937 | jsonStream | train | function jsonStream(target, socket) {
// first set the channel encodeing to utf8
socket.setEncoding('utf8');
// data chunks may not contain a complete json string, thats why we store the data
var jsonBuffer = '';
// emits when new data from TCP connection is received
socket.on('data', function (chunk) {
// first add the chunk to the json buffer
jsonBuffer += chunk;
var start = 0, i;
// next find the next line end char
while ((i = jsonBuffer.indexOf('\n', start)) >= 0) {
// if one was found copy it out of the jsonBuffer string
var json = jsonBuffer.slice(start, i);
// now that we have a complete json string
// emit message with a parsed json object
target.emit('message', JSON.parse(json));
// set the starting point of next line end search
start = i + 1;
}
// when no more complete json objects exist in the jsonBuffer,
// we will slice the jsonBuffer so it only contains the uncomplete json string
jsonBuffer = jsonBuffer.slice(start);
});
} | javascript | {
"resource": ""
} |
q38938 | train | function (token, context, chain) {
var i ,
len ,
files = [] ,
output = '' ,
viewData = Object.create(context) ,
env = container.getParameter('kernel.environment') ,
data = container.get('assets.template.helper.assets')
.assets(token.files[0], token.files[1], token.files[2], false);
if (env === 'development') {
// dev environments print all of the files one-by-one
data.files.forEach(function(file) {
files.push(file + '?' + data.versionParameter + '=' + data.version);
});
} else {
// prod or test print the combined file only
files = [data.combinedFile];
}
// render the output one file at a time, respectively injecting URL into each
for (i = 0, len = files.length; i < len; i++) {
viewData.url = files[i];
output += Twig.parse.apply(this, [token.output, viewData]);
}
return {
chain: chain,
output: output
};
} | javascript | {
"resource": ""
} | |
q38939 | Module | train | function Module(id, parent) {
this.id = id
this.parent = parent;
if (parent && parent.children) {
parent.children.push(this);
}
this.children = [];
this.filename = null;
this.format = undefined;
this.loaded = false;
} | javascript | {
"resource": ""
} |
q38940 | train | function( matrix )
{
// default to empty 2d array
if ( typeof( matrix ) == "undefined" )
var matrix = []; // zero rows
// store rows for O(n) retrieval after initial
// operation. sacrifices memory efficiency
this.__rows = matrix;
this.__cols = d3.transpose(matrix);
// get the default index of an array of rows or cols
var index_arr = function(arr){
// otherwise, return an array of integers (as strings)
return d3.range(arr.length)
.map(function(a){
return String(a);
});
}
// create the default indexes
this.__index = {
"row" : index_arr(this.__rows),
"col" : index_arr(this.__cols)
};
this.rows = function() { return this.__rows; };
this.cols = function() { return this.__cols; };
return this;
} | javascript | {
"resource": ""
} | |
q38941 | plugin_parser | train | function plugin_parser(xmlPath) {
this.path = xmlPath;
this.doc = xml.parseElementtreeSync(xmlPath);
this.platforms = this.doc.findall('platform').map(function(p) {
return p.attrib.name;
});
} | javascript | {
"resource": ""
} |
q38942 | onContentChanged | train | function onContentChanged( contentStringOrObject ) {
try {
const
isString = typeof contentStringOrObject === 'string',
content = isString ? Icons.iconsBook[ contentStringOrObject ] : contentStringOrObject;
this._content = createSvgFromDefinition.call( this, content );
if ( !this._content ) return;
$.clear( this, this._content.svgRootGroup );
// Update pens' colors.
for ( const penIndex of [ 0, 1, 2, 3, 4, 5, 6, 7 ] ) {
updatePen.call( this, penIndex, this[ `pen${penIndex}` ] );
}
this.$.style.display = "";
} catch ( ex ) {
this.$.style.display = "none";
if ( this.content !== '' ) this.content = '';
}
} | javascript | {
"resource": ""
} |
q38943 | updatePen | train | function updatePen( penIndex, penColor = "0" ) {
if ( !this._content ) return;
let elementsToFill = this._content.elementsToFillPerColor[ penIndex ];
if ( !Array.isArray( elementsToFill ) ) elementsToFill = [];
let elementsToStroke = this._content.elementsToStrokePerColor[ penIndex ];
if ( !Array.isArray( elementsToStroke ) ) elementsToStroke = [];
updateColor( elementsToFill, elementsToStroke, penColor );
} | javascript | {
"resource": ""
} |
q38944 | aliasesTaken | train | function aliasesTaken (arr) {
var taken
for (var ind in arr) {
if (!arr.hasOwnProperty(ind)) continue;
if (aliasTaken(arr[ind]) !== false) return arr[ind];
}
return false;
} | javascript | {
"resource": ""
} |
q38945 | simpleChar | train | function simpleChar(character) {
return CHAR_TAB !== character &&
CHAR_LINE_FEED !== character &&
CHAR_CARRIAGE_RETURN !== character &&
CHAR_COMMA !== character &&
CHAR_LEFT_SQUARE_BRACKET !== character &&
CHAR_RIGHT_SQUARE_BRACKET !== character &&
CHAR_LEFT_CURLY_BRACKET !== character &&
CHAR_RIGHT_CURLY_BRACKET !== character &&
CHAR_SHARP !== character &&
CHAR_AMPERSAND !== character &&
CHAR_ASTERISK !== character &&
CHAR_EXCLAMATION !== character &&
CHAR_VERTICAL_LINE !== character &&
CHAR_GREATER_THAN !== character &&
CHAR_SINGLE_QUOTE !== character &&
CHAR_DOUBLE_QUOTE !== character &&
CHAR_PERCENT !== character &&
CHAR_COLON !== character &&
!ESCAPE_SEQUENCES[character] &&
!needsHexEscape(character);
} | javascript | {
"resource": ""
} |
q38946 | needsHexEscape | train | function needsHexEscape(character) {
return !((0x00020 <= character && character <= 0x00007E) ||
(0x00085 === character) ||
(0x000A0 <= character && character <= 0x00D7FF) ||
(0x0E000 <= character && character <= 0x00FFFD) ||
(0x10000 <= character && character <= 0x10FFFF));
} | javascript | {
"resource": ""
} |
q38947 | fromCodePoint | train | function fromCodePoint(cp) {
return (cp < 0x10000) ? String.fromCharCode(cp) :
String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) +
String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023));
} | javascript | {
"resource": ""
} |
q38948 | isKeyword | train | function isKeyword(id) {
switch (id.length) {
case 2:
return (id === 'if') || (id === 'in') || (id === 'do');
case 3:
return (id === 'var') || (id === 'for') || (id === 'new') ||
(id === 'try') || (id === 'let');
case 4:
return (id === 'this') || (id === 'else') || (id === 'case') ||
(id === 'void') || (id === 'with') || (id === 'enum');
case 5:
return (id === 'while') || (id === 'break') || (id === 'catch') ||
(id === 'throw') || (id === 'const') || (id === 'yield') ||
(id === 'class') || (id === 'super');
case 6:
return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
(id === 'switch') || (id === 'export') || (id === 'import');
case 7:
return (id === 'default') || (id === 'finally') || (id === 'extends');
case 8:
return (id === 'function') || (id === 'continue') || (id === 'debugger');
case 10:
return (id === 'instanceof');
default:
return false;
}
} | javascript | {
"resource": ""
} |
q38949 | scanPunctuator | train | function scanPunctuator() {
var token, str;
token = {
type: Token.Punctuator,
value: '',
lineNumber: lineNumber,
lineStart: lineStart,
start: index,
end: index
};
// Check for most common single-character punctuators.
str = source[index];
switch (str) {
case '(':
if (extra.tokenize) {
extra.openParenToken = extra.tokenValues.length;
}
++index;
break;
case '{':
if (extra.tokenize) {
extra.openCurlyToken = extra.tokenValues.length;
}
state.curlyStack.push('{');
++index;
break;
case '.':
++index;
if (source[index] === '.' && source[index + 1] === '.') {
// Spread operator: ...
index += 2;
str = '...';
}
break;
case '}':
++index;
state.curlyStack.pop();
break;
case ')':
case ';':
case ',':
case '[':
case ']':
case ':':
case '?':
case '~':
++index;
break;
default:
// 4-character punctuator.
str = source.substr(index, 4);
if (str === '>>>=') {
index += 4;
} else {
// 3-character punctuators.
str = str.substr(0, 3);
if (str === '===' || str === '!==' || str === '>>>' ||
str === '<<=' || str === '>>=') {
index += 3;
} else {
// 2-character punctuators.
str = str.substr(0, 2);
if (str === '&&' || str === '||' || str === '==' || str === '!=' ||
str === '+=' || str === '-=' || str === '*=' || str === '/=' ||
str === '++' || str === '--' || str === '<<' || str === '>>' ||
str === '&=' || str === '|=' || str === '^=' || str === '%=' ||
str === '<=' || str === '>=' || str === '=>') {
index += 2;
} else {
// 1-character punctuators.
str = source[index];
if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
++index;
}
}
}
}
}
if (index === token.start) {
throwUnexpectedToken();
}
token.end = index;
token.value = str;
return token;
} | javascript | {
"resource": ""
} |
q38950 | scanTemplate | train | function scanTemplate() {
var cooked = '', ch, start, rawOffset, terminated, head, tail, restore, unescaped;
terminated = false;
tail = false;
start = index;
head = (source[index] === '`');
rawOffset = 2;
++index;
while (index < length) {
ch = source[index++];
if (ch === '`') {
rawOffset = 1;
tail = true;
terminated = true;
break;
} else if (ch === '$') {
if (source[index] === '{') {
state.curlyStack.push('${');
++index;
terminated = true;
break;
}
cooked += ch;
} else if (ch === '\\') {
ch = source[index++];
if (!isLineTerminator(ch.charCodeAt(0))) {
switch (ch) {
case 'n':
cooked += '\n';
break;
case 'r':
cooked += '\r';
break;
case 't':
cooked += '\t';
break;
case 'u':
case 'x':
if (source[index] === '{') {
++index;
cooked += scanUnicodeCodePointEscape();
} else {
restore = index;
unescaped = scanHexEscape(ch);
if (unescaped) {
cooked += unescaped;
} else {
index = restore;
cooked += ch;
}
}
break;
case 'b':
cooked += '\b';
break;
case 'f':
cooked += '\f';
break;
case 'v':
cooked += '\v';
break;
default:
if (ch === '0') {
if (isDecimalDigit(source.charCodeAt(index))) {
// Illegal: \01 \02 and so on
throwError(Messages.TemplateOctalLiteral);
}
cooked += '\0';
} else if (isOctalDigit(ch)) {
// Illegal: \1 \2
throwError(Messages.TemplateOctalLiteral);
} else {
cooked += ch;
}
break;
}
} else {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
}
} else if (isLineTerminator(ch.charCodeAt(0))) {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
cooked += '\n';
} else {
cooked += ch;
}
}
if (!terminated) {
throwUnexpectedToken();
}
if (!head) {
state.curlyStack.pop();
}
return {
type: Token.Template,
value: {
cooked: cooked,
raw: source.slice(start + 1, index - rawOffset)
},
head: head,
tail: tail,
lineNumber: lineNumber,
lineStart: lineStart,
start: start,
end: index
};
} | javascript | {
"resource": ""
} |
q38951 | parseArrayPattern | train | function parseArrayPattern(params, kind) {
var node = new Node(), elements = [], rest, restNode;
expect('[');
while (!match(']')) {
if (match(',')) {
lex();
elements.push(null);
} else {
if (match('...')) {
restNode = new Node();
lex();
params.push(lookahead);
rest = parseVariableIdentifier(kind);
elements.push(restNode.finishRestElement(rest));
break;
} else {
elements.push(parsePatternWithDefault(params, kind));
}
if (!match(']')) {
expect(',');
}
}
}
expect(']');
return node.finishArrayPattern(elements);
} | javascript | {
"resource": ""
} |
q38952 | parsePropertyFunction | train | function parsePropertyFunction(node, paramInfo, isGenerator) {
var previousStrict, body;
isAssignmentTarget = isBindingElement = false;
previousStrict = strict;
body = isolateCoverGrammar(parseFunctionSourceElements);
if (strict && paramInfo.firstRestricted) {
tolerateUnexpectedToken(paramInfo.firstRestricted, paramInfo.message);
}
if (strict && paramInfo.stricted) {
tolerateUnexpectedToken(paramInfo.stricted, paramInfo.message);
}
strict = previousStrict;
return node.finishFunctionExpression(null, paramInfo.params, paramInfo.defaults, body, isGenerator);
} | javascript | {
"resource": ""
} |
q38953 | parseTemplateElement | train | function parseTemplateElement(option) {
var node, token;
if (lookahead.type !== Token.Template || (option.head && !lookahead.head)) {
throwUnexpectedToken();
}
node = new Node();
token = lex();
return node.finishTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail);
} | javascript | {
"resource": ""
} |
q38954 | parseGroupExpression | train | function parseGroupExpression() {
var expr, expressions, startToken, i, params = [];
expect('(');
if (match(')')) {
lex();
if (!match('=>')) {
expect('=>');
}
return {
type: PlaceHolders.ArrowParameterPlaceHolder,
params: [],
rawParams: []
};
}
startToken = lookahead;
if (match('...')) {
expr = parseRestElement(params);
expect(')');
if (!match('=>')) {
expect('=>');
}
return {
type: PlaceHolders.ArrowParameterPlaceHolder,
params: [expr]
};
}
isBindingElement = true;
expr = inheritCoverGrammar(parseAssignmentExpression);
if (match(',')) {
isAssignmentTarget = false;
expressions = [expr];
while (startIndex < length) {
if (!match(',')) {
break;
}
lex();
if (match('...')) {
if (!isBindingElement) {
throwUnexpectedToken(lookahead);
}
expressions.push(parseRestElement(params));
expect(')');
if (!match('=>')) {
expect('=>');
}
isBindingElement = false;
for (i = 0; i < expressions.length; i++) {
reinterpretExpressionAsPattern(expressions[i]);
}
return {
type: PlaceHolders.ArrowParameterPlaceHolder,
params: expressions
};
}
expressions.push(inheritCoverGrammar(parseAssignmentExpression));
}
expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
}
expect(')');
if (match('=>')) {
if (expr.type === Syntax.Identifier && expr.name === 'yield') {
return {
type: PlaceHolders.ArrowParameterPlaceHolder,
params: [expr]
};
}
if (!isBindingElement) {
throwUnexpectedToken(lookahead);
}
if (expr.type === Syntax.SequenceExpression) {
for (i = 0; i < expr.expressions.length; i++) {
reinterpretExpressionAsPattern(expr.expressions[i]);
}
} else {
reinterpretExpressionAsPattern(expr);
}
expr = {
type: PlaceHolders.ArrowParameterPlaceHolder,
params: expr.type === Syntax.SequenceExpression ? expr.expressions : [expr]
};
}
isBindingElement = false;
return expr;
} | javascript | {
"resource": ""
} |
q38955 | parsePrimaryExpression | train | function parsePrimaryExpression() {
var type, token, expr, node;
if (match('(')) {
isBindingElement = false;
return inheritCoverGrammar(parseGroupExpression);
}
if (match('[')) {
return inheritCoverGrammar(parseArrayInitializer);
}
if (match('{')) {
return inheritCoverGrammar(parseObjectInitializer);
}
type = lookahead.type;
node = new Node();
if (type === Token.Identifier) {
if (state.sourceType === 'module' && lookahead.value === 'await') {
tolerateUnexpectedToken(lookahead);
}
expr = node.finishIdentifier(lex().value);
} else if (type === Token.StringLiteral || type === Token.NumericLiteral) {
isAssignmentTarget = isBindingElement = false;
if (strict && lookahead.octal) {
tolerateUnexpectedToken(lookahead, Messages.StrictOctalLiteral);
}
expr = node.finishLiteral(lex());
} else if (type === Token.Keyword) {
if (!strict && state.allowYield && matchKeyword('yield')) {
return parseNonComputedProperty();
}
if (!strict && matchKeyword('let')) {
return node.finishIdentifier(lex().value);
}
isAssignmentTarget = isBindingElement = false;
if (matchKeyword('function')) {
return parseFunctionExpression();
}
if (matchKeyword('this')) {
lex();
return node.finishThisExpression();
}
if (matchKeyword('class')) {
return parseClassExpression();
}
throwUnexpectedToken(lex());
} else if (type === Token.BooleanLiteral) {
isAssignmentTarget = isBindingElement = false;
token = lex();
token.value = (token.value === 'true');
expr = node.finishLiteral(token);
} else if (type === Token.NullLiteral) {
isAssignmentTarget = isBindingElement = false;
token = lex();
token.value = null;
expr = node.finishLiteral(token);
} else if (match('/') || match('/=')) {
isAssignmentTarget = isBindingElement = false;
index = startIndex;
if (typeof extra.tokens !== 'undefined') {
token = collectRegex();
} else {
token = scanRegExp();
}
lex();
expr = node.finishLiteral(token);
} else if (type === Token.Template) {
expr = parseTemplateLiteral();
} else {
throwUnexpectedToken(lex());
}
return expr;
} | javascript | {
"resource": ""
} |
q38956 | parseArguments | train | function parseArguments() {
var args = [], expr;
expect('(');
if (!match(')')) {
while (startIndex < length) {
if (match('...')) {
expr = new Node();
lex();
expr.finishSpreadElement(isolateCoverGrammar(parseAssignmentExpression));
} else {
expr = isolateCoverGrammar(parseAssignmentExpression);
}
args.push(expr);
if (match(')')) {
break;
}
expectCommaSeparator();
}
}
expect(')');
return args;
} | javascript | {
"resource": ""
} |
q38957 | parseNewExpression | train | function parseNewExpression() {
var callee, args, node = new Node();
expectKeyword('new');
if (match('.')) {
lex();
if (lookahead.type === Token.Identifier && lookahead.value === 'target') {
if (state.inFunctionBody) {
lex();
return node.finishMetaProperty('new', 'target');
}
}
throwUnexpectedToken(lookahead);
}
callee = isolateCoverGrammar(parseLeftHandSideExpression);
args = match('(') ? parseArguments() : [];
isAssignmentTarget = isBindingElement = false;
return node.finishNewExpression(callee, args);
} | javascript | {
"resource": ""
} |
q38958 | parseLeftHandSideExpressionAllowCall | train | function parseLeftHandSideExpressionAllowCall() {
var quasi, expr, args, property, startToken, previousAllowIn = state.allowIn;
startToken = lookahead;
state.allowIn = true;
if (matchKeyword('super') && state.inFunctionBody) {
expr = new Node();
lex();
expr = expr.finishSuper();
if (!match('(') && !match('.') && !match('[')) {
throwUnexpectedToken(lookahead);
}
} else {
expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression);
}
for (;;) {
if (match('.')) {
isBindingElement = false;
isAssignmentTarget = true;
property = parseNonComputedMember();
expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
} else if (match('(')) {
isBindingElement = false;
isAssignmentTarget = false;
args = parseArguments();
expr = new WrappingNode(startToken).finishCallExpression(expr, args);
} else if (match('[')) {
isBindingElement = false;
isAssignmentTarget = true;
property = parseComputedMember();
expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
} else if (lookahead.type === Token.Template && lookahead.head) {
quasi = parseTemplateLiteral();
expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi);
} else {
break;
}
}
state.allowIn = previousAllowIn;
return expr;
} | javascript | {
"resource": ""
} |
q38959 | parsePostfixExpression | train | function parsePostfixExpression() {
var expr, token, startToken = lookahead;
expr = inheritCoverGrammar(parseLeftHandSideExpressionAllowCall);
if (!hasLineTerminator && lookahead.type === Token.Punctuator) {
if (match('++') || match('--')) {
// ECMA-262 11.3.1, 11.3.2
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
tolerateError(Messages.StrictLHSPostfix);
}
if (!isAssignmentTarget) {
tolerateError(Messages.InvalidLHSInAssignment);
}
isAssignmentTarget = isBindingElement = false;
token = lex();
expr = new WrappingNode(startToken).finishPostfixExpression(token.value, expr);
}
}
return expr;
} | javascript | {
"resource": ""
} |
q38960 | parseUnaryExpression | train | function parseUnaryExpression() {
var token, expr, startToken;
if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
expr = parsePostfixExpression();
} else if (match('++') || match('--')) {
startToken = lookahead;
token = lex();
expr = inheritCoverGrammar(parseUnaryExpression);
// ECMA-262 11.4.4, 11.4.5
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
tolerateError(Messages.StrictLHSPrefix);
}
if (!isAssignmentTarget) {
tolerateError(Messages.InvalidLHSInAssignment);
}
expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
isAssignmentTarget = isBindingElement = false;
} else if (match('+') || match('-') || match('~') || match('!')) {
startToken = lookahead;
token = lex();
expr = inheritCoverGrammar(parseUnaryExpression);
expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
isAssignmentTarget = isBindingElement = false;
} else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
startToken = lookahead;
token = lex();
expr = inheritCoverGrammar(parseUnaryExpression);
expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
tolerateError(Messages.StrictDelete);
}
isAssignmentTarget = isBindingElement = false;
} else {
expr = parsePostfixExpression();
}
return expr;
} | javascript | {
"resource": ""
} |
q38961 | parseConditionalExpression | train | function parseConditionalExpression() {
var expr, previousAllowIn, consequent, alternate, startToken;
startToken = lookahead;
expr = inheritCoverGrammar(parseBinaryExpression);
if (match('?')) {
lex();
previousAllowIn = state.allowIn;
state.allowIn = true;
consequent = isolateCoverGrammar(parseAssignmentExpression);
state.allowIn = previousAllowIn;
expect(':');
alternate = isolateCoverGrammar(parseAssignmentExpression);
expr = new WrappingNode(startToken).finishConditionalExpression(expr, consequent, alternate);
isAssignmentTarget = isBindingElement = false;
}
return expr;
} | javascript | {
"resource": ""
} |
q38962 | parseYieldExpression | train | function parseYieldExpression() {
var argument, expr, delegate, previousAllowYield;
argument = null;
expr = new Node();
delegate = false;
expectKeyword('yield');
if (!hasLineTerminator) {
previousAllowYield = state.allowYield;
state.allowYield = false;
delegate = match('*');
if (delegate) {
lex();
argument = parseAssignmentExpression();
} else {
if (!match(';') && !match('}') && !match(')') && lookahead.type !== Token.EOF) {
argument = parseAssignmentExpression();
}
}
state.allowYield = previousAllowYield;
}
return expr.finishYieldExpression(argument, delegate);
} | javascript | {
"resource": ""
} |
q38963 | parseAssignmentExpression | train | function parseAssignmentExpression() {
var token, expr, right, list, startToken;
startToken = lookahead;
token = lookahead;
if (!state.allowYield && matchKeyword('yield')) {
return parseYieldExpression();
}
expr = parseConditionalExpression();
if (expr.type === PlaceHolders.ArrowParameterPlaceHolder || match('=>')) {
isAssignmentTarget = isBindingElement = false;
list = reinterpretAsCoverFormalsList(expr);
if (list) {
firstCoverInitializedNameError = null;
return parseArrowFunctionExpression(list, new WrappingNode(startToken));
}
return expr;
}
if (matchAssign()) {
if (!isAssignmentTarget) {
tolerateError(Messages.InvalidLHSInAssignment);
}
// ECMA-262 12.1.1
if (strict && expr.type === Syntax.Identifier) {
if (isRestrictedWord(expr.name)) {
tolerateUnexpectedToken(token, Messages.StrictLHSAssignment);
}
if (isStrictModeReservedWord(expr.name)) {
tolerateUnexpectedToken(token, Messages.StrictReservedWord);
}
}
if (!match('=')) {
isAssignmentTarget = isBindingElement = false;
} else {
reinterpretExpressionAsPattern(expr);
}
token = lex();
right = isolateCoverGrammar(parseAssignmentExpression);
expr = new WrappingNode(startToken).finishAssignmentExpression(token.value, expr, right);
firstCoverInitializedNameError = null;
}
return expr;
} | javascript | {
"resource": ""
} |
q38964 | parseExpression | train | function parseExpression() {
var expr, startToken = lookahead, expressions;
expr = isolateCoverGrammar(parseAssignmentExpression);
if (match(',')) {
expressions = [expr];
while (startIndex < length) {
if (!match(',')) {
break;
}
lex();
expressions.push(isolateCoverGrammar(parseAssignmentExpression));
}
expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
}
return expr;
} | javascript | {
"resource": ""
} |
q38965 | parseStatementListItem | train | function parseStatementListItem() {
if (lookahead.type === Token.Keyword) {
switch (lookahead.value) {
case 'export':
if (state.sourceType !== 'module') {
tolerateUnexpectedToken(lookahead, Messages.IllegalExportDeclaration);
}
return parseExportDeclaration();
case 'import':
if (state.sourceType !== 'module') {
tolerateUnexpectedToken(lookahead, Messages.IllegalImportDeclaration);
}
return parseImportDeclaration();
case 'const':
return parseLexicalDeclaration({inFor: false});
case 'function':
return parseFunctionDeclaration(new Node());
case 'class':
return parseClassDeclaration();
}
}
if (matchKeyword('let') && isLexicalDeclaration()) {
return parseLexicalDeclaration({inFor: false});
}
return parseStatement();
} | javascript | {
"resource": ""
} |
q38966 | parseLexicalBinding | train | function parseLexicalBinding(kind, options) {
var init = null, id, node = new Node(), params = [];
id = parsePattern(params, kind);
// ECMA-262 12.2.1
if (strict && id.type === Syntax.Identifier && isRestrictedWord(id.name)) {
tolerateError(Messages.StrictVarName);
}
if (kind === 'const') {
if (!matchKeyword('in') && !matchContextualKeyword('of')) {
expect('=');
init = isolateCoverGrammar(parseAssignmentExpression);
}
} else if ((!options.inFor && id.type !== Syntax.Identifier) || match('=')) {
expect('=');
init = isolateCoverGrammar(parseAssignmentExpression);
}
return node.finishVariableDeclarator(id, init);
} | javascript | {
"resource": ""
} |
q38967 | parseIfStatement | train | function parseIfStatement(node) {
var test, consequent, alternate;
expectKeyword('if');
expect('(');
test = parseExpression();
expect(')');
consequent = parseStatement();
if (matchKeyword('else')) {
lex();
alternate = parseStatement();
} else {
alternate = null;
}
return node.finishIfStatement(test, consequent, alternate);
} | javascript | {
"resource": ""
} |
q38968 | parseDoWhileStatement | train | function parseDoWhileStatement(node) {
var body, test, oldInIteration;
expectKeyword('do');
oldInIteration = state.inIteration;
state.inIteration = true;
body = parseStatement();
state.inIteration = oldInIteration;
expectKeyword('while');
expect('(');
test = parseExpression();
expect(')');
if (match(';')) {
lex();
}
return node.finishDoWhileStatement(body, test);
} | javascript | {
"resource": ""
} |
q38969 | parseContinueStatement | train | function parseContinueStatement(node) {
var label = null, key;
expectKeyword('continue');
// Optimize the most common form: 'continue;'.
if (source.charCodeAt(startIndex) === 0x3B) {
lex();
if (!state.inIteration) {
throwError(Messages.IllegalContinue);
}
return node.finishContinueStatement(null);
}
if (hasLineTerminator) {
if (!state.inIteration) {
throwError(Messages.IllegalContinue);
}
return node.finishContinueStatement(null);
}
if (lookahead.type === Token.Identifier) {
label = parseVariableIdentifier();
key = '$' + label.name;
if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
throwError(Messages.UnknownLabel, label.name);
}
}
consumeSemicolon();
if (label === null && !state.inIteration) {
throwError(Messages.IllegalContinue);
}
return node.finishContinueStatement(label);
} | javascript | {
"resource": ""
} |
q38970 | parseReturnStatement | train | function parseReturnStatement(node) {
var argument = null;
expectKeyword('return');
if (!state.inFunctionBody) {
tolerateError(Messages.IllegalReturn);
}
// 'return' followed by a space and an identifier is very common.
if (source.charCodeAt(lastIndex) === 0x20) {
if (isIdentifierStart(source.charCodeAt(lastIndex + 1))) {
argument = parseExpression();
consumeSemicolon();
return node.finishReturnStatement(argument);
}
}
if (hasLineTerminator) {
// HACK
return node.finishReturnStatement(null);
}
if (!match(';')) {
if (!match('}') && lookahead.type !== Token.EOF) {
argument = parseExpression();
}
}
consumeSemicolon();
return node.finishReturnStatement(argument);
} | javascript | {
"resource": ""
} |
q38971 | parseWithStatement | train | function parseWithStatement(node) {
var object, body;
if (strict) {
tolerateError(Messages.StrictModeWith);
}
expectKeyword('with');
expect('(');
object = parseExpression();
expect(')');
body = parseStatement();
return node.finishWithStatement(object, body);
} | javascript | {
"resource": ""
} |
q38972 | parseSwitchCase | train | function parseSwitchCase() {
var test, consequent = [], statement, node = new Node();
if (matchKeyword('default')) {
lex();
test = null;
} else {
expectKeyword('case');
test = parseExpression();
}
expect(':');
while (startIndex < length) {
if (match('}') || matchKeyword('default') || matchKeyword('case')) {
break;
}
statement = parseStatementListItem();
consequent.push(statement);
}
return node.finishSwitchCase(test, consequent);
} | javascript | {
"resource": ""
} |
q38973 | parseThrowStatement | train | function parseThrowStatement(node) {
var argument;
expectKeyword('throw');
if (hasLineTerminator) {
throwError(Messages.NewlineAfterThrow);
}
argument = parseExpression();
consumeSemicolon();
return node.finishThrowStatement(argument);
} | javascript | {
"resource": ""
} |
q38974 | parseCatchClause | train | function parseCatchClause() {
var param, params = [], paramMap = {}, key, i, body, node = new Node();
expectKeyword('catch');
expect('(');
if (match(')')) {
throwUnexpectedToken(lookahead);
}
param = parsePattern(params);
for (i = 0; i < params.length; i++) {
key = '$' + params[i].value;
if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
tolerateError(Messages.DuplicateBinding, params[i].value);
}
paramMap[key] = true;
}
// ECMA-262 12.14.1
if (strict && isRestrictedWord(param.name)) {
tolerateError(Messages.StrictCatchVariable);
}
expect(')');
body = parseBlock();
return node.finishCatchClause(param, body);
} | javascript | {
"resource": ""
} |
q38975 | parseFunctionSourceElements | train | function parseFunctionSourceElements() {
var statement, body = [], token, directive, firstRestricted,
oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesisCount,
node = new Node();
expect('{');
while (startIndex < length) {
if (lookahead.type !== Token.StringLiteral) {
break;
}
token = lookahead;
statement = parseStatementListItem();
body.push(statement);
if (statement.expression.type !== Syntax.Literal) {
// this is not directive
break;
}
directive = source.slice(token.start + 1, token.end - 1);
if (directive === 'use strict') {
strict = true;
if (firstRestricted) {
tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
}
} else {
if (!firstRestricted && token.octal) {
firstRestricted = token;
}
}
}
oldLabelSet = state.labelSet;
oldInIteration = state.inIteration;
oldInSwitch = state.inSwitch;
oldInFunctionBody = state.inFunctionBody;
oldParenthesisCount = state.parenthesizedCount;
state.labelSet = {};
state.inIteration = false;
state.inSwitch = false;
state.inFunctionBody = true;
state.parenthesizedCount = 0;
while (startIndex < length) {
if (match('}')) {
break;
}
body.push(parseStatementListItem());
}
expect('}');
state.labelSet = oldLabelSet;
state.inIteration = oldInIteration;
state.inSwitch = oldInSwitch;
state.inFunctionBody = oldInFunctionBody;
state.parenthesizedCount = oldParenthesisCount;
return node.finishBlockStatement(body);
} | javascript | {
"resource": ""
} |
q38976 | parseModuleSpecifier | train | function parseModuleSpecifier() {
var node = new Node();
if (lookahead.type !== Token.StringLiteral) {
throwError(Messages.InvalidModuleSpecifier);
}
return node.finishLiteral(lex());
} | javascript | {
"resource": ""
} |
q38977 | parseScriptBody | train | function parseScriptBody() {
var statement, body = [], token, directive, firstRestricted;
while (startIndex < length) {
token = lookahead;
if (token.type !== Token.StringLiteral) {
break;
}
statement = parseStatementListItem();
body.push(statement);
if (statement.expression.type !== Syntax.Literal) {
// this is not directive
break;
}
directive = source.slice(token.start + 1, token.end - 1);
if (directive === 'use strict') {
strict = true;
if (firstRestricted) {
tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
}
} else {
if (!firstRestricted && token.octal) {
firstRestricted = token;
}
}
}
while (startIndex < length) {
statement = parseStatementListItem();
/* istanbul ignore if */
if (typeof statement === 'undefined') {
break;
}
body.push(statement);
}
return body;
} | javascript | {
"resource": ""
} |
q38978 | train | function(){
// Initialize the API object
if (this.mainView) {
this.mainView.clear();
}
var url = this.options.url;
if (url && url.indexOf('http') !== 0) {
url = this.buildUrl(window.location.href.toString(), url);
}
if(this.api) {
this.options.authorizations = this.api.clientAuthorizations.authz;
}
this.options.url = url;
this.headerView.update(url);
this.api = new SwaggerClient(this.options);
} | javascript | {
"resource": ""
} | |
q38979 | flushCurrentCell | train | function flushCurrentCell() {
if (currentCell.children.length > 0) {
cells.push(currentCell);
currentCell = N.tag("div");
cellsWeights.push(1);
totalWeight++;
}
} | javascript | {
"resource": ""
} |
q38980 | readFileContent | train | function readFileContent(fileName){
try{
return(fs.readFileSync(fileName , "utf-8"));
}catch(e){
console.log("---readFileContent-- Error reading file "+fileName);
console.log(e);
return null;
}
} | javascript | {
"resource": ""
} |
q38981 | output | train | function output (consumer, template, params, getDefault) {
return new Output (consumer, template, params, getDefault);
} | javascript | {
"resource": ""
} |
q38982 | train | function (xhr, options, promise) {
console.log(NAME, '_initXHR');
var instance = this,
url = options.url,
method = options.method || GET,
headers = options.headers || {}, // all request will get some headers
async = !options.sync,
data = options.data,
reject = promise.reject,
sendPayload;
// xhr will be null in case of a CORS-request when no CORS is possible
if (!xhr) {
console.error(NAME, '_initXHR fails: '+ERROR_NO_XHR);
reject(new Error(ERROR_NO_XHR));
return;
}
console.log(NAME, '_initXHR succesfully created '+(xhr._isXHR2 ? 'XMLHttpRequest2' : (xhr._isXDR ? 'XDomainRequest' : 'XMLHttpRequest1'))+'-instance');
// method-name should be in uppercase:
method = method.toUpperCase();
// in case of BODY-method: eliminate any data behind querystring:
// else: append data-object behind querystring
if (BODY_METHODS[method]) {
url = url.split('?'); // now url is an array
url = url[0]; // now url is a String again
}
else if (data && (headers[CONTENT_TYPE]!==MIME_BLOB)) {
url += ((url.indexOf('?') > 0) ? '&' : '?') + instance._toQueryString(data);
}
xhr.open(method, url, async);
// xhr.responseType = options.responseType || 'text';
options.withCredentials && (xhr.withCredentials=true);
// more initialisation might be needed by extended modules:
instance._xhrInitList.each(
function(fn) {
fn(xhr, promise, headers, method);
}
);
if (BODY_METHODS[method] && data) {
if (headers[CONTENT_TYPE]===MIME_BLOB) {
if (!xhr._isXDR) {
sendPayload = data;
}
}
else {
sendPayload = ((headers[CONTENT_TYPE]===MIME_JSON) || xhr._isXDR) ? JSON.stringify(data) : instance._toQueryString(data);
}
}
// send the request:
xhr.send(sendPayload);
console.log(NAME, 'xhr send to '+url+' with method '+method);
// now add xhr.abort() to the promise, so we can call from within the returned promise-instance
promise.abort = function() {
console.log(NAME, 'xhr aborted');
reject(new Error(ABORTED));
xhr._aborted = true; // must be set: IE9 won't allow to read anything on xhr after being aborted
xhr.abort();
};
// in case synchronous transfer: force an xhr.onreadystatechange:
async || xhr.onreadystatechange();
} | javascript | {
"resource": ""
} | |
q38983 | train | function(xhr, promise, headers, method) {
// XDR cannot set requestheaders, only XHR:
if (!xhr._isXDR) {
console.log(NAME, '_setHeaders');
var name;
if ((method!=='POST') && (method!=='PUT')) {
// force GET-request to make a request instead of using cache (like IE does):
headers['If-Modified-Since'] = 'Wed, 15 Nov 1995 01:00:00 GMT';
// header 'Content-Type' should only be set with POST or PUT requests:
delete headers[CONTENT_TYPE];
}
// set all headers
for (name in headers) {
xhr.setRequestHeader(name, headers[name]);
}
// in case of POST or PUT method: always make sure 'Content-Type' is specified
((method!=='POST') && (method!=='PUT')) || (headers && (CONTENT_TYPE in headers)) || xhr.setRequestHeader(CONTENT_TYPE, DEF_CONTENT_TYPE_POST);
}
} | javascript | {
"resource": ""
} | |
q38984 | train | function(data) {
var paramArray = [],
key, value;
// TODO: use `object` module
for (key in data) {
value = data[key];
key = ENCODE_URI_COMPONENT(key);
paramArray.push((value === null) ? key : (key + '=' + ENCODE_URI_COMPONENT(value)));
}
console.log(NAME, '_toQueryString --> '+paramArray.join('&'));
return paramArray.join('&');
} | javascript | {
"resource": ""
} | |
q38985 | AnalyticsEventEmitter | train | function AnalyticsEventEmitter(logger, utils, CONSTANT, onErrorCallback, optionalArguments, serviceName) {
'use strict';
this.logger = logger || {};
this.utils = utils || {};
this.CONSTANT = CONSTANT || {};
optionalArguments = optionalArguments || {};
this.settings = optionalArguments.settings;
this.reportEventDelay = optionalArguments.reportEventInterval;
if(serviceName) {
this.networkRequestServiceName = serviceName;
}
// Register onErrorCallback callback
this.on('error', onErrorCallback || function (err) {
this.logger.log('Emitted an error event: ' + err);
});
} | javascript | {
"resource": ""
} |
q38986 | train | function (types) {
that.logger.logEnter('callback in loadEventTypes, types:\n' + JSON.stringify(types));
// The "raw" event type data has a deeply-nested structure and it
// contains a bunch of stuff we're not interested in. We'll just
// store the names of each type's properties.
Object.keys(types).forEach(function (typeName) {
if (types[typeName].properties) {
eventTypes[typeName] = Object.keys(types[typeName].properties);
}
});
that.logger.log('eventTypes:\n' + JSON.stringify(eventTypes));
if (process.env.TESTONLY_EMIT_INTERNAL_EVENTS) {
that.emit(that.CONSTANT.internal_event_load_types_done);
}
// Now the event buffer can begin processing events.
eventBuffer.ready();
that.logger.logExit('callback in loadEventTypes');
} | javascript | {
"resource": ""
} | |
q38987 | train | function (filePath, options)
{
gulpUtil.log(gulpUtil.colors.blue("jsHint"), pathHelper.makeRelative(filePath));
var jsHintConfig = jsHintConfigHelper.getRules(xtend({
lookup: false,
esnext: false
}, options));
gulp.src(filePath)
.pipe(plumber())
.pipe(jshint(jsHintConfig))
.pipe(jshint.reporter(jshintStylish));
} | javascript | {
"resource": ""
} | |
q38988 | moveETP2End | train | function moveETP2End(config) {
if (!ExtractTextPlugin) return
const etps = config.plugins.filter(val => val instanceof ExtractTextPlugin)
_.chain(config.plugins)
.pullAll(etps)
.push(...etps)
.value()
} | javascript | {
"resource": ""
} |
q38989 | defineGlobalVars | train | function defineGlobalVars(runtimeConfig, isDebug) {
const globals = Object.assign({}, runtimeConfig.globals, {
APP_DEBUG_MODE: isDebug || !!runtimeConfig.debuggable
})
return new webpack.DefinePlugin(globals)
} | javascript | {
"resource": ""
} |
q38990 | assertContext | train | function assertContext() {
return new Promise(function(resolve, reject) {
// Check if we're in an active session
let d = process.domain
if (d == null ||
d.context == null ||
d.context.bardo == null) {
// Begin the session before proceeding
return begin().then((ctx) => {
resolve(ctx)
}).catch(reject)
}
// Continue onwards with our active domain
return resolve(d.context.bardo)
})
} | javascript | {
"resource": ""
} |
q38991 | execute_ | train | function execute_(ctx, statement, values) {
return new Promise(function(resolve, reject) {
if (/^begin/i.test(statement)) {
// If this is a `BEGIN` statement; put us in a transaction
ctx.inTransaction = true
} else if (/^(commit|rollback)/i.test(statement)) {
// Else if this is a `COMMIT` or `ROLLBACK` statement;
// leave the transaction
ctx.inTransaction = false
}
// Default values to an empty array
values = values || []
// TRACE: Get the current clock time
let now = microtime.now()
// Send the statement
ctx.client.query(statement, values, function(err, result) {
// Handle and reject if an error occurred
if (err) return reject(err)
// TRACE: Calculate the elasped time and log the SQL statement
let elapsed = +((microtime.now() - now) / 1000).toFixed(2)
log.trace({
id: ctx.id,
elapsed: `${elapsed}ms`,
values: (values && values.length) ? values : undefined
}, statement)
// DEBUG: Increment the per-session counters
ctx.elapsed += elapsed
ctx.count += 1
// Parse (and resolve) the result proxy
if (!_.isFinite(result.rowCount)) {
// This doesn't support a sane row count resolve with nothing
resolve()
} else if (result.fields == null) {
// Resolve the row count
resolve(result.rowCount)
} else {
// Resolve the rows
resolve(result.rows)
}
})
})
} | javascript | {
"resource": ""
} |
q38992 | issueCountReporter | train | function issueCountReporter (file)
{
if (!file.scsslint.success)
{
totalIssues += file.scsslint.issues.length;
}
scssLintReporter.defaultReporter(file);
} | javascript | {
"resource": ""
} |
q38993 | compileSingleFile | train | function compileSingleFile (filePath, isDebug, options)
{
var outputPath = "./" + path.dirname(filePath).replace("assets/scss", "public/css");
gulpUtil.log(gulpUtil.colors.blue("Sass"), pathHelper.makeRelative(filePath), " -> ", outputPath + "/" + path.basename(filePath).replace(/\.scss$/, ".css"));
var innerPipe = gulp.src(filePath)
.pipe(plumber());
if (isDebug)
{
innerPipe = innerPipe
.pipe(watch(filePath));
}
innerPipe = innerPipe
.pipe(sass({
errLogToConsole: true,
includePaths: [
process.env.PWD
]
}))
.pipe(autoprefixer({
browsers: options.browsers,
cascade: false
}));
// if not in debug mode, minify
if (!isDebug)
{
innerPipe = innerPipe.pipe(cssMin({
processImport: false
}));
}
// write auto prefixer
return innerPipe
.pipe(gulp.dest(outputPath));
} | javascript | {
"resource": ""
} |
q38994 | lintFiles | train | function lintFiles (src)
{
gulp.src(src)
.pipe(scssLint({
config: __dirname + "/../config/scss-lint.yml",
customReport: issueCountReporter
}))
.on('error', function (error)
{
gulpUtil.log(gulpUtil.colors.red('An error has occurred while executing scss-lint: ' + error.message));
})
.on('end', reportTotalIssueCount);
} | javascript | {
"resource": ""
} |
q38995 | startWatcherForLinting | train | function startWatcherForLinting (src)
{
watch(src,
function (file)
{
if (file.path)
{
lintFiles(file.path);
}
}
);
} | javascript | {
"resource": ""
} |
q38996 | compileAllFiles | train | function compileAllFiles (src, isDebug, options)
{
glob(src,
function (err, files)
{
if (err) throw err;
for (var i = 0, l = files.length; i < l; i++)
{
// only start compilation at root files
if (sassHelpers.isRootFile(files[i]))
{
compileSingleFile(files[i], isDebug, options);
}
}
}
);
} | javascript | {
"resource": ""
} |
q38997 | makeModule | train | function makeModule(index) {
var stored, src, srcPath, relpath;
// Prepare module
var module = new Module({
uid: index
,req: []
,path: index
,relpath: null
,isNodeModule: false
,isAsyncModule: arequirePath === index
,arequirePath: arequirePath
,index: index
});
if(~module.path.indexOf('/node_modules/')) module.isNodeModule = true;
relpath = path.relative(process.cwd(), module.path);
relpath = !/^\./.test(relpath) ? './' + relpath : relpath;
module.relpath = relpath;
debug('makeModule for %s', relpath);
// Check for stored version of this path
stored = _.find(modules, function(p) {
return module.path === p.path;
});
if(stored) {
debug('allready stored : return (absolute path match)');
return stored;
}
// Read source
src = fs.readFileSync(module.path, 'utf8');
module.mtime = fs.statSync(module.path).mtime;
module.uid = getUID({src: src, path:module.path, options: options});
// Check for stored version with same uid
stored = _.find(modules, function(p) {
return module.uid === p.uid;
});
if(stored) {
debug('allready stored : return (md5 hash match)');
return stored;
}
// Save module
modules.push(module);
// Do not parse ?
module.notparsed = _.find(noparse, function(np) {
if(np instanceof RegExp) {
return np.test(module.path);
} else if ('string' == typeof np) {
return minimatch(module.path, np);
} else if ('function' == typeof np) {
return np(module.path, module);
} else {
return false;
}
});
// Parse
if(module.notparsed) {
debug(' no parse');
} else {
debug(' run parse');
src = parse(src, module, makeModule, options);
}
// Store the module source :
module.source = src;
// Return the module object
debug('end %s', relpath);
return module;
} | javascript | {
"resource": ""
} |
q38998 | update | train | function update (client) {
return function update (options) {
options = options || {};
const req = {
url: `${client.baseUrl}/rest/applications/${options.variantId}/installations/${options.installation.id}`,
body: options.installation,
method: 'PUT'
};
return request(client, req)
.then((response) => {
if (response.resp.statusCode !== 204) {
return Promise.reject(response.body);
}
return Promise.resolve(response.body);
});
};
} | javascript | {
"resource": ""
} |
q38999 | BaseTexture | train | function BaseTexture(source, scaleMode, resolution)
{
EventEmitter.call(this);
this.uuid = utils.uuid();
/**
* The Resolution of the texture.
*
* @member {number}
*/
this.resolution = resolution || 1;
/**
* The width of the base texture set when the image has loaded
*
* @member {number}
* @readOnly
*/
this.width = 100;
/**
* The height of the base texture set when the image has loaded
*
* @member {number}
* @readOnly
*/
this.height = 100;
// TODO docs
// used to store the actual dimensions of the source
/**
* Used to store the actual width of the source of this texture
*
* @member {number}
* @readOnly
*/
this.realWidth = 100;
/**
* Used to store the actual height of the source of this texture
*
* @member {number}
* @readOnly
*/
this.realHeight = 100;
/**
* The scale mode to apply when scaling this texture
*
* @member {{number}}
* @default scaleModes.LINEAR
*/
this.scaleMode = scaleMode || CONST.SCALE_MODES.DEFAULT;
/**
* Set to true once the base texture has successfully loaded.
*
* This is never true if the underlying source fails to load or has no texture data.
*
* @member {boolean}
* @readOnly
*/
this.hasLoaded = false;
/**
* Set to true if the source is currently loading.
*
* If an Image source is loading the 'loaded' or 'error' event will be
* dispatched when the operation ends. An underyling source that is
* immediately-available bypasses loading entirely.
*
* @member {boolean}
* @readonly
*/
this.isLoading = false;
/**
* The image source that is used to create the texture.
*
* TODO: Make this a setter that calls loadSource();
*
* @member {Image|Canvas}
* @readonly
*/
this.source = null; // set in loadSource, if at all
/**
* Controls if RGB channels should be pre-multiplied by Alpha (WebGL only)
*
* @member {boolean}
* @default true
*/
this.premultipliedAlpha = true;
/**
* @member {string}
*/
this.imageUrl = null;
/**
* Wether or not the texture is a power of two, try to use power of two textures as much as you can
* @member {boolean}
* @private
*/
this.isPowerOfTwo = false;
// used for webGL
/**
*
* Set this to true if a mipmap of this texture needs to be generated. This value needs to be set before the texture is used
* Also the texture must be a power of two size to work
*
* @member {boolean}
*/
this.mipmap = false;
/**
* A map of renderer IDs to webgl textures
*
* @member {object<number, WebGLTexture>}
* @private
*/
this._glTextures = [];
// if no source passed don't try to load
if (source)
{
this.loadSource(source);
}
/**
* Fired when a not-immediately-available source finishes loading.
*
* @event loaded
* @memberof BaseTexture#
* @protected
*/
/**
* Fired when a not-immediately-available source fails to load.
*
* @event error
* @memberof BaseTexture#
* @protected
*/
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.