_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q62700
|
getPrevMap
|
test
|
function getPrevMap(from) {
if (typeof options.map.prev === 'string') {
var mapPath = options.map.prev + path.basename(from) + '.map';
if (grunt.file.exists(mapPath)) {
return grunt.file.read(mapPath);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q62701
|
test
|
function (req, res, next) {
if(req.url.indexOf('.') === -1 && req.url.indexOf(startDir) > -1){
req.url = startPath;
}
return next();
}
|
javascript
|
{
"resource": ""
}
|
|
q62702
|
parseIPv4
|
test
|
function parseIPv4(addr) {
if (typeof(addr) !== 'string')
throw new TypeError('addr (string) is required');
var octets = addr.split(/\./).map(function (octet) {
return (parseInt(octet, 10));
});
if (octets.length !== 4)
throw new TypeError('valid IP address required');
var uint32 = ((octets[0] * Math.pow(256, 3)) +
(octets[1] * Math.pow(256, 2)) +
(octets[2] * 256) + octets[3]);
return (uint32);
}
|
javascript
|
{
"resource": ""
}
|
q62703
|
getNested
|
test
|
function getNested(obj, prop) {
var service = obj[prop];
if (service === undefined && Bottle.config.strict) {
throw new Error('Bottle was unable to resolve a service. `' + prop + '` is undefined.');
}
return service;
}
|
javascript
|
{
"resource": ""
}
|
q62704
|
getNestedBottle
|
test
|
function getNestedBottle(name) {
var bottle;
if (!this.nested[name]) {
bottle = Bottle.pop();
this.nested[name] = bottle;
this.factory(name, function SubProviderFactory() {
return bottle.container;
});
}
return this.nested[name];
}
|
javascript
|
{
"resource": ""
}
|
q62705
|
applyMiddleware
|
test
|
function applyMiddleware(middleware, name, instance, container) {
var descriptor = {
configurable : true,
enumerable : true
};
if (middleware.length) {
descriptor.get = function getWithMiddlewear() {
var index = 0;
var next = function nextMiddleware(err) {
if (err) {
throw err;
}
if (middleware[index]) {
middleware[index++](instance, next);
}
};
next();
return instance;
};
} else {
descriptor.value = instance;
descriptor.writable = true;
}
Object.defineProperty(container, name, descriptor);
return container[name];
}
|
javascript
|
{
"resource": ""
}
|
q62706
|
middleware
|
test
|
function middleware(fullname, func) {
var parts, name;
if (typeof fullname === FUNCTION_TYPE) {
func = fullname;
fullname = GLOBAL_NAME;
}
parts = fullname.split(DELIMITER);
name = parts.shift();
if (parts.length) {
getNestedBottle.call(this, name).middleware(parts.join(DELIMITER), func);
} else {
if (!this.middlewares[name]) {
this.middlewares[name] = [];
}
this.middlewares[name].push(func);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q62707
|
createProvider
|
test
|
function createProvider(name, Provider) {
var providerName, properties, container, id, decorators, middlewares;
id = this.id;
container = this.container;
decorators = this.decorators;
middlewares = this.middlewares;
providerName = name + PROVIDER_SUFFIX;
properties = Object.create(null);
properties[providerName] = {
configurable : true,
enumerable : true,
get : function getProvider() {
var instance = new Provider();
delete container[providerName];
container[providerName] = instance;
return instance;
}
};
properties[name] = {
configurable : true,
enumerable : true,
get : function getService() {
var provider = container[providerName];
var instance;
if (provider) {
// filter through decorators
instance = getWithGlobal(decorators, name).reduce(reducer, provider.$get(container));
delete container[providerName];
delete container[name];
}
return instance === undefined ? instance : applyMiddleware(getWithGlobal(middlewares, name),
name, instance, container);
}
};
Object.defineProperties(container, properties);
return this;
}
|
javascript
|
{
"resource": ""
}
|
q62708
|
provider
|
test
|
function provider(fullname, Provider) {
var parts, name;
parts = fullname.split(DELIMITER);
if (this.providerMap[fullname] && parts.length === 1 && !this.container[fullname + PROVIDER_SUFFIX]) {
return console.error(fullname + ' provider already instantiated.');
}
this.originalProviders[fullname] = Provider;
this.providerMap[fullname] = true;
name = parts.shift();
if (parts.length) {
getNestedBottle.call(this, name).provider(parts.join(DELIMITER), Provider);
return this;
}
return createProvider.call(this, name, Provider);
}
|
javascript
|
{
"resource": ""
}
|
q62709
|
createService
|
test
|
function createService(name, Service, isClass) {
var deps = arguments.length > 3 ? slice.call(arguments, 3) : [];
var bottle = this;
return factory.call(this, name, function GenericFactory() {
var serviceFactory = Service; // alias for jshint
var args = deps.map(getNestedService, bottle.container);
if (!isClass) {
return serviceFactory.apply(null, args);
}
return new (Service.bind.apply(Service, [null].concat(args)))();
});
}
|
javascript
|
{
"resource": ""
}
|
q62710
|
service
|
test
|
function service(name, Service) {
return createService.apply(this, [name, Service, true].concat(slice.call(arguments, 2)));
}
|
javascript
|
{
"resource": ""
}
|
q62711
|
serviceFactory
|
test
|
function serviceFactory(name, factoryService) {
return createService.apply(this, [name, factoryService, false].concat(slice.call(arguments, 2)));
}
|
javascript
|
{
"resource": ""
}
|
q62712
|
defineValue
|
test
|
function defineValue(name, val) {
Object.defineProperty(this, name, {
configurable : true,
enumerable : true,
value : val,
writable : true
});
}
|
javascript
|
{
"resource": ""
}
|
q62713
|
setValueObject
|
test
|
function setValueObject(container, name) {
var nestedContainer = container[name];
if (!nestedContainer) {
nestedContainer = {};
defineValue.call(container, name, nestedContainer);
}
return nestedContainer;
}
|
javascript
|
{
"resource": ""
}
|
q62714
|
value
|
test
|
function value(name, val) {
var parts;
parts = name.split(DELIMITER);
name = parts.pop();
defineValue.call(parts.reduce(setValueObject, this.container), name, val);
return this;
}
|
javascript
|
{
"resource": ""
}
|
q62715
|
constant
|
test
|
function constant(name, value) {
var parts = name.split(DELIMITER);
name = parts.pop();
defineConstant.call(parts.reduce(setValueObject, this.container), name, value);
return this;
}
|
javascript
|
{
"resource": ""
}
|
q62716
|
decorator
|
test
|
function decorator(fullname, func) {
var parts, name;
if (typeof fullname === FUNCTION_TYPE) {
func = fullname;
fullname = GLOBAL_NAME;
}
parts = fullname.split(DELIMITER);
name = parts.shift();
if (parts.length) {
getNestedBottle.call(this, name).decorator(parts.join(DELIMITER), func);
} else {
if (!this.decorators[name]) {
this.decorators[name] = [];
}
this.decorators[name].push(func);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q62717
|
instanceFactory
|
test
|
function instanceFactory(name, Factory) {
return factory.call(this, name, function GenericInstanceFactory(container) {
return {
instance : Factory.bind(Factory, container)
};
});
}
|
javascript
|
{
"resource": ""
}
|
q62718
|
pop
|
test
|
function pop(name) {
var instance;
if (typeof name === STRING_TYPE) {
instance = bottles[name];
if (!instance) {
bottles[name] = instance = new Bottle();
instance.constant('BOTTLE_NAME', name);
}
return instance;
}
return new Bottle();
}
|
javascript
|
{
"resource": ""
}
|
q62719
|
register
|
test
|
function register(Obj) {
var value = Obj.$value === undefined ? Obj : Obj.$value;
return this[Obj.$type || 'service'].apply(this, [Obj.$name, value].concat(Obj.$inject || []));
}
|
javascript
|
{
"resource": ""
}
|
q62720
|
resetProviders
|
test
|
function resetProviders(names) {
var tempProviders = this.originalProviders;
var shouldFilter = Array.isArray(names);
Object.keys(this.originalProviders).forEach(function resetProvider(originalProviderName) {
if (shouldFilter && names.indexOf(originalProviderName) === -1) {
return;
}
var parts = originalProviderName.split(DELIMITER);
if (parts.length > 1) {
parts.forEach(removeProviderMap, getNestedBottle.call(this, parts[0]));
}
removeProviderMap.call(this, originalProviderName);
this.provider(originalProviderName, tempProviders[originalProviderName]);
}, this);
}
|
javascript
|
{
"resource": ""
}
|
q62721
|
throwIfInvalidNode
|
test
|
function throwIfInvalidNode(node, functionName) {
if (!exports.isASTNode(node)) {
throw new Error(functionName + "(): " + util.inspect(node) + " is not a valid AST node.");
}
}
|
javascript
|
{
"resource": ""
}
|
q62722
|
isEvent
|
test
|
function isEvent(expr, eventDeclarations) {
for (let { node, enclosingContract } of eventDeclarations) {
if (expr.callee.name === node.name && sourceCode.isAChildOf(expr, enclosingContract)) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q62723
|
registerEventName
|
test
|
function registerEventName(emitted) {
const { node } = emitted;
(!emitted.exit) && events.push({ node, enclosingContract: sourceCode.getParent(node) });
}
|
javascript
|
{
"resource": ""
}
|
q62724
|
inspectVariableDeclarator
|
test
|
function inspectVariableDeclarator(emitted) {
let node = emitted.node;
if (!emitted.exit) {
allVariableDeclarations [node.id.name] = node;
}
}
|
javascript
|
{
"resource": ""
}
|
q62725
|
inspectProgram
|
test
|
function inspectProgram(emitted) {
if (emitted.exit) {
Object.keys(allVariableDeclarations).forEach(function(name) {
context.report({
node: allVariableDeclarations [name],
message: "Variable '" + name + "' is declared but never used."
});
});
}
}
|
javascript
|
{
"resource": ""
}
|
q62726
|
inspectIdentifier
|
test
|
function inspectIdentifier(emitted) {
if (!emitted.exit) {
let node = emitted.node,
sourceCode = context.getSourceCode();
if (
allVariableDeclarations [node.name] &&
sourceCode.getParent(node).type !== "VariableDeclarator"
) {
delete allVariableDeclarations [node.name];
}
}
}
|
javascript
|
{
"resource": ""
}
|
q62727
|
inspectFunctionsOfContract
|
test
|
function inspectFunctionsOfContract(emitted) {
if (emitted.exit) {
return;
}
const { node } = emitted, { body } = node;
let cursor = 0;
// Filter out non-function nodes
body.filter(child => {
return ["FunctionDeclaration", "ConstructorDeclaration"].includes(child.type);
}).forEach(funcNode => {
// Return if the function is ignored or in the correct order.
if (
(context.options && isIgnored(funcNode, node, context.options[0].ignore)) ||
isFunctionVisibility(node, funcNode, functionOrder[cursor])
) {
return;
}
const funcPosInOrder = findFuncPosInOrder(node, funcNode);
if (funcPosInOrder > cursor) {
cursor = funcPosInOrder;
return;
}
context.report({ node: funcNode, message: errorMessage });
});
}
|
javascript
|
{
"resource": ""
}
|
q62728
|
inspectCallExpression
|
test
|
function inspectCallExpression(emitted) {
let node = emitted.node,
callArgs = node.arguments;
if (emitted.exit) {
return;
}
let nodeCode = sourceCode.getText(node);
//for a 0-argument call, ensure that name is followed by '()'
if (!callArgs.length) {
for (let i = nodeCode.length; i > 0; i--) {
if (nodeCode [i] === ")" && nodeCode [i-1] === "(") {
return;
}
if (/[\s\(\)]/.test(nodeCode [i])) {
break;
}
}
return context.report({
node: node,
message: "\"" + nodeCode + "\": " +
"A call without arguments should have brackets without any whitespace between them, like 'functionName ()'."
});
}
let lastCallArg = callArgs.slice(-1) [0];
//if call spans over multiple lines (due to too many arguments), below rules don't apply
if (sourceCode.getLine(node) !== sourceCode.getEndingLine(lastCallArg)) {
return;
}
let charBeforeFirstArg = sourceCode.getPrevChar(callArgs [0]),
charAfterLastCallArg = sourceCode.getNextChar(lastCallArg);
(callArgs [0].type !== "NameValueAssignment" && charBeforeFirstArg !== "(") && context.report({
node: callArgs [0],
location: {
column: sourceCode.getColumn(callArgs [0]) - 1
},
message: "'" + node.callee.name + "': The first argument must not be preceded by any whitespace or comments (only '(')."
});
(lastCallArg.type !== "NameValueAssignment" && charAfterLastCallArg !== ")") && context.report({
node: callArgs [0],
location: {
column: sourceCode.getEndingColumn(lastCallArg) + 1
},
message: "'" + node.callee.name + "': The last argument must not be succeeded by any whitespace or comments (only ')')."
});
}
|
javascript
|
{
"resource": ""
}
|
q62729
|
inspectExperimentalPragmaStatement
|
test
|
function inspectExperimentalPragmaStatement(emitted) {
if (emitted.exit) {
return;
}
const { node } = emitted,
nodesAllowedAbove = ["ExperimentalPragmaStatement", "PragmaStatement"],
programNode = context.getSourceCode().getParent(node);
for (let childNode of programNode.body) {
// If we've reached this exp. pragma while traversing body, it means its position is fine.
if (node.start === childNode.start) {
return;
}
// We found the first node not allowed above experimental pragma, report and exit.
const pragmaCode = context.getSourceCode().getText(node);
if (nodesAllowedAbove.indexOf(childNode.type) < 0) {
const errObject = {
node,
fix(fixer) {
return [fixer.remove(node),
fixer.insertTextBefore(childNode, `${pragmaCode}${EOL}`)];
},
message: "Experimental Pragma must precede everything except Solidity Pragma."
};
return context.report(errObject);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q62730
|
test
|
function(sourceCode, errorMessages) {
let fixedSourceCode = "", fixes = [], fixesApplied = [], remainingMessages = [];
let cursor = Number.NEGATIVE_INFINITY;
function attemptFix(fix) {
let start = fix.range [0], end = fix.range [1];
// If this fix overlaps with the previous one or has negaive range, return.
// Note that when cursor === start, its NOT an overlap since when source code in range
// [i, j] is being edited, the code covered is actually from i to j-1.
if (cursor > start || start > end) {
return false;
}
fixedSourceCode += sourceCode.slice(Math.max(0, cursor), Math.max(0, start));
fixedSourceCode += fix.text;
cursor = end;
return true;
}
// Segregate errors that can be fixed from those that can't for sure.
errorMessages.forEach(function(msg) {
if (msg.fix) {
// If msg.fix is an Array of fix packets, merge them into a single fix packet.
try {
msg.fix = mergeFixes(msg.fix, sourceCode);
} catch (e) {
throw new Error("An error occured while applying fix of rule \""
+ msg.ruleName + "\" for error \"" + msg.message + "\": " + e.message);
}
return fixes.push(msg);
}
remainingMessages.push(msg);
});
// Fixes will be applied in top-down approach. The fix that arrives first (line-wise, followed by column-wise)
// gets applied first. But if current fix is applied successfully & the next one overlaps the current one,
// then the next one is simply skipped. Hence, it is NOT guranteed that all fixes will be applied.
fixes.sort(compareMessagesByFixRange).forEach(function(msg) {
if (attemptFix(msg.fix)) {
return fixesApplied.push(msg);
}
remainingMessages.push(msg);
});
fixedSourceCode += sourceCode.slice(Math.max(0, cursor));
remainingMessages.sort(compareMessagesByLocation);
return {
fixesApplied: fixesApplied,
fixedSourceCode: fixedSourceCode,
remainingErrorMessages: remainingMessages
};
}
|
javascript
|
{
"resource": ""
}
|
|
q62731
|
inspectTopLevelDeclaration
|
test
|
function inspectTopLevelDeclaration(emitted) {
let body = emitted.node.body || [],
levelOneIndentRegExp = new RegExp("^\\n" + BASE_INDENTATION_STYLE + "$"),
endingLineRegExp = new RegExp("^" + BASE_INDENTATION_STYLE + "(\\S| \\*)$"), //either a non-whitespace character or 1 extra whitespace followed by * (closing of multi-line comment)
endingLineExtraIndentRegExp = new RegExp("^" + BASE_INDENTATION_STYLE.repeat(2) + "(\\S| \\*)$");
if (emitted.exit) {
return;
}
function inspectChild(child) {
let prevChars = sourceCode.getPrevChars(child, BASE_INDENTATION_STYLE.length+1),
endingLineNum = sourceCode.getEndingLine(child);
//if the start of node doesn't follow correct indentation
if (!levelOneIndentRegExp.test(prevChars)) {
context.report({
node: child,
message: `Only use indent of ${BASE_INDENTATION_STYLE_DESC}.`
});
}
// If the node starts & ends on same line, exit.
if (sourceCode.getLine(child) === endingLineNum) {
return;
}
// If node starts & ends on diff lines, the ending line must also follow correct indentation.
// Exception to this is an abstract function whose declaration spans over multiple lines. Eg-
// function foo()
// payable
// returns (uint, string);
if (child.type === "FunctionDeclaration" && child.is_abstract) {
if (!endingLineExtraIndentRegExp.test(
sourceCode.getTextOnLine(endingLineNum).slice(0, BASE_INDENTATION_STYLE.repeat(2).length+1))) {
context.report({
node: child,
location: {
line: endingLineNum,
column: 0
},
message: `Only use indent of ${BASE_INDENTATION_STYLE_DESC}.`
});
}
return;
}
if (!endingLineRegExp.test(
sourceCode.getTextOnLine(endingLineNum).slice(0, BASE_INDENTATION_STYLE.length+1))) {
context.report({
node: child,
location: {
line: endingLineNum,
column: 0
},
message: `Only use indent of ${BASE_INDENTATION_STYLE_DESC}.`
});
}
}
body.forEach(inspectChild);
}
|
javascript
|
{
"resource": ""
}
|
q62732
|
inspectBlockStatement
|
test
|
function inspectBlockStatement(emitted) {
let node = emitted.node;
//if the complete block resides on the same line, no need to check for indentation
if (emitted.exit || (sourceCode.getLine(node) === sourceCode.getEndingLine(node))) {
return;
}
let parent = sourceCode.getParent(node),
parentDeclarationLine = sourceCode.getLine(parent),
parentDeclarationLineText = sourceCode.getTextOnLine(parentDeclarationLine),
currentIndent, currentIndentLevel;
function inspectBlockItem(blockIndent, blockIndentDesc, blockItem) {
let prevChars = sourceCode.getPrevChars(blockItem, blockIndent.length+1),
endingLineNum = sourceCode.getEndingLine(blockItem),
endingLineRegExp = new RegExp("^" + blockIndent + "(" + BASE_INDENTATION_STYLE + ")?\\S.*$");
if (prevChars !== ("\n" + blockIndent)) {
context.report({
node: blockItem,
message: `Only use indent of ${blockIndentDesc}.`
});
}
/**
* If the block item spans over multiple lines, make sure the ending line also follows the indent rule
* An exception to this is the if-else statements when they don't have BlockStatement as their body
* eg-
* if (a)
* foo();
* else
* bar();
*
* Another exception is chaining.
* eg-
* function() {
* myObject
* .funcA()
* .funcB()
* [0];
* }
* Ending line has 1 extra indentation but this is acceptable.
*/
if (
blockItem.type !== "IfStatement" &&
sourceCode.getLine(blockItem) !== endingLineNum &&
!endingLineRegExp.test(sourceCode.getTextOnLine(endingLineNum))
) {
context.report({
node: blockItem,
location: {
line: endingLineNum,
column: 0
},
message: `Only use indent of ${blockIndentDesc}.`
});
}
}
currentIndent = parentDeclarationLineText.slice(
0,
parentDeclarationLineText.indexOf(parentDeclarationLineText.trim())
);
//in case of no match, match() returns null. Return [] instead to avoid crash
currentIndentLevel = (currentIndent.match(BASE_INDENTATION_STYLE_REGEXP_GLOBAL) || []).length;
//ensure that there is only whitespace of correct level before the block's parent's code
if (getIndentString(BASE_INDENTATION_STYLE, currentIndentLevel) !== currentIndent) {
return; //exit now, we can' proceed further unless this is fixed
}
//indentation of items inside block should be 1 level greater than that of parent
const blockIndent = getIndentString(BASE_INDENTATION_STYLE, currentIndentLevel + 1);
const blockIndentDesc = getIndentDescription(BASE_INDENTATION_STYLE, currentIndentLevel + 1);
node.body.forEach(inspectBlockItem.bind(null, blockIndent, blockIndentDesc));
}
|
javascript
|
{
"resource": ""
}
|
q62733
|
test
|
function(node, beforeCount, afterCount) {
let sourceCodeText = this.text;
if (node) {
if (astUtils.isASTNode(node)) {
return this.text.slice(
Math.max(0, node.start - (Math.abs(beforeCount) || 0)),
node.end + (Math.abs(afterCount) || 0)
);
}
throw new Error("Invalid Node object");
}
return sourceCodeText;
}
|
javascript
|
{
"resource": ""
}
|
|
q62734
|
inspectVariableDeclaration
|
test
|
function inspectVariableDeclaration(emitted) {
let node = emitted.node, code = sourceCode.getText(node);
if (emitted.exit) {
return;
}
//if a particular character is '=', check its left and right for single space
for (let i = 2; i < code.length; i++) {
if (code [i] === "=") {
(!/^[^\/\s] $/.test(code.slice(i-2, i))) && context.report({
node: node,
message: "There should be only a single space between assignment operator '=' and its left side."
});
(!/^ [^\/\s]$/.test(code.slice(i+1, i+3))) && context.report({
node: node,
message: "There should be only a single space between assignment operator '=' and its right side."
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q62735
|
RuleContext
|
test
|
function RuleContext(ruleName, ruleDesc, ruleMeta, Solium) {
let contextObject = this;
// Set contect attribute 'options' iff options were provided.
ruleDesc.options && Object.assign(contextObject, { options: ruleDesc.options });
//set read-only properties of the context object
Object.defineProperties(contextObject, {
name: {
value: ruleName,
writable: false //though the default is false anyway, I think its better to express your intention clearly
},
meta: {
value: ruleDesc,
writable: false
}
});
//inherit all Solium methods which are of relevance to the rule
INHERITABLE_METHODS.forEach(function(methodName) {
contextObject [methodName] = function(s, z, a, b, o) { //every method will receive 5 arguments tops
return Solium [methodName].call(Solium, s, z, a, b, o);
};
});
/**
* wrapper around Solium.report () which adds some additional information to the error object
* @param {Object} error An object describing the lint error, sent by the rule currently running
*/
contextObject.report = function(error) {
if (!isErrObjectValid(error)) {
throw new Error(
`Rule "${ruleName}": invalid error object was passed. AJV message:${EOL}${util.inspect(isErrObjectValid.errors)}`
);
}
Object.assign(error, { ruleName: ruleName, ruleMeta: ruleMeta, type: contextObject.meta.type });
Solium.report(error);
};
}
|
javascript
|
{
"resource": ""
}
|
q62736
|
resolveUpstream
|
test
|
function resolveUpstream(upstream) {
let coreRulesetRegExp = /^solium:[a-z_]+$/;
// Determine whether upstream is a solium core ruleset or a sharable config.
if (coreRulesetRegExp.test(upstream)) {
try {
return require("../../config/rulesets/solium-" + upstream.split(":") [1]).rules;
} catch (e) {
throw new Error("\"" + upstream + "\" is not a core ruleset.");
}
}
// If flow reaches here, it means upstream is a sharable config.
let configName = constants.SOLIUM_SHARABLE_CONFIG_PREFIX + upstream, config;
try {
config = require(configName);
} catch (e) {
if (e.code === "MODULE_NOT_FOUND") {
throw new Error(
"The sharable config \"" + configName + "\" is not installed. " +
"If Solium is installed globally, install the config globally using " +
"\"npm install -g " + configName + "\". Else install locally using " +
"\"npm install --save-dev " + configName + "\"."
);
}
throw new Error("The sharable config \"" + configName + "\" could not be loaded: " + e.message);
}
if (isAValidSharableConfig(config)) {
return config.rules;
}
throw new Error("Invalid sharable config \"" +
configName + "\". AJV message:\n" + util.inspect(isAValidSharableConfig.errors));
}
|
javascript
|
{
"resource": ""
}
|
q62737
|
resolvePluginConfig
|
test
|
function resolvePluginConfig(name, plugin) {
let config = {};
Object.keys(plugin.rules).forEach(function(ruleName) {
config [name + "/" + ruleName] = plugin.rules [ruleName].meta.docs.type;
});
return config;
}
|
javascript
|
{
"resource": ""
}
|
q62738
|
writeConfigFile
|
test
|
function writeConfigFile(config) {
try {
fs.writeFileSync(
SOLIUMRC_FILENAME_ABSOLUTE,
JSON.stringify(config, null, 2)
);
} catch (e) {
errorReporter.reportFatal(
`An error occurred while writing to ${SOLIUMRC_FILENAME_ABSOLUTE}:${EOL}${e.message}`);
process.exit(errorCodes.WRITE_FAILED);
}
}
|
javascript
|
{
"resource": ""
}
|
q62739
|
lintString
|
test
|
function lintString(sourceCode, userConfig, errorReporter, fileName) {
let lintErrors, fixesApplied;
try {
if (userConfig.options.autofix || userConfig.options.autofixDryrun) {
let result = solium.lintAndFix(sourceCode, userConfig);
lintErrors = result.errorMessages;
if (userConfig.options.autofix) {
applyFixes(fileName, result);
fixesApplied = result.fixesApplied;
} else {
errorReporter.reportDiff(fileName,
sourceCode, result.fixedSourceCode, result.fixesApplied.length);
}
} else {
lintErrors = solium.lint(sourceCode, userConfig);
}
} catch (e) {
// Don't abort in case of a parse error, just report it as a normal lint issue.
if (e.name !== "SyntaxError") {
const messageOrStackrace = userConfig.options.debug ? e.stack : e.message;
errorReporter.reportFatal(`An error occured while linting over ${fileName}:${EOL}${messageOrStackrace}`);
process.exit(errorCodes.ERRORS_FOUND);
}
lintErrors = [{
ruleName: "",
type: "error",
message: `Syntax error: unexpected token ${e.found}`,
line: e.location.start.line,
column: e.location.start.column
}];
}
// If any lint/internal errors/warnings exist, report them
lintErrors.length &&
errorReporter.report(fileName, sourceCode, lintErrors, fixesApplied);
return lintErrors.reduce(function(numOfErrors, err) {
return err.type === "error" ? numOfErrors+1 : numOfErrors;
}, 0);
}
|
javascript
|
{
"resource": ""
}
|
q62740
|
lintFile
|
test
|
function lintFile(fileName, userConfig, errorReporter) {
let sourceCode;
try {
sourceCode = fs.readFileSync(fileName, "utf8");
} catch (e) {
errorReporter.reportFatal("Unable to read " + fileName + ": " + e.message);
process.exit(errorCodes.FILE_NOT_FOUND);
}
return lintString(sourceCode, userConfig, errorReporter, fileName);
}
|
javascript
|
{
"resource": ""
}
|
q62741
|
createCliOptions
|
test
|
function createCliOptions(cliObject) {
function collect(val, memo) {
memo.push(val);
return memo;
}
cliObject
.version(`Solium version ${version}`)
.description("Linter to find & fix style and security issues in Solidity smart contracts.")
.usage("[options] <keyword>")
.option("-i, --init", "Create default rule configuration files")
.option("-f, --file [filepath::String]", "Solidity file to lint")
.option("-d, --dir [dirpath::String]", "Directory containing Solidity files to lint")
.option("-R, --reporter [name::String]", "Format to report lint issues in (pretty | gcc)", "pretty")
.option("-c, --config [filepath::String]", "Path to the .soliumrc configuration file")
.option("-, --stdin", "Read input file from stdin")
.option("--fix", "Fix Lint issues where possible")
.option("--fix-dry-run", "Output fix diff without applying it")
.option("--debug", "Display debug information")
.option("--watch", "Watch for file changes")
.option("--hot", "(Deprecated) Same as --watch")
.option("--no-soliumignore", "Do not look for .soliumignore file")
.option("--no-soliumrc", "Do not look for soliumrc configuration file")
.option(
"--rule [rule]",
"Rule to execute. This overrides the specified rule's configuration in soliumrc if present",
collect,
[]
)
.option(
"--plugin [plugin]",
"Plugin to execute. This overrides the specified plugin's configuration in soliumrc if present",
collect,
[]
);
}
|
javascript
|
{
"resource": ""
}
|
q62742
|
test
|
function(options, listItemsSchema) {
let validateOptionsList = SchemaValidator.compile({
type: "array",
minItems: listItemsSchema.length,
additionalItems: false,
items: listItemsSchema
});
return validateOptionsList(options);
}
|
javascript
|
{
"resource": ""
}
|
|
q62743
|
inspectFD
|
test
|
function inspectFD(emitted) {
const { node } = emitted,
visibilityModifiers = ["public", "external", "internal", "private"];
const modifiers = (node.modifiers || []),
firstVisibilityModifierIndex = modifiers.findIndex(m => visibilityModifiers.includes(m.name));
// If no visibility modifiers exist in function declaration, exit now
if (emitted.exit || firstVisibilityModifierIndex === -1) {
return;
}
const firstNonVisModifBeforeFirstVisModif = modifiers.slice(0, firstVisibilityModifierIndex).find(m => !visibilityModifiers.includes(m.name));
// TODO: Add fix() for this rule
if (firstNonVisModifBeforeFirstVisModif) {
const issue = {
node: modifiers[firstVisibilityModifierIndex],
message: `Visibility modifier "${modifiers[firstVisibilityModifierIndex].name}" should come before other modifiers.`
};
context.report(issue);
}
}
|
javascript
|
{
"resource": ""
}
|
q62744
|
isHex
|
test
|
function isHex(literal) {
let reg = /^[0-9a-f]+$/i;
//test for '0x' separately because hex notation should not be a part of the standard RegExp
if (literal.slice(0, 2) !== "0x") {
return false;
}
return reg.test(literal.slice(2));
}
|
javascript
|
{
"resource": ""
}
|
q62745
|
Soundfont
|
test
|
function Soundfont (ctx, nameToUrl) {
console.warn('new Soundfont() is deprected')
console.log('Please use Soundfont.instrument() instead of new Soundfont().instrument()')
if (!(this instanceof Soundfont)) return new Soundfont(ctx)
this.nameToUrl = nameToUrl || Soundfont.nameToUrl
this.ctx = ctx
this.instruments = {}
this.promises = []
}
|
javascript
|
{
"resource": ""
}
|
q62746
|
oscillatorPlayer
|
test
|
function oscillatorPlayer (ctx, defaultOptions) {
defaultOptions = defaultOptions || {}
return function (note, time, duration, options) {
console.warn('The oscillator player is deprecated.')
console.log('Starting with version 0.9.0 you will have to wait until the soundfont is loaded to play sounds.')
var midi = note > 0 && note < 129 ? +note : parser.midi(note)
var freq = midi ? parser.midiToFreq(midi, 440) : null
if (!freq) return
duration = duration || 0.2
options = options || {}
var destination = options.destination || defaultOptions.destination || ctx.destination
var vcoType = options.vcoType || defaultOptions.vcoType || 'sine'
var gain = options.gain || defaultOptions.gain || 0.4
var vco = ctx.createOscillator()
vco.type = vcoType
vco.frequency.value = freq
/* VCA */
var vca = ctx.createGain()
vca.gain.value = gain
/* Connections */
vco.connect(vca)
vca.connect(destination)
vco.start(time)
if (duration > 0) vco.stop(time + duration)
return vco
}
}
|
javascript
|
{
"resource": ""
}
|
q62747
|
instrument
|
test
|
function instrument (ac, name, options) {
if (arguments.length === 1) return function (n, o) { return instrument(ac, n, o) }
var opts = options || {}
var isUrl = opts.isSoundfontURL || isSoundfontURL
var toUrl = opts.nameToUrl || nameToUrl
var url = isUrl(name) ? name : toUrl(name, opts.soundfont, opts.format)
return load(ac, url, { only: opts.only || opts.notes }).then(function (buffers) {
var p = player(ac, buffers, opts).connect(opts.destination ? opts.destination : ac.destination)
p.url = url
p.name = name
return p
})
}
|
javascript
|
{
"resource": ""
}
|
q62748
|
hasSystemLib
|
test
|
function hasSystemLib (lib) {
var libName = 'lib' + lib + '.+(so|dylib)'
var libNameRegex = new RegExp(libName)
// Try using ldconfig on linux systems
if (hasLdconfig()) {
try {
if (childProcess.execSync('ldconfig -p 2>/dev/null | grep -E "' + libName + '"').length) {
return true
}
} catch (err) {
// noop -- proceed to other search methods
}
}
// Try checking common library locations
return SYSTEM_PATHS.some(function (systemPath) {
try {
var dirListing = fs.readdirSync(systemPath)
return dirListing.some(function (file) {
return libNameRegex.test(file)
})
} catch (err) {
return false
}
})
}
|
javascript
|
{
"resource": ""
}
|
q62749
|
thenify
|
test
|
async function thenify(fn) {
return await new Promise(function(resolve, reject) {
function callback(err, res) {
if (err) return reject(err);
return resolve(res);
}
fn(callback);
});
}
|
javascript
|
{
"resource": ""
}
|
q62750
|
startWatching
|
test
|
function startWatching(opts) {
var chokidarOpts = createChokidarOpts(opts);
var watcher = chokidar.watch(opts.patterns, chokidarOpts);
var throttledRun = _.throttle(run, opts.throttle);
var debouncedRun = _.debounce(throttledRun, opts.debounce);
watcher.on('all', function(event, path) {
var description = EVENT_DESCRIPTIONS[event] + ':';
if (opts.verbose) {
console.error(description, path);
} else {
if (!opts.silent) {
console.log(event + ':' + path);
}
}
// XXX: commands might be still run concurrently
if (opts.command) {
debouncedRun(
opts.command
.replace(/\{path\}/ig, path)
.replace(/\{event\}/ig, event)
);
}
});
watcher.on('error', function(error) {
console.error('Error:', error);
console.error(error.stack);
});
watcher.once('ready', function() {
var list = opts.patterns.join('", "');
if (!opts.silent) {
console.error('Watching', '"' + list + '" ..');
}
});
}
|
javascript
|
{
"resource": ""
}
|
q62751
|
_resolveIgnoreOpt
|
test
|
function _resolveIgnoreOpt(ignoreOpt) {
if (!ignoreOpt) {
return ignoreOpt;
}
var ignores = !_.isArray(ignoreOpt) ? [ignoreOpt] : ignoreOpt;
return _.map(ignores, function(ignore) {
var isRegex = ignore[0] === '/' && ignore[ignore.length - 1] === '/';
if (isRegex) {
// Convert user input to regex object
var match = ignore.match(new RegExp('^/(.*)/(.*?)$'));
return new RegExp(match[1], match[2]);
}
return ignore;
});
}
|
javascript
|
{
"resource": ""
}
|
q62752
|
requireProp
|
test
|
function requireProp(props, propName, componentName) {
return isEmpty(props[propName])
? new Error(
`The prop \`${propName}\` is required for \`${componentName}\`.`
)
: null
}
|
javascript
|
{
"resource": ""
}
|
q62753
|
_0to1
|
test
|
function _0to1(props, propName, componentName) {
if (isEmpty(props[propName])) {
return null
}
if (
typeof props[propName] === 'number' &&
props[propName] >= 0 &&
props[propName] <= 1
) {
return null
}
return new Error(
`Invalid prop \`${propName}\` supplied to \`${componentName}\`. Please provide a number in the 0-1 range.`
)
}
|
javascript
|
{
"resource": ""
}
|
q62754
|
babel
|
test
|
function babel(options = {}) {
return (context, { addLoader }) =>
addLoader({
// setting `test` defaults here, in case there is no `context.match` data
test: /\.(js|jsx)$/,
use: [
{
loader: 'thread-loader',
options: {
// Keep workers alive for more effective watch mode
...(process.env.NODE_ENV === 'development' && { poolTimeout: Infinity }),
},
},
{
loader: 'babel-loader',
options: Object.assign(babelLoaderOptions, options),
},
],
...context.match,
})
}
|
javascript
|
{
"resource": ""
}
|
q62755
|
imageLoader
|
test
|
function imageLoader() {
return (context, { addLoader }) =>
addLoader({
test: /\.(gif|ico|jpg|jpeg|png|webp)$/,
loader: 'url-loader',
options: {
limit: 10000,
name: fileNameTemplate,
},
})
}
|
javascript
|
{
"resource": ""
}
|
q62756
|
csvLoader
|
test
|
function csvLoader() {
return (context, { addLoader }) =>
addLoader({
test: /\.csv$/,
loader: 'csv-loader',
options: {
dynamicTyping: true,
header: true,
skipEmptyLines: true,
},
})
}
|
javascript
|
{
"resource": ""
}
|
q62757
|
cssSvgLoader
|
test
|
function cssSvgLoader() {
return (context, { addLoader }) =>
addLoader({
// This needs to be different form the reactSvgLoader, otherwise it will merge
test: /(.*)\.svg$/,
issuer: {
test: /\.css$/,
},
loader: 'url-loader',
options: {
limit: 10000,
name: fileNameTemplate,
},
})
}
|
javascript
|
{
"resource": ""
}
|
q62758
|
prependEntry
|
test
|
function prependEntry(entry) {
const blockFunction = (context, util) => {
if (!context.entriesToPrepend) context.entriesToPrepend = []
context.entriesToPrepend.unshift(entry)
return config => config
}
return Object.assign(blockFunction, {
post: prependEntryPostHook,
})
}
|
javascript
|
{
"resource": ""
}
|
q62759
|
build
|
test
|
function build() {
log.info(`Creating an optimized production build...`)
const compiler = createWebpackCompiler(
() => {
log.ok(`The ${chalk.cyan(relativeAppBuildPath)} folder is ready to be deployed.`)
},
() => {
log.err(`Aborting`)
process.exit(2)
}
)
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) {
return reject(err)
}
return resolve(stats)
})
})
}
|
javascript
|
{
"resource": ""
}
|
q62760
|
mergeData
|
test
|
function mergeData (to, from) {
if (!from) { return to }
var key, toVal, fromVal;
var keys = Object.keys(from);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
toVal = to[key];
fromVal = from[key];
if (!hasOwn(to, key)) {
set(to, key, fromVal);
} else if (
toVal !== fromVal &&
isPlainObject(toVal) &&
isPlainObject(fromVal)
) {
mergeData(toVal, fromVal);
}
}
return to
}
|
javascript
|
{
"resource": ""
}
|
q62761
|
withDefault
|
test
|
function withDefault(type) {
return Object.defineProperty(type, 'def', {
value: function value(def) {
if (def === undefined && !this.default) {
return this;
}
if (!isFunction(def) && !validateType(this, def)) {
warn(this._vueTypes_name + " - invalid default value: \"" + def + "\"", def);
return this;
}
if (isArray(def)) {
this.default = function () {
return [].concat(def);
};
} else if (isPlainObject_1(def)) {
this.default = function () {
return Object.assign({}, def);
};
} else {
this.default = def;
}
return this;
},
enumerable: false,
writable: false
});
}
|
javascript
|
{
"resource": ""
}
|
q62762
|
withValidate
|
test
|
function withValidate(type) {
return Object.defineProperty(type, 'validate', {
value: function value(fn) {
this.validator = fn.bind(this);
return this;
},
enumerable: false
});
}
|
javascript
|
{
"resource": ""
}
|
q62763
|
toType
|
test
|
function toType(name, obj, validateFn) {
if (validateFn === void 0) {
validateFn = false;
}
Object.defineProperty(obj, '_vueTypes_name', {
enumerable: false,
writable: false,
value: name
});
withDefault(withRequired(obj));
if (validateFn) {
withValidate(obj);
}
if (isFunction(obj.validator)) {
obj.validator = obj.validator.bind(obj);
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q62764
|
validateType
|
test
|
function validateType(type, value, silent) {
if (silent === void 0) {
silent = false;
}
var typeToCheck = type;
var valid = true;
var expectedType;
if (!isPlainObject_1(type)) {
typeToCheck = {
type: type
};
}
var namePrefix = typeToCheck._vueTypes_name ? typeToCheck._vueTypes_name + ' - ' : '';
if (hasOwn.call(typeToCheck, 'type') && typeToCheck.type !== null) {
if (isArray(typeToCheck.type)) {
valid = typeToCheck.type.some(function (type) {
return validateType(type, value, true);
});
expectedType = typeToCheck.type.map(function (type) {
return getType(type);
}).join(' or ');
} else {
expectedType = getType(typeToCheck);
if (expectedType === 'Array') {
valid = isArray(value);
} else if (expectedType === 'Object') {
valid = isPlainObject_1(value);
} else if (expectedType === 'String' || expectedType === 'Number' || expectedType === 'Boolean' || expectedType === 'Function') {
valid = getNativeType(value) === expectedType;
} else {
valid = value instanceof typeToCheck.type;
}
}
}
if (!valid) {
silent === false && warn(namePrefix + "value \"" + value + "\" should be of type \"" + expectedType + "\"");
return false;
}
if (hasOwn.call(typeToCheck, 'validator') && isFunction(typeToCheck.validator)) {
// swallow warn
var oldWarn;
if (silent) {
oldWarn = warn;
warn = noop;
}
valid = typeToCheck.validator(value);
oldWarn && (warn = oldWarn);
if (!valid && silent === false) warn(namePrefix + "custom validation failed");
return valid;
}
return valid;
}
|
javascript
|
{
"resource": ""
}
|
q62765
|
CustomEvent
|
test
|
function CustomEvent(type, eventInitDict) {
/*jshint eqnull:true */
var event = document.createEvent(eventName);
if (typeof type != 'string') {
throw new Error('An event name must be provided');
}
if (eventName == 'Event') {
event.initCustomEvent = initCustomEvent;
}
if (eventInitDict == null) {
eventInitDict = defaultInitDict;
}
event.initCustomEvent(
type,
eventInitDict.bubbles,
eventInitDict.cancelable,
eventInitDict.detail
);
return event;
}
|
javascript
|
{
"resource": ""
}
|
q62766
|
initCustomEvent
|
test
|
function initCustomEvent(
type, bubbles, cancelable, detail
) {
/*jshint validthis:true*/
this.initEvent(type, bubbles, cancelable);
this.detail = detail;
}
|
javascript
|
{
"resource": ""
}
|
q62767
|
cleanUpRuntimeEvents
|
test
|
function cleanUpRuntimeEvents() {
// Remove all touch events added during 'onDown' as well.
document.removeEventListener('touchmove', onMove, getPassiveSupported() ? { passive: false } : false);
document.removeEventListener('touchend', onUp);
document.removeEventListener('touchcancel', stopTracking);
document.removeEventListener('mousemove', onMove, getPassiveSupported() ? { passive: false } : false);
document.removeEventListener('mouseup', onUp);
}
|
javascript
|
{
"resource": ""
}
|
q62768
|
addRuntimeEvents
|
test
|
function addRuntimeEvents() {
cleanUpRuntimeEvents();
// @see https://developers.google.com/web/updates/2017/01/scrolling-intervention
document.addEventListener('touchmove', onMove, getPassiveSupported() ? { passive: false } : false);
document.addEventListener('touchend', onUp);
document.addEventListener('touchcancel', stopTracking);
document.addEventListener('mousemove', onMove, getPassiveSupported() ? { passive: false } : false);
document.addEventListener('mouseup', onUp);
}
|
javascript
|
{
"resource": ""
}
|
q62769
|
normalizeEvent
|
test
|
function normalizeEvent(ev) {
if (ev.type === 'touchmove' || ev.type === 'touchstart' || ev.type === 'touchend') {
var touch = ev.targetTouches[0] || ev.changedTouches[0];
return {
x: touch.clientX,
y: touch.clientY,
id: touch.identifier
};
} else {
// mouse events
return {
x: ev.clientX,
y: ev.clientY,
id: null
};
}
}
|
javascript
|
{
"resource": ""
}
|
q62770
|
onDown
|
test
|
function onDown(ev) {
var event = normalizeEvent(ev);
if (!pointerActive && !paused) {
pointerActive = true;
decelerating = false;
pointerId = event.id;
pointerLastX = pointerCurrentX = event.x;
pointerLastY = pointerCurrentY = event.y;
trackingPoints = [];
addTrackingPoint(pointerLastX, pointerLastY);
addRuntimeEvents();
}
}
|
javascript
|
{
"resource": ""
}
|
q62771
|
onMove
|
test
|
function onMove(ev) {
ev.preventDefault();
var event = normalizeEvent(ev);
if (pointerActive && event.id === pointerId) {
pointerCurrentX = event.x;
pointerCurrentY = event.y;
addTrackingPoint(pointerLastX, pointerLastY);
requestTick();
}
}
|
javascript
|
{
"resource": ""
}
|
q62772
|
addTrackingPoint
|
test
|
function addTrackingPoint(x, y) {
var time = Date.now();
while (trackingPoints.length > 0) {
if (time - trackingPoints[0].time <= 100) {
break;
}
trackingPoints.shift();
}
trackingPoints.push({ x: x, y: y, time: time });
}
|
javascript
|
{
"resource": ""
}
|
q62773
|
updateAndRender
|
test
|
function updateAndRender() {
var pointerChangeX = pointerCurrentX - pointerLastX;
var pointerChangeY = pointerCurrentY - pointerLastY;
targetX += pointerChangeX * multiplier;
targetY += pointerChangeY * multiplier;
if (bounce) {
var diff = checkBounds();
if (diff.x !== 0) {
targetX -= pointerChangeX * dragOutOfBoundsMultiplier(diff.x) * multiplier;
}
if (diff.y !== 0) {
targetY -= pointerChangeY * dragOutOfBoundsMultiplier(diff.y) * multiplier;
}
} else {
checkBounds(true);
}
callUpdateCallback();
pointerLastX = pointerCurrentX;
pointerLastY = pointerCurrentY;
ticking = false;
}
|
javascript
|
{
"resource": ""
}
|
q62774
|
startDecelAnim
|
test
|
function startDecelAnim() {
var firstPoint = trackingPoints[0];
var lastPoint = trackingPoints[trackingPoints.length - 1];
var xOffset = lastPoint.x - firstPoint.x;
var yOffset = lastPoint.y - firstPoint.y;
var timeOffset = lastPoint.time - firstPoint.time;
var D = timeOffset / 15 / multiplier;
decVelX = xOffset / D || 0; // prevent NaN
decVelY = yOffset / D || 0;
var diff = checkBounds();
if (Math.abs(decVelX) > 1 || Math.abs(decVelY) > 1 || !diff.inBounds) {
decelerating = true;
requestAnimFrame(stepDecelAnim);
}
}
|
javascript
|
{
"resource": ""
}
|
q62775
|
stepDecelAnim
|
test
|
function stepDecelAnim() {
if (!decelerating) {
return;
}
decVelX *= friction;
decVelY *= friction;
targetX += decVelX;
targetY += decVelY;
var diff = checkBounds();
if (Math.abs(decVelX) > stopThreshold || Math.abs(decVelY) > stopThreshold || !diff.inBounds) {
if (bounce) {
var reboundAdjust = 2.5;
if (diff.x !== 0) {
if (diff.x * decVelX <= 0) {
decVelX += diff.x * bounceDeceleration;
} else {
var adjust = diff.x > 0 ? reboundAdjust : -reboundAdjust;
decVelX = (diff.x + adjust) * bounceAcceleration;
}
}
if (diff.y !== 0) {
if (diff.y * decVelY <= 0) {
decVelY += diff.y * bounceDeceleration;
} else {
var adjust = diff.y > 0 ? reboundAdjust : -reboundAdjust;
decVelY = (diff.y + adjust) * bounceAcceleration;
}
}
} else {
if (diff.x !== 0) {
if (diff.x > 0) {
targetX = boundXmin;
} else {
targetX = boundXmax;
}
decVelX = 0;
}
if (diff.y !== 0) {
if (diff.y > 0) {
targetY = boundYmin;
} else {
targetY = boundYmax;
}
decVelY = 0;
}
}
callUpdateCallback();
requestAnimFrame(stepDecelAnim);
} else {
decelerating = false;
}
}
|
javascript
|
{
"resource": ""
}
|
q62776
|
checkBounds
|
test
|
function checkBounds(restrict) {
var xDiff = 0;
var yDiff = 0;
if (boundXmin !== undefined && targetX < boundXmin) {
xDiff = boundXmin - targetX;
} else if (boundXmax !== undefined && targetX > boundXmax) {
xDiff = boundXmax - targetX;
}
if (boundYmin !== undefined && targetY < boundYmin) {
yDiff = boundYmin - targetY;
} else if (boundYmax !== undefined && targetY > boundYmax) {
yDiff = boundYmax - targetY;
}
if (restrict) {
if (xDiff !== 0) {
targetX = (xDiff > 0) ? boundXmin : boundXmax;
}
if (yDiff !== 0) {
targetY = (yDiff > 0) ? boundYmin : boundYmax;
}
}
return {
x: xDiff,
y: yDiff,
inBounds: xDiff === 0 && yDiff === 0
};
}
|
javascript
|
{
"resource": ""
}
|
q62777
|
initCompDirs
|
test
|
function initCompDirs(){
var compRoot = path.resolve(process.cwd(),'src/components'),
compReg = /^[A-Z]\w+$/;
//['Button', 'Select']
compDirs = fs.readdirSync(compRoot).filter(function(filename){
return compReg.test(filename)
})
return compDirs
}
|
javascript
|
{
"resource": ""
}
|
q62778
|
appendLogToFileStream
|
test
|
function appendLogToFileStream(fileName, newLog, headerLineCount) {
const filePath = path.join(__dirname, '../../', fileName)
const oldChangelog = grunt.file.read(filePath)
.toString()
.split('\n');
let wStr = fs.createWriteStream(filePath)
/** lines used by the default header */
let logHeader = oldChangelog.slice(0, headerLineCount);
/** previous changelog entries */
let prevLogs = oldChangelog.slice(headerLineCount);
var s = new Readable;
s.pipe(wStr);
s.push(logHeader.join('\n') + '\n');
s.push(newLog);
s.push(prevLogs.join('\n'));
s.push(null); // indicates end-of-file basically - the end of the stream)
return wStr;
}
|
javascript
|
{
"resource": ""
}
|
q62779
|
doSeek
|
test
|
function doSeek(length, eocdrNotFoundCallback) {
reader.readUint8Array(reader.size - length, length, function(bytes) {
for (var i = bytes.length - EOCDR_MIN; i >= 0; i--) {
if (bytes[i] === 0x50 && bytes[i + 1] === 0x4b && bytes[i + 2] === 0x05 && bytes[i + 3] === 0x06) {
eocdrCallback(new DataView(bytes.buffer, i, EOCDR_MIN));
return;
}
}
eocdrNotFoundCallback();
}, function() {
onerror(ERR_READ);
});
}
|
javascript
|
{
"resource": ""
}
|
q62780
|
CronJob
|
test
|
function CronJob (sandbox, job) {
/**
* @property name - The name of the cron job
* @property schedule - The cron schedule of the job
* @property next_scheduled_at - The next time this job is scheduled
*/
assign(this, job);
/**
* @property claims - The claims embedded in the Webtask's token
*/
if (job.token) {
this.claims = Decode(job.token);
}
else {
this.claims = {
jtn: job.name,
ten: this.container,
};
}
/**
* @property sandbox - The {@see Sandbox} instance used to create this Webtask instance
*/
this.sandbox = sandbox;
/**
* @property url - The public url that can be used to invoke webtask that the cron job runs
*/
Object.defineProperty(this, 'url', {
enumerable: true,
get: function () {
return this.sandbox.url + '/api/run/' + this.container + '/' + this.name;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q62781
|
Sandbox
|
test
|
function Sandbox (options) {
var securityVersion = 'v1';
this.url = options.url;
this.container = options.container;
this.token = options.token;
this.onBeforeRequest = []
.concat(options.onBeforeRequest)
.filter(hook => typeof hook === 'function');
try {
var typ = Decode(options.token, { header: true }).typ;
if (typ && typ.toLowerCase() === 'jwt') {
securityVersion = 'v2';
}
} catch (_) {
// Ignore jwt decoding failures and assume v1 opaque token
}
this.securityVersion = securityVersion;
}
|
javascript
|
{
"resource": ""
}
|
q62782
|
Webtask
|
test
|
function Webtask (sandbox, token, options) {
if (!options) options = {};
if (sandbox.securityVersion === 'v1') {
try {
/**
* @property claims - The claims embedded in the Webtask's token
*/
this.claims = Decode(token);
/**
* @property token - The token associated with this webtask
*/
this.token = token;
}
catch (_) {
throw new Error('token must be a valid JWT');
}
}
if (sandbox.securityVersion === 'v2') {
if (typeof options.name !== 'string') {
throw new Error('name must be a valid string');
}
this.claims = {
jtn: options.name,
ten: options.container || sandbox.container,
}
}
/**
* @property sandbox - The {@see Sandbox} instance used to create this Webtask instance
*/
this.sandbox = sandbox;
/**
* @property meta - The metadata associated with this webtask
*/
this.meta = options.meta || {};
/**
* @property secrets - The secrets associated with this webtask if `decrypt=true`
*/
this.secrets = options.secrets;
/**
* @property code - The code associated with this webtask if `fetch_code=true`
*/
this.code = options.code;
/**
* @property container - The container name in which the webtask will run
*/
Object.defineProperty(this, 'container', {
enumerable: true,
get: function () {
return options.container || this.sandbox.container;
}
});
/**
* @property url - The public url that can be used to invoke this webtask
*/
Object.defineProperty(this, 'url', {
enumerable: true,
get: function () {
var url = options.webtask_url;
if (!url) {
if (this.claims.host) {
var surl = Url.parse(this.sandbox.url);
url = surl.protocol + '//' + this.claims.host + (surl.port ? (':' + surl.port) : '') + '/' + this.sandbox.container;
}
else {
url = this.sandbox.url + '/api/run/' + this.sandbox.container;
}
if (this.claims.jtn) url += '/' + this.claims.jtn;
else url += '?key=' + this.token;
}
return url;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q62783
|
wrappedPromise
|
test
|
function wrappedPromise(executor) {
if (!(this instanceof wrappedPromise)) {
return Promise(executor);
}
if (typeof executor !== 'function') {
return new Promise(executor);
}
var context, args;
var promise = new Promise(wrappedExecutor);
promise.__proto__ = wrappedPromise.prototype;
try {
executor.apply(context, args);
} catch (err) {
args[1](err);
}
return promise;
function wrappedExecutor(resolve, reject) {
context = this;
args = [wrappedResolve, wrappedReject];
// These wrappers create a function that can be passed a function and an argument to
// call as a continuation from the resolve or reject.
function wrappedResolve(val) {
ensureAslWrapper(promise, false);
return resolve(val);
}
function wrappedReject(val) {
ensureAslWrapper(promise, false);
return reject(val);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q62784
|
union
|
test
|
function union(dest, added) {
var destLength = dest.length;
var addedLength = added.length;
var returned = [];
if (destLength === 0 && addedLength === 0) return returned;
for (var j = 0; j < destLength; j++) returned[j] = dest[j];
if (addedLength === 0) return returned;
for (var i = 0; i < addedLength; i++) {
var missing = true;
for (j = 0; j < destLength; j++) {
if (dest[j].uid === added[i].uid) {
missing = false;
break;
}
}
if (missing) returned.push(added[i]);
}
return returned;
}
|
javascript
|
{
"resource": ""
}
|
q62785
|
simpleWrap
|
test
|
function simpleWrap(original, list, length) {
inAsyncTick = true;
for (var i = 0; i < length; ++i) {
var listener = list[i];
if (listener.create) listener.create(listener.data);
}
inAsyncTick = false;
// still need to make sure nested async calls are made in the context
// of the listeners active at their creation
return function () {
listenerStack.push(listeners);
listeners = union(list, listeners);
var returned = original.apply(this, arguments);
listeners = listenerStack.pop();
return returned;
};
}
|
javascript
|
{
"resource": ""
}
|
q62786
|
wrapCallback
|
test
|
function wrapCallback(original) {
var length = listeners.length;
// no context to capture, so avoid closure creation
if (length === 0) return original;
// capture the active listeners as of when the wrapped function was called
var list = listeners.slice();
for (var i = 0; i < length; ++i) {
if (list[i].flags > 0) return asyncWrap(original, list, length);
}
return simpleWrap(original, list, length);
}
|
javascript
|
{
"resource": ""
}
|
q62787
|
test
|
function (dir, options, internal) {
// Parse arguments.
options = options || largest.options;
// Get all file stats in parallel.
return fs.readdirAsync(dir)
.then (function (files) {
var paths = _.map(files, function (file) { return path.join(dir, file); });
return Promise.all(_.map(paths, function (path) { return fs.statAsync(path); }))
.then(function (stats) { return [paths, stats]; });
})
// Build up a list of possible candidates, recursing into subfolders if requested.
.spread(function (paths, stats) {
return Promise.all(
_.map(stats, function (stat, i) {
if (stat.isFile()) return Promise.resolve({ path: paths[i], size: stat.size, searched: 1 });
return options.recurse ? largest(paths[i], options, true) : Promise.resolve(null);
})
);
})
// Choose the best candidate.
.then(function (candidates) {
return _(candidates)
.compact()
.reduce(function (best, cand) {
if (cand.size > best.size) var temp = cand, cand = best, best = temp;
best.searched += cand.searched;
return best;
});
})
// Add a preview if requested (but skip if this is an internal step in a recursive search).
.then(function (result) {
if (result && options.preview && !internal) {
var fd_;
return fs.openAsync(result.path, 'r')
.then(function (fd) {
fd_ = fd;
var buffer = new Buffer(40);
return fs.readAsync(fd, buffer, 0, 40, 0);
})
.spread(function (bytesRead, buffer) {
result.preview = buffer.toString('utf-8', 0, bytesRead);
return fs.closeAsync(fd_);
})
.then(function () {
return result;
});
} else {
return result; // Return without adding preview.
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q62788
|
makeAsyncFunc
|
test
|
function makeAsyncFunc(config) {
// Validate the specified configuration
config.validate();
// Create an async function tailored to the given options.
var result = function async(bodyFunc) {
// Create a semaphore for limiting top-level concurrency, if specified in options.
var semaphore = config.maxConcurrency ? new Semaphore(config.maxConcurrency) : Semaphore.unlimited;
// Choose and run the appropriate function factory based on whether the result should be iterable.
var makeFunc = config.isIterable ? makeAsyncIterator : makeAsyncNonIterator;
var result = makeFunc(bodyFunc, config, semaphore);
// Ensure the suspendable function's arity matches that of the function it wraps.
var arity = bodyFunc.length;
if (config.acceptsCallback)
++arity;
result = makeFuncWithArity(result, arity);
return result;
};
// Add the mod() function, and return the result.
result.mod = makeModFunc(config);
return result;
}
|
javascript
|
{
"resource": ""
}
|
q62789
|
makeAsyncIterator
|
test
|
function makeAsyncIterator(bodyFunc, config, semaphore) {
// Return a function that returns an iterator.
return function iterable() {
// Capture the initial arguments used to start the iterator, as an array.
var startupArgs = new Array(arguments.length + 1); // Reserve 0th arg for the yield function.
for (var i = 0, len = arguments.length; i < len; ++i)
startupArgs[i + 1] = arguments[i];
// Create a yield() function tailored for this iterator.
var yield_ = function (expr) {
// Ensure this function is executing inside a fiber.
if (!Fiber.current) {
throw new Error('await functions, yield functions, and value-returning suspendable ' +
'functions may only be called from inside a suspendable function. ');
}
// Notify waiters of the next result, then suspend the iterator.
if (runContext.callback)
runContext.callback(null, { value: expr, done: false });
if (runContext.resolver)
runContext.resolver.resolve({ value: expr, done: false });
Fiber.yield();
};
// Insert the yield function as the first argument when starting the iterator.
startupArgs[0] = yield_;
// Create the iterator.
var runContext = new RunContext(bodyFunc, this, startupArgs);
var iterator = new AsyncIterator(runContext, semaphore, config.returnValue, config.acceptsCallback);
// Wrap the given bodyFunc to properly complete the iteration.
runContext.wrapped = function () {
var len = arguments.length, args = new Array(len);
for (var i = 0; i < len; ++i)
args[i] = arguments[i];
bodyFunc.apply(this, args);
iterator.destroy();
return { done: true };
};
// Return the iterator.
return iterator;
};
}
|
javascript
|
{
"resource": ""
}
|
q62790
|
makeAsyncNonIterator
|
test
|
function makeAsyncNonIterator(bodyFunc, config, semaphore) {
// Return a function that executes fn in a fiber and returns a promise of fn's result.
return function nonIterable() {
// Get all the arguments passed in, as an array.
var argsAsArray = new Array(arguments.length);
for (var i = 0; i < argsAsArray.length; ++i)
argsAsArray[i] = arguments[i];
// Remove concurrency restrictions for nested calls, to avoid race conditions.
if (FiberMgr.isExecutingInFiber())
this._semaphore = Semaphore.unlimited;
// Configure the run context.
var runContext = new RunContext(bodyFunc, this, argsAsArray, function () { return semaphore.leave(); });
if (config.returnValue !== Config.NONE) {
var resolver = defer();
runContext.resolver = resolver;
}
if (config.acceptsCallback && argsAsArray.length && _.isFunction(argsAsArray[argsAsArray.length - 1])) {
var callback = argsAsArray.pop();
runContext.callback = callback;
}
// Execute bodyFunc to completion in a coroutine. For thunks, this is a lazy operation.
if (config.returnValue === Config.THUNK) {
var thunk = function (done) {
if (done)
resolver.promise.then(function (val) { return done(null, val); }, function (err) { return done(err); });
semaphore.enter(function () { return FiberMgr.create().run(runContext); });
};
}
else {
semaphore.enter(function () { return FiberMgr.create().run(runContext); });
}
// Return the appropriate value.
switch (config.returnValue) {
case Config.PROMISE: return resolver.promise;
case Config.THUNK: return thunk;
case Config.RESULT: return await(resolver.promise);
case Config.NONE: return;
}
};
}
|
javascript
|
{
"resource": ""
}
|
q62791
|
traverseClone
|
test
|
function traverseClone(o, visitor) {
var result;
if (_.isArray(o)) {
var len = o.length;
result = new Array(len);
for (var i = 0; i < len; ++i) {
result[i] = traverseClone(o[i], visitor);
visitor(result, i);
}
}
else if (_.isPlainObject(o)) {
result = {};
for (var key in o) {
if (o.hasOwnProperty(key)) {
result[key] = traverseClone(o[key], visitor);
visitor(result, key);
}
}
}
else {
result = o;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q62792
|
thunkToPromise
|
test
|
function thunkToPromise(thunk) {
return new Promise(function (resolve, reject) {
var callback = function (err, val) { return (err ? reject(err) : resolve(val)); };
thunk(callback);
});
}
|
javascript
|
{
"resource": ""
}
|
q62793
|
test
|
function (dir) {
var files = fs.readdirSync(dir);
// Get all file stats in parallel.
var paths = _.map(files, function (file) { return path.join(dir, file); });
var stats = _.map(paths, function (path) { return fs.statSync(path); });
// Count the files.
return _.filter(stats, function (stat) { return stat.isFile(); }).length;
}
|
javascript
|
{
"resource": ""
}
|
|
q62794
|
scopedCopyIndex
|
test
|
async function scopedCopyIndex(client, sourceIndex, targetIndex) {
const { taskID } = await client.copyIndex(
sourceIndex.indexName,
targetIndex.indexName,
['settings', 'synonyms', 'rules']
);
return targetIndex.waitTask(taskID);
}
|
javascript
|
{
"resource": ""
}
|
q62795
|
moveIndex
|
test
|
async function moveIndex(client, sourceIndex, targetIndex) {
const { taskID } = await client.moveIndex(
sourceIndex.indexName,
targetIndex.indexName
);
return targetIndex.waitTask(taskID);
}
|
javascript
|
{
"resource": ""
}
|
q62796
|
indexExists
|
test
|
async function indexExists(index) {
try {
const { nbHits } = await index.search();
return nbHits > 0;
} catch (e) {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q62797
|
loadModule
|
test
|
function loadModule(moduleName) {
var module = modules[moduleName];
if (module !== undefined) {
return module;
}
// This uses a switch for static require analysis
switch (moduleName) {
case 'charset':
module = require('./lib/charset');
break;
case 'encoding':
module = require('./lib/encoding');
break;
case 'language':
module = require('./lib/language');
break;
case 'mediaType':
module = require('./lib/mediaType');
break;
default:
throw new Error('Cannot find module \'' + moduleName + '\'');
}
// Store to prevent invoking require()
modules[moduleName] = module;
return module;
}
|
javascript
|
{
"resource": ""
}
|
q62798
|
parseAcceptLanguage
|
test
|
function parseAcceptLanguage(accept) {
var accepts = accept.split(',');
for (var i = 0, j = 0; i < accepts.length; i++) {
var language = parseLanguage(accepts[i].trim(), i);
if (language) {
accepts[j++] = language;
}
}
// trim accepts
accepts.length = j;
return accepts;
}
|
javascript
|
{
"resource": ""
}
|
q62799
|
parseLanguage
|
test
|
function parseLanguage(str, i) {
var match = simpleLanguageRegExp.exec(str);
if (!match) return null;
var prefix = match[1],
suffix = match[2],
full = prefix;
if (suffix) full += "-" + suffix;
var q = 1;
if (match[3]) {
var params = match[3].split(';')
for (var j = 0; j < params.length; j++) {
var p = params[j].split('=');
if (p[0] === 'q') q = parseFloat(p[1]);
}
}
return {
prefix: prefix,
suffix: suffix,
q: q,
i: i,
full: full
};
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.