_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q11800
|
compareNames
|
train
|
function compareNames(a, b) {
if (!isArray(a)) a = splitAuthorString(a);
if (!isArray(b)) b = splitAuthorString(b);
var aPos = 0, bPos = 0;
var authorLimit = Math.min(a.length, b.length);
var failed = false;
while (aPos < authorLimit && bPos < authorLimit) {
if (fuzzyStringCompare(a[aPos], b[bPos])) { // Direct or fuzzy matching of entire strings
aPos++;
bPos++;
} else {
var aAuth = splitAuthor(a[aPos]);
var bAuth = splitAuthor(b[bPos]);
var nameLimit = Math.min(aAuth.length, bAuth.length);
var nameMatches = 0;
for (var n = 0; n < nameLimit; n++) {
if (
aAuth[n] == bAuth[n] || // Direct match
aAuth[n].length == 1 && bAuth[n].substr(0, 1) || // A is initial and B is full name
bAuth[n].length == 1 && aAuth[n].substr(0, 1) ||
(aAuth[n].length > 1 && bAuth[n].length > 1 && fuzzyStringCompare(aAuth[n], bAuth[n], 3))
) {
nameMatches++;
}
}
if (nameMatches >= nameLimit) {
aPos++;
bPos++;
} else {
failed = true;
}
break;
}
}
return !failed;
}
|
javascript
|
{
"resource": ""
}
|
q11801
|
train
|
function(call, error, response, body, codes, reject) {
if (error) {
if (typeof error == 'string') {
var message = util.format("Unexpected error on %s %s, reason : %s",
call.method, call.uri, error);
util.log(message);
var exception = new Error(message);
exception.call = call;
reject(exception);
} else {
util.log(error);
reject(error);
}
return true;
} else if (codes.indexOf(response.statusCode) <0 ) {
var message;
if (body.message){
message = util.format("Unexpected response code %s on %s %s, reason : %s",
response.statusCode, call.method, call.uri, body.message);
} else {
message = util.format("Unexpected response code %s on %s %s",
response.statusCode, call.method, call.uri);
}
util.log(message);
var exception = new Error(message);
exception.call = call;
exception.reason = body;
reject(exception);
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q11802
|
Element
|
train
|
function Element (driver, parent, selector, id) {
this._driver = driver;
this._parent = parent;
this._selector = selector;
this._id = id;
}
|
javascript
|
{
"resource": ""
}
|
q11803
|
train
|
function (benchmark, simultaneousRequests, done) {
var pageName,
engineName;
this.benchmark = benchmark;
this.simultaneousRequests = simultaneousRequests;
this.done = done;
if (typeof simultaneousRequests !== "number") {
throw new Error("simultaneousRequests must be an integer; " + (typeof simultaneousRequests) + " passed");
}
if (simultaneousRequests < 1) {
throw new Error("simultaneousRequests must be at least 1; " + simultaneousRequests + " passed");
}
this.responseTimes = {};
for (pageName in this.benchmark.pages) {
this.responseTimes[pageName] = {};
for (engineName in this.benchmark.engines) {
this.responseTimes[pageName][engineName] = [];
}
}
this.totals = {};
}
|
javascript
|
{
"resource": ""
}
|
|
q11804
|
visit
|
train
|
function visit() {
if (this.isBlacklisted()) return false;
if (this.opts.shouldSkip && this.opts.shouldSkip(this)) return false;
this.call("enter");
if (this.shouldSkip) {
return this.shouldStop;
}
var node = this.node;
var opts = this.opts;
if (node) {
if (Array.isArray(node)) {
// traverse over these replacement nodes we purposely don't call exitNode
// as the original node has been destroyed
for (var i = 0; i < node.length; i++) {
_index2["default"].node(node[i], opts, this.scope, this.state, this, this.skipKeys);
}
} else {
_index2["default"].node(node, opts, this.scope, this.state, this, this.skipKeys);
this.call("exit");
}
}
return this.shouldStop;
}
|
javascript
|
{
"resource": ""
}
|
q11805
|
JSONPath
|
train
|
function JSONPath(expression, options) {
if (!options || typeof options != 'object') {
options = {};
}
if (!options.resultType) {
options.resultType = 'value';
}
if (typeof options.flatten == 'undefined') {
options.flatten = false;
}
if (typeof options.wrap == 'undefined') {
options.wrap = true;
}
if (typeof options.sandbox == 'undefined') {
options.sandbox = {};
}
this.expression = expression;
this.options = options;
this.resultType = options.resultType;
}
|
javascript
|
{
"resource": ""
}
|
q11806
|
getParentPath
|
train
|
function getParentPath(path, sep) {
if (!is.nonEmptyStr(path)) return false;
if (!is.nonEmptyStr(sep)) sep = defaultSepChar;
// create new path and remove leading and trailing sep chars
var properties = filter(path.split(sep), function(elem) {
return is.str(elem) && elem.length;
});
// create a parent path
var parentPath = '';
for (var i=0; i<properties.length-1; i++) {
parentPath += properties[i];
parentPath += (i < properties.length-2) ? sep : '';
}
return parentPath.length ? parentPath : false;
}
|
javascript
|
{
"resource": ""
}
|
q11807
|
createUnionTypeAnnotation
|
train
|
function createUnionTypeAnnotation(types) {
var flattened = removeTypeDuplicates(types);
if (flattened.length === 1) {
return flattened[0];
} else {
return t.unionTypeAnnotation(flattened);
}
}
|
javascript
|
{
"resource": ""
}
|
q11808
|
removeTypeDuplicates
|
train
|
function removeTypeDuplicates(nodes) {
var generics = {};
var bases = {};
// store union type groups to circular references
var typeGroups = [];
var types = [];
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (!node) continue;
// detect duplicates
if (types.indexOf(node) >= 0) {
continue;
}
// this type matches anything
if (t.isAnyTypeAnnotation(node)) {
return [node];
}
//
if (t.isFlowBaseAnnotation(node)) {
bases[node.type] = node;
continue;
}
//
if (t.isUnionTypeAnnotation(node)) {
if (typeGroups.indexOf(node.types) < 0) {
nodes = nodes.concat(node.types);
typeGroups.push(node.types);
}
continue;
}
// find a matching generic type and merge and deduplicate the type parameters
if (t.isGenericTypeAnnotation(node)) {
var _name = node.id.name;
if (generics[_name]) {
var existing = generics[_name];
if (existing.typeParameters) {
if (node.typeParameters) {
existing.typeParameters.params = removeTypeDuplicates(existing.typeParameters.params.concat(node.typeParameters.params));
}
} else {
existing = node.typeParameters;
}
} else {
generics[_name] = node;
}
continue;
}
types.push(node);
}
// add back in bases
for (var type in bases) {
types.push(bases[type]);
}
// add back in generics
for (var _name2 in generics) {
types.push(generics[_name2]);
}
return types;
}
|
javascript
|
{
"resource": ""
}
|
q11809
|
createTypeAnnotationBasedOnTypeof
|
train
|
function createTypeAnnotationBasedOnTypeof(type) {
if (type === "string") {
return t.stringTypeAnnotation();
} else if (type === "number") {
return t.numberTypeAnnotation();
} else if (type === "undefined") {
return t.voidTypeAnnotation();
} else if (type === "boolean") {
return t.booleanTypeAnnotation();
} else if (type === "function") {
return t.genericTypeAnnotation(t.identifier("Function"));
} else if (type === "object") {
return t.genericTypeAnnotation(t.identifier("Object"));
} else if (type === "symbol") {
return t.genericTypeAnnotation(t.identifier("Symbol"));
} else {
throw new Error("Invalid typeof value");
}
}
|
javascript
|
{
"resource": ""
}
|
q11810
|
deepEquals
|
train
|
function deepEquals(a, b) {
var i, key;
if (isScalar(a) && isScalar(b)) {
return scalarEquals(a, b);
}
if (a === null || b === null || a === undefined || b === undefined) return a === b;
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) return false;
for (i = 0; i < a.length; i++) {
if (!deepEquals(a[i], b[i])) return false;
}
return true;
} else if (!Array.isArray(a) && !Array.isArray(b)) {
for (key in a) {
if (!deepEquals(a[key], b[key])) return false;
}
for (key in b) {
if (!deepEquals(a[key], b[key])) return false;
}
return true;
} else {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q11811
|
deepCopy
|
train
|
function deepCopy(obj) {
var res;
var i;
var key;
if (isTerminal(obj)) {
res = obj;
} else if (Array.isArray(obj)) {
res = Array(obj.length);
for (i = 0; i < obj.length; i++) {
res[i] = deepCopy(obj[i]);
}
} else {
res = {};
for (key in obj) {
res[key] = deepCopy(obj[key]);
}
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
q11812
|
setPath
|
train
|
function setPath(obj, path, value) {
var cur = obj;
var parts = path.split('.');
var i;
for (i = 0; i < parts.length; i++) {
if (i === parts.length - 1) {
cur[parts[i]] = value;
} else {
if (isScalar(cur[parts[i]])) cur[parts[i]] = {};
cur = cur[parts[i]];
}
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q11813
|
deletePath
|
train
|
function deletePath(obj, path) {
var cur = obj;
var parts = path.split('.');
var i;
for (i = 0; i < parts.length; i++) {
if (i === parts.length - 1) {
delete cur[parts[i]];
} else {
if (isScalar(cur[parts[i]])) {
return obj;
}
cur = cur[parts[i]];
}
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q11814
|
getPath
|
train
|
function getPath(obj, path, allowSkipArrays) {
if (path === null || path === undefined) return obj;
var cur = obj;
var parts = path.split('.');
var i;
for (i = 0; i < parts.length; i++) {
if (isScalar(cur)) return undefined;
if (Array.isArray(cur) && allowSkipArrays && !(/^[0-9]+$/.test(parts[i])) && cur.length === 1) {
cur = cur[0];
i--;
} else {
cur = cur[parts[i]];
}
}
return cur;
}
|
javascript
|
{
"resource": ""
}
|
q11815
|
merge
|
train
|
function merge(/* object, sources */) {
var lastSource = arguments[arguments.length - 1];
if (
typeof lastSource === 'function' ||
(
arguments.length > 2 &&
Array.isArray(lastSource) &&
lastSource.indexOf(arguments[1]) >= 0
)
) {
return mergeHeavy.apply(null, arguments);
} else {
return mergeLight.apply(null, arguments);
}
}
|
javascript
|
{
"resource": ""
}
|
q11816
|
dottedDiff
|
train
|
function dottedDiff(val1, val2) {
if (isScalar(val1) && isScalar(val2)) {
return val1 === val2 ? [] : '';
} else {
return Object.keys(addDottedDiffFieldsToSet({}, '', val1, val2));
}
}
|
javascript
|
{
"resource": ""
}
|
q11817
|
objectHash
|
train
|
function objectHash(obj) {
var hash = crypto.createHash('md5');
hash.update(makeHashKey(obj));
return hash.digest('hex');
}
|
javascript
|
{
"resource": ""
}
|
q11818
|
sanitizeDate
|
train
|
function sanitizeDate(val) {
if (!val) return null;
if (_.isDate(val)) return val;
if (_.isString(val)) return new Date(Date.parse(val));
if (_.isNumber(val)) return new Date(val);
if (_.isObject(val) && val.date) return sanitizeDate(val.date);
return null;
}
|
javascript
|
{
"resource": ""
}
|
q11819
|
render
|
train
|
async function render(view, options) {
view += settings.viewExt;
const viewPath = path.join(settings.root, view);
debug(`render: ${viewPath}`);
// get from cache
if (settings.cache && cache[viewPath]) {
return cache[viewPath].call(options.scope, options);
}
const tpl = await fs.readFile(viewPath, 'utf8');
// override `ejs` node_module `resolveInclude` function
ejs.resolveInclude = function(name, filename, isDir) {
if (!path.extname(name)) {
name += settings.viewExt;
}
return parentResolveInclude(name, filename, isDir);
}
const fn = ejs.compile(tpl, {
filename: viewPath,
_with: settings._with,
compileDebug: settings.debug && settings.compileDebug,
debug: settings.debug,
delimiter: settings.delimiter
});
if (settings.cache) {
cache[viewPath] = fn;
}
return fn.call(options.scope, options);
}
|
javascript
|
{
"resource": ""
}
|
q11820
|
parse
|
train
|
function parse(code) {
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
opts.allowHashBang = true;
opts.sourceType = "module";
opts.ecmaVersion = Infinity;
opts.plugins = {
jsx: true,
flow: true
};
opts.features = {};
for (var key in _transformation2["default"].pipeline.transformers) {
opts.features[key] = true;
}
var ast = babylon.parse(code, opts);
if (opts.onToken) {
// istanbul ignore next
var _opts$onToken;
(_opts$onToken = opts.onToken).push.apply(_opts$onToken, ast.tokens);
}
if (opts.onComment) {
// istanbul ignore next
var _opts$onComment;
(_opts$onComment = opts.onComment).push.apply(_opts$onComment, ast.comments);
}
return ast.program;
}
|
javascript
|
{
"resource": ""
}
|
q11821
|
renderToString
|
train
|
function renderToString(meta) {
if (meta.html) return meta.html.source
var output = [
'<!DOCTYPE html>', '<html>', '<head>', '<meta charset="utf8" />'
]
var { head, body } = meta
head.metas.forEach(e => output.push(renderMeta(e.name, e.http, e.content)))
head.styles.forEach(e => output.push(renderStyle(e.type, e.src, e.source)))
head.scripts.forEach(e => output.push(renderScript(e.type, e.src, e.source)))
if (head.title) output.push(`<title>${head.title}</title>`)
if (head.icon) output.push(renderIcon(head.icon.type, head.icon.src))
output.push('</head>', '<body>')
if (body.holder) output.push(body.holder.source)
body.injectA.forEach(e => output.push(renderScript(e.type, e.src, e.source)))
body.scripts.forEach(e => output.push(renderScript(e.type, e.src, e.source)))
body.injectB.forEach(e => output.push(renderScript(e.type, e.src, e.source)))
output.push('</body>', '</html>')
return concatString(output)
}
|
javascript
|
{
"resource": ""
}
|
q11822
|
getRoute
|
train
|
function getRoute(route) {
for (var key in settings.routes) {
if (key === route) {
return settings.routes[key];
}
}
}
|
javascript
|
{
"resource": ""
}
|
q11823
|
compareUrlRoute
|
train
|
function compareUrlRoute(currentURL, currentRoute) {
var regex = /\{(.*)\}/i;
var arraySize = currentRoute.length,
testValue = false;
for (var i = 0; i < arraySize; i++) {
var dynamic = regex.exec(currentRoute[i]);
if (dynamic) {
document.routeParams[dynamic[1]] = currentURL[i];
} else {
if (currentRoute[i] === currentURL[i]) {
testValue = true;
}
}
}
return testValue;
}
|
javascript
|
{
"resource": ""
}
|
q11824
|
train
|
function (commit, until) {
var checker = this;
until = !isNaN(until) ? until : (new Date()).getTime() + (this.getOption('timeout'));
if ((new Date()).getTime() > until) {
return this.handleError('Timeout');
}
return this.getBuilds()
.then(function (builds) {
if (undefined !== builds.message) {
return checker.handleError(builds.message);
}
var finder = new BuildFinder(builds),
builds = finder.findByCommit(commit);
if (null === builds) {
return checker.handleError('Build not found');
}
return builds;
}, this.handleError)
.then(function (builds) {
var successfulBuilds = 0;
for (var i = 0; i < builds.length; i++) {
if (builds[i].isSuccess()) {
successfulBuilds++;
} else if (builds[i].isFailure() || !checker.getOption('retryOnRunning')) {
return checker.handleError('Invalid status for CircleCI build: "' + builds[i].getStatus() + '"')
}
}
if (successfulBuilds === builds.length) {
return true;
}
// Sleep for 10 seconds by default
var promise = sleep(checker.getOption('retryAfter'));
return promise.then(function () {
return checker.checkCommit(commit, until);
});
}, this.handleError);
}
|
javascript
|
{
"resource": ""
}
|
|
q11825
|
clientsGenerator
|
train
|
function clientsGenerator()
{
var i = 0,
len = clientsList.length;
for( ; i < len; i++ )
{
var client = { name : clientsList[ i ].name };
var time = _.timeNow();
setTimeout(( function( client, time )
{
/* sending clients to shop */
this.barberShopArrive( client, time );
}).bind( this, client, time ), clientsList[ i ].arrivedTime );
}
}
|
javascript
|
{
"resource": ""
}
|
q11826
|
loadEntities
|
train
|
function loadEntities() {
// Uncompress the base charmap
charMap = require('./string_entities_map.js');
HTMLEntities = {};
for (key in charMap) {
for (i = 0; i < charMap[key].length; i++) {
HTMLEntities[charMap[key][i]] = key;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q11827
|
isCharVowel
|
train
|
function isCharVowel(char = '', includeY = true) {
if (isEmpty(char)) return false;
const regexp = includeY ? /[aeiouy]/ : /[aeiou]/;
return char.toLowerCase().charAt(0).search(regexp) !== -1;
}
|
javascript
|
{
"resource": ""
}
|
q11828
|
convertFullwidthCharsToASCII
|
train
|
function convertFullwidthCharsToASCII(text = '') {
const asciiChars = [...text].map((char, index) => {
const code = char.charCodeAt(0);
const lower = isCharInRange(char, LOWERCASE_FULLWIDTH_START, LOWERCASE_FULLWIDTH_END);
const upper = isCharInRange(char, UPPERCASE_FULLWIDTH_START, UPPERCASE_FULLWIDTH_END);
if (lower) {
return String.fromCharCode((code - LOWERCASE_FULLWIDTH_START) + LOWERCASE_START);
} else if (upper) {
return String.fromCharCode((code - UPPERCASE_FULLWIDTH_START) + UPPERCASE_START);
}
return char;
});
return asciiChars.join('');
}
|
javascript
|
{
"resource": ""
}
|
q11829
|
train
|
function(){
var view = "_design/searchJob/_view/jobstatus?key=" + JSON.stringify('UPLOADING');
return server.methods.clusterprovider.getView(view)
.then(function(docs){
return Promise.map(_.pluck(docs, "value"), server.methods.cronprovider.addJobToUpdateQueue);
})
.catch(console.error);
}
|
javascript
|
{
"resource": ""
}
|
|
q11830
|
train
|
function (options) {
if (!options) // fast path
return _defaults;
var ret = _.extend({}, _defaults);
_.each(['N', 'g', 'k'], function (p) {
if (options[p]) {
if (typeof options[p] === "string")
ret[p] = new BigInteger(options[p], 16);
else if (options[p] instanceof BigInteger)
ret[p] = options[p];
else
throw new Error("Invalid parameter: " + p);
}
});
if (options.hash)
ret.hash = function (x) { return options.hash(x).toLowerCase(); };
if (!options.k && (options.N || options.g || options.hash)) {
ret.k = ret.hash(ret.N.toString(16) + ret.g.toString(16));
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q11831
|
doMultipleInheritance
|
train
|
function doMultipleInheritance(new_constructor, parent_constructor, proto) {
var more;
if (proto == null) {
proto = Object.create(new_constructor.prototype);
}
// See if this goes even deeper FIRST
// (older properties could get overwritten)
more = Object.getPrototypeOf(parent_constructor.prototype);
if (more.constructor !== Object) {
// Recurse with the earlier constructor
doMultipleInheritance(new_constructor, more.constructor, proto);
}
// Inject the enumerable and non-enumerable properties of the parent
Collection.Object.inject(proto, parent_constructor.prototype);
return proto;
}
|
javascript
|
{
"resource": ""
}
|
q11832
|
getNamespace
|
train
|
function getNamespace(namespace) {
var result,
name,
data;
// Try getting the namespace
if (!namespace) {
result = Blast.Classes;
} else {
result = Obj.path(Blast.Classes, namespace);
}
if (result == null) {
name = namespace.split('.');
name = name[name.length - 1];
result = Collection.Function.create(name, function() {
var instance;
if (!result[name]) {
throw new Error('Could not find class "' + name + '" in namespace "' + namespace + '"');
}
// Create the object instance
instance = Object.create(result[name].prototype);
// Apply the constructor
result[name].apply(instance, arguments);
return instance;
});
// Add a getter to get the main class of this namespace
Blast.defineGet(result, 'main_class', function getMainClass() {
return result[name];
});
// Remember this is a namespace
result.is_namespace = true;
// Create the namespace object
Obj.setPath(Blast.Classes, namespace, result);
// Emit the creation of this namespace
if (Blast.emit) {
data = {
type : 'namespace',
namespace : namespace
};
Blast.emit(data, namespace);
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q11833
|
getClass
|
train
|
function getClass(path) {
var pieces = path.split('.'),
result;
result = Obj.path(Blast.Classes, path);
if (typeof result == 'function') {
if (result.is_namespace) {
result = result[result.name];
}
return result;
}
result = Obj.path(Blast.Globals, path);
if (typeof result == 'function') {
if (result.is_namespace) {
result = result[result.name];
}
return result;
}
}
|
javascript
|
{
"resource": ""
}
|
q11834
|
getClassPathInfo
|
train
|
function getClassPathInfo(path) {
var result = {},
namespace,
name,
temp;
// See what's there
temp = Obj.path(Blast.Classes, path);
// Is there nothing at the current path?
if (!temp) {
if (path.indexOf('.') > -1) {
// Split the path
temp = path.split('.');
// The last part is actually the name of the class
name = temp.pop();
// The namespace is what's left over
namespace = temp.join('.');
} else {
// There is no real "path", it's just the name
name = path;
// So there is no namespace
namespace = '';
}
} else {
// Is the found function a namespace
if (temp && temp.is_namespace) {
// The name of the class is the same as the namespace
name = temp.name;
// The namespace path is the entire path
namespace = path;
// The full path actually needs the name again
path = path + '.' + name;
} else if (temp) {
// We found a class function
// The namespace should be on this class
namespace = temp.namespace || '';
// The name is the name of the found class
name = temp.name;
} else {
namespace = '';
name = path;
}
}
result.name = name;
result.namespace = namespace;
result.path = path;
result.class = Obj.path(Blast.Classes, path);
result.namespace_wrapper = Obj.path(Blast.Classes, namespace);
if (!namespace && !result.class && typeof Blast.Globals[name] == 'function') {
result.class = Blast.Globals[name];
}
if (!result.namespace_wrapper) {
result.namespace_wrapper = getNamespace(namespace);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q11835
|
doConstitutors
|
train
|
function doConstitutors(constructor) {
var waiting,
tasks,
i;
if (has_constituted.get(constructor)) {
return;
}
has_constituted.set(constructor, true);
tasks = constructor.constitutors;
if (tasks) {
for (i = 0; i < tasks.length; i++) {
doConstructorTask(constructor, tasks[i]);
}
}
waiting = waiting_children.get(constructor);
if (!waiting || !waiting.length) {
return;
}
for (i = 0; i < waiting.length; i++) {
doConstitutors(waiting[i]);
}
}
|
javascript
|
{
"resource": ""
}
|
q11836
|
doConstructorTask
|
train
|
function doConstructorTask(constructor, task) {
var finished;
finished = finished_constitutors.get(constructor);
if (!finished) {
finished = [];
finished_constitutors.set(constructor, finished);
}
if (finished.indexOf(task) == -1) {
task.call(constructor);
finished.push(task);
}
}
|
javascript
|
{
"resource": ""
}
|
q11837
|
applyDecoration
|
train
|
function applyDecoration(constructor, key, options) {
if (options.kind == 'method') {
return Fn.setMethod(constructor, key, options.descriptor);
}
throw new Error('Decorating ' + options.kind + ' is not yet implemented');
}
|
javascript
|
{
"resource": ""
}
|
q11838
|
setStaticProperty
|
train
|
function setStaticProperty(key, getter, setter, inherit) {
return Fn.setStaticProperty(this, key, getter, setter, inherit);
}
|
javascript
|
{
"resource": ""
}
|
q11839
|
compose
|
train
|
function compose(key, compositor, traits) {
return Fn.compose(this.prototype, key, compositor, traits);
}
|
javascript
|
{
"resource": ""
}
|
q11840
|
ensureConstructorStaticMethods
|
train
|
function ensureConstructorStaticMethods(newConstructor) {
if (typeof newConstructor.setMethod !== 'function') {
Blast.defineValue(newConstructor, protoPrepareStaticProperty);
Blast.defineValue(newConstructor, protoSetStaticProperty);
Blast.defineValue(newConstructor, protoPrepareProperty);
Blast.defineValue(newConstructor, protoEnforceProperty);
Blast.defineValue(newConstructor, protoDecorateMethod);
Blast.defineValue(newConstructor, protoStaticCompose);
Blast.defineValue(newConstructor, protoGetChildren);
Blast.defineValue(newConstructor, protoSetProperty);
Blast.defineValue(newConstructor, protoConstitute);
Blast.defineValue(newConstructor, protoSetStatic);
Blast.defineValue(newConstructor, protoSetMethod);
Blast.defineValue(newConstructor, protoCompose);
if (newConstructor.extend == null) {
Blast.defineValue(newConstructor, 'extend', protoExtend);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q11841
|
map
|
train
|
function map(transform) {
var cb = makeAsync(transform, 2);
return through.obj(function (value, enc, next) {
cb(value, next);
});
}
|
javascript
|
{
"resource": ""
}
|
q11842
|
reduce
|
train
|
function reduce(reducer, initialValue) {
var accumulator = initialValue;
var cb = makeAsync(reducer, 3);
return through.obj(
function transform(chunk, enc, next) {
cb(accumulator, chunk, function (err, result) {
accumulator = result;
next(err);
});
},
function Flush(next) {
this.push(accumulator);
next();
}
);
}
|
javascript
|
{
"resource": ""
}
|
q11843
|
copy
|
train
|
function copy(acc, k) {
const val = x[k]
let cpy
if (Array.isArray(val)) {
cpy = val.slice(0)
} else {
cpy = val
}
acc[k] = cpy
return acc
}
|
javascript
|
{
"resource": ""
}
|
q11844
|
RCS
|
train
|
function RCS (input, opts) {
opts = opts || {}
this.log = require('./logger')('rcs-lib', {debug: opts.verbose || false})
var config
// If feeding in a direct config object
if (opts.config !== null && typeof opts.config === 'object') {
config = opts.config
} else {
config = this.readConfig(opts.config)
}
opts = assign(config, opts)
opts.output = path.resolve(process.cwd(), (opts.output || 'styleguide').replace(/\/+$/, ''))
opts.title = opts.title || 'Style Guide'
opts.root = opts.root ? path.normalize('/' + opts.root.replace(/\/+$/, '')) : null
opts.pushstate = opts.pushstate || false
opts.files = opts.files || []
opts.babelConfig = opts.babelConfig || null
opts.webpackConfig = opts.webpackConfig || {}
// Run on port 3000 if mode enabled but port not specified
if (opts.dev && opts.dev === true) {
opts.dev = 3000
} else if (!opts.dev) {
opts.dev = false
}
var globOptions = opts.ignore ? {realpath: true, ignore: opts.ignore } : {realpath: true};
opts.styleComponents = opts.styleComponents ? glob.sync(opts.styleComponents, globOptions) : false;
this.input = glob
.sync(input, {realpath: true})
.filter(function (file) {
var readFile = fs.readFileSync(file);
try {
if (reactDocGenModule.parse(readFile)) {
return true
}
} catch (e) {
return false
}
});
opts['reactDocgen'] = opts['reactDocgen'] || {}
if (!opts['reactDocgen'].files) {
opts['reactDocgen'].files = [input]
}
this.opts = opts
// files to parse for react-docgen
this.reactDocGenFiles = this.getReactPropDocFiles()
// Cached files to include into the styleguide app
this.cssFiles = this.extractFiles('.css')
this.jsFiles = this.extractFiles('.js')
this.appTemplate = fs.readFileSync(path.resolve(__dirname, './fixtures/index.html.mustache'), 'utf-8')
this.stageDir = path.resolve(__dirname, '../rcs-tmp')
}
|
javascript
|
{
"resource": ""
}
|
q11845
|
train
|
function (obj, eventType, eventHandler) {
if (!obj.eventHandlers) { obj.eventHandlers = {}; }
if (!obj.eventHandlers[eventType]) {
obj.eventHandlers[eventType] = [];
}
if (eventHandler) {
obj.eventHandlers[eventType].push(eventHandler);
}
return obj.eventHandlers[eventType];
}
|
javascript
|
{
"resource": ""
}
|
|
q11846
|
train
|
function(parentClass, isWhat, tag, features) { // v0 spec implementation using https://github.com/WebReflection/document-register-element
var elementClass = Object.create(parentClass.prototype);
// Clone event handlers
if (elementClass.eventHandlers) {
var clonedHandlers = {};
for (var i in elementClass.eventHandlers) {
var handlers = elementClass.eventHandlers[i];
clonedHandlers[i] = handlers.slice(0); // Clone array of listeners;
}
elementClass.eventHandlers = clonedHandlers;
}
// Lifecycle
elementClass.createdCallback = function () {
// Add event listeners
for (var i in this.eventHandlers) {
var event = new CustomEvent(i);
for (var j in this.eventHandlers[i]) {
this.addEventListener(event.type, this.eventHandlers[i][j]);
}
}
// Trigger create
var event = new CustomEvent('create');
this.dispatchEvent(event);
};
elementClass.attachedCallback = function () {
var event = new CustomEvent('attach');
this.dispatchEvent(event);
};
elementClass.detachedCallback = function () {
var event = new CustomEvent('detach');
this.dispatchEvent(event);
};
elementClass.attributeChangedCallback = function (attributeName) {
var event = new CustomEvent('attributeChange', { detail: { attributeName: attributeName } });
this.dispatchEvent(event);
};
// Attach features
if (features) {
if (!features.length) { // Can't use Array.isArray
features = [features];
}
for (var i=0;i<features.length;i++) {
utils.addFeature(elementClass, features[i]);
}
}
var params = {
prototype: elementClass
};
if (tag) {
params.extends = tag;
}
var elementConstructor = document.registerElement(isWhat, params); // v0 syntax
return elementConstructor;
}
|
javascript
|
{
"resource": ""
}
|
|
q11847
|
train
|
function (obj, properties) {
var events, propertyDescriptors, i;
if (!properties) { return; }
// Clone events
if (properties.on) {
events = Object.assign({}, properties.on);
}
Object.assign(obj, properties); // IE11 need a polyfill
// Handle events
if (events) {
for (i in events) {
this.addCustomEvent(obj, i, events[i]);
}
delete obj.on;
}
// Handle observed attributes
if (properties.observedAttributes) {
if (!obj.observedAttributesList) {
obj.observedAttributesList = [];
}
Array.prototype.push.apply(obj.observedAttributesList,properties.observedAttributes);
}
// Handle properties getters and setters
if (properties.define) {
propertyDescriptors = Object.assign({}, properties.define);
Object.defineProperties(obj, propertyDescriptors);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q11848
|
train
|
function() {
'use strict';
var features = arguments;
if (!features.length) {
return;
}
// Detect isWhat, tag and parent class
var props = feature.apply(null, arguments);
var isWhat = props.is;
var tag = props.tag;
var parentClass = props.extends;
if (!parentClass) {parentClass = HTMLElement;}
if (tag && !isWhat) {isWhat = tag; tag = null;};
if (!tag && !isWhat) {utils.warn('Name not specified'); return;}
if (props.polyfill == 'v0') {
return utils.registerElement(parentClass, isWhat, tag, arguments);
} else {
return utils.defineElement(parentClass, isWhat, tag, arguments);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q11849
|
train
|
function() {
'use strict';
var self = this || {};
if (arguments.length) {
for (var i = 0; i<arguments.length; i++) {
if (typeof arguments[i] != 'object') {utils.warn('Expected object in argument #' + i); continue;}
Object.assign(self, arguments[i]);
}
}
return self;
}
|
javascript
|
{
"resource": ""
}
|
|
q11850
|
Property
|
train
|
function Property(node, print) {
print.list(node.decorators, { separator: "" });
if (node.method || node.kind === "get" || node.kind === "set") {
this._method(node, print);
} else {
if (node.computed) {
this.push("[");
print.plain(node.key);
this.push("]");
} else {
// print `({ foo: foo = 5 } = {})` as `({ foo = 5 } = {});`
if (t.isAssignmentPattern(node.value) && t.isIdentifier(node.key) && node.key.name === node.value.left.name) {
print.plain(node.value);
return;
}
print.plain(node.key);
// shorthand!
if (node.shorthand && t.isIdentifier(node.key) && t.isIdentifier(node.value) && node.key.name === node.value.name) {
return;
}
}
this.push(":");
this.space();
print.plain(node.value);
}
}
|
javascript
|
{
"resource": ""
}
|
q11851
|
ArrayExpression
|
train
|
function ArrayExpression(node, print) {
var elems = node.elements;
var len = elems.length;
this.push("[");
print.printInnerComments();
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
if (elem) {
if (i > 0) this.space();
print.plain(elem);
if (i < len - 1) this.push(",");
} else {
// If the array expression ends with a hole, that hole
// will be ignored by the interpreter, but if it ends with
// two (or more) holes, we need to write out two (or more)
// commas so that the resulting code is interpreted with
// both (all) of the holes.
this.push(",");
}
}
this.push("]");
}
|
javascript
|
{
"resource": ""
}
|
q11852
|
getSourceTrees
|
train
|
function getSourceTrees(pathsToSearch) {
return {
read: function(readTree) {
var promises = _.map(pathsToSearch, function(path) {
return new Promise(function(resolve) {
fs.exists(path, function(exists) {
resolve((exists) ? path : null);
});
});
});
return Promise.all(promises)
.then(function(paths) {
paths = _.filter(paths);
if (paths.length === 0) throw new Error('No source paths found');
return paths;
})
.then(function(paths) {
console.log('Found source paths: ' + paths.join(', '));
var pathTrees = _.map(paths, function(path) {
return new Funnel(path, { srcDir: '.', destDir: path });
});
return readTree(mergeTrees(pathTrees));
});
},
cleanup: function() {}
};
}
|
javascript
|
{
"resource": ""
}
|
q11853
|
checkTorrentIntegrity
|
train
|
async function checkTorrentIntegrity(torrentFile, dataFile) {
const _ntRead = promisify(nt.read);
return _ntRead(torrentFile)
.then((torrent) => {
return new Promise((resolve, reject) => {
torrent.metadata.info.name = path.basename(dataFile);
const hasher = torrent.hashCheck(path.dirname(dataFile));
let percentMatch = 0;
const errors = [];
hasher.on('match', (i, hash, percent) => {
percentMatch = percent;
});
hasher.on('error', (err) => {
errors.push(err.message);
});
hasher.on('end', () => {
if(errors.length > 0) {
reject(errors);
} else {
resolve({
'success': percentMatch === 100,
'hash': torrent.infoHash()
});
}
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q11854
|
canCompile
|
train
|
function canCompile(filename, altExts) {
var exts = altExts || canCompile.EXTENSIONS;
var ext = _path2["default"].extname(filename);
return _lodashCollectionContains2["default"](exts, ext);
}
|
javascript
|
{
"resource": ""
}
|
q11855
|
list
|
train
|
function list(val) {
if (!val) {
return [];
} else if (Array.isArray(val)) {
return val;
} else if (typeof val === "string") {
return val.split(",");
} else {
return [val];
}
}
|
javascript
|
{
"resource": ""
}
|
q11856
|
regexify
|
train
|
function regexify(val) {
if (!val) return new RegExp(/.^/);
if (Array.isArray(val)) val = new RegExp(val.map(_lodashStringEscapeRegExp2["default"]).join("|"), "i");
if (_lodashLangIsString2["default"](val)) {
// normalise path separators
val = _slash2["default"](val);
// remove starting wildcards or relative separator if present
if (_lodashStringStartsWith2["default"](val, "./") || _lodashStringStartsWith2["default"](val, "*/")) val = val.slice(2);
if (_lodashStringStartsWith2["default"](val, "**/")) val = val.slice(3);
var regex = _minimatch2["default"].makeRe(val, { nocase: true });
return new RegExp(regex.source.slice(1, -1), "i");
}
if (_lodashLangIsRegExp2["default"](val)) return val;
throw new TypeError("illegal type for regexify");
}
|
javascript
|
{
"resource": ""
}
|
q11857
|
shouldIgnore
|
train
|
function shouldIgnore(filename, ignore, only) {
filename = _slash2["default"](filename);
if (only) {
var _arr = only;
for (var _i = 0; _i < _arr.length; _i++) {
var pattern = _arr[_i];
if (_shouldIgnore(pattern, filename)) return false;
}
return true;
} else if (ignore.length) {
var _arr2 = ignore;
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var pattern = _arr2[_i2];
if (_shouldIgnore(pattern, filename)) return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q11858
|
parseTemplate
|
train
|
function parseTemplate(loc, code) {
var ast = _helpersParse2["default"](code, { filename: loc, looseModules: true }).program;
ast = _traversal2["default"].removeProperties(ast);
return ast;
}
|
javascript
|
{
"resource": ""
}
|
q11859
|
activatePostCSSPlugins
|
train
|
function activatePostCSSPlugins(config) {
const plugins = [];
if (config.lintRules || config.lintRules !== "") {
// TODO: Throw easy-to-understand error message
// incorrect path? (ex. "lintRules": "aaa")
// typo? (ex. "lintRules": "stylelint-config-suitcs")
const lintRules = require(config.lintRules);
if (lintRules.rules) {
plugins.push(stylelint(lintRules));
} else {
throw new Error("Illegal lint rule: \"rules\" property is not found.");
}
}
if (config.browsers && config.browsers !== "") {
plugins.push(autoprefixer(config.browsers));
}
plugins.push(cssfmt);
plugins.push(reporter);
return plugins;
}
|
javascript
|
{
"resource": ""
}
|
q11860
|
ImportSpecifier
|
train
|
function ImportSpecifier(node, print) {
print.plain(node.imported);
if (node.local && node.local.name !== node.imported.name) {
this.push(" as ");
print.plain(node.local);
}
}
|
javascript
|
{
"resource": ""
}
|
q11861
|
es5Plugins
|
train
|
function es5Plugins(){
return [
require('babel-plugin-check-es2015-constants'),
require('babel-plugin-transform-es2015-arrow-functions'),
require('babel-plugin-transform-es2015-block-scoped-functions'),
require('babel-plugin-transform-es2015-block-scoping'),
require('babel-plugin-transform-es2015-classes'),
require('babel-plugin-transform-es2015-computed-properties'),
require('babel-plugin-transform-es2015-destructuring'),
require('babel-plugin-transform-es2015-duplicate-keys'),
require('babel-plugin-transform-es2015-for-of'),
require('babel-plugin-transform-es2015-function-name'),
require('babel-plugin-transform-es2015-literals'),
require('babel-plugin-transform-es2015-object-super'),
require('babel-plugin-transform-es2015-parameters'),
require('babel-plugin-transform-es2015-shorthand-properties'),
require('babel-plugin-transform-es2015-spread'),
require('babel-plugin-transform-es2015-sticky-regex'),
require('babel-plugin-transform-es2015-template-literals'),
require('babel-plugin-transform-es2015-typeof-symbol'),
require('babel-plugin-transform-es2015-unicode-regex'),
require('babel-plugin-transform-async-to-generator'),
require('babel-plugin-transform-exponentiation-operator'),
require('babel-plugin-transform-regenerator')
];
}
|
javascript
|
{
"resource": ""
}
|
q11862
|
train
|
function(obj, key, value) {
if(typeof obj[key] === "undefined") {
obj[key] = value;
}
else {
//Check if the current option is not an array
if(Array.isArray(obj[key]) === false) {
obj[key] = [obj[key]];
}
obj[key].push(value);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q11863
|
PriorityQueue
|
train
|
function PriorityQueue(initialItems) {
var self = this;
MinHeap.call(this, function (a, b) {
return self.priority(a) < self.priority(b) ? -1 : 1;
});
this._priority = {};
initialItems = initialItems || {};
Object.keys(initialItems).forEach(function (item) {
self.insert(item, initialItems[item]);
});
}
|
javascript
|
{
"resource": ""
}
|
q11864
|
clean
|
train
|
function clean(type, options) {
options = assign({}, defaults, options);
if (type === 'dblclick') {
options.detail = 2;
}
if (isString(options.key)) {
options.key = keycode(options.key);
}
return options;
}
|
javascript
|
{
"resource": ""
}
|
q11865
|
createMouseEvent
|
train
|
function createMouseEvent(type, options) {
options = clean(type, options);
var e = document.createEvent('MouseEvent');
e.initMouseEvent(
type,
options.bubbles,
options.cancelable,
options.view,
options.detail,
options.screenX,
options.screenY,
options.clientX,
options.clientY,
options.ctrl,
options.alt,
options.shift,
options.meta,
options.button,
options.relatedTarget
);
return e;
}
|
javascript
|
{
"resource": ""
}
|
q11866
|
createKeyboardEvent
|
train
|
function createKeyboardEvent(type, options) {
options = clean(type, options);
var e = document.createEvent('KeyboardEvent');
(e.initKeyEvent || e.initKeyboardEvent).call(
e,
type,
options.bubbles,
options.cancelable,
options.view,
options.ctrl,
options.alt,
options.shift,
options.meta,
options.key,
options.key
);
// http://stackoverflow.com/a/10520017
if (e.keyCode !== options.key) {
Object.defineProperty(e, 'keyCode', {
get: function() { return options.key; }
});
Object.defineProperty(e, 'charCode', {
get: function() { return options.key; }
});
Object.defineProperty(e, 'which', {
get: function() { return options.key; }
});
Object.defineProperty(e, 'shiftKey', {
get: function() { return options.shift; }
});
}
return e;
}
|
javascript
|
{
"resource": ""
}
|
q11867
|
createEvent
|
train
|
function createEvent(type, options) {
switch (type) {
case 'dblclick':
case 'click':
return createMouseEvent(type, options);
case 'keydown':
case 'keyup':
return createKeyboardEvent(type, options);
}
}
|
javascript
|
{
"resource": ""
}
|
q11868
|
createIeEvent
|
train
|
function createIeEvent(type, options) {
options = clean(type, options);
var e = document.createEventObject();
e.altKey = options.alt;
e.bubbles = options.bubbles;
e.button = options.button;
e.cancelable = options.cancelable;
e.clientX = options.clientX;
e.clientY = options.clientY;
e.ctrlKey = options.ctrl;
e.detail = options.detail;
e.metaKey = options.meta;
e.screenX = options.screenX;
e.screenY = options.screenY;
e.shiftKey = options.shift;
e.keyCode = options.key;
e.charCode = options.key;
e.view = options.view;
return e;
}
|
javascript
|
{
"resource": ""
}
|
q11869
|
_check_and_save
|
train
|
function _check_and_save(path){
//console.log('l@: ' + path);
if( afs.exists_p(path) ){
if( afs.file_p(path) ){
//console.log('found file: ' + path);
// Break into parts for saving if it is a full file.
var filename = path;
var slash_loc = path.lastIndexOf('/') + 1;
if( slash_loc != 0 ){
filename = path.substr(slash_loc, path.length);
}
// Capture full path.
path_cache[path] = path;
zcache[path] = afs.read_file(path);
// Capture flattened name.
path_cache[filename] = path;
zcache[filename] = afs.read_file(path);
// Capture which is which.
ns_cache_flat[filename] = true;
ns_cache_full[path] = true;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q11870
|
_add_permanently_to
|
train
|
function _add_permanently_to(stack, item_or_list){
if( item_or_list && tcache[stack] ){
if( ! us.isArray(item_or_list) ){ // atom
tcache[stack].push(item_or_list);
}else{ // list
tcache[stack] = tcache[stack].concat(item_or_list);
}
}
return tcache[stack];
}
|
javascript
|
{
"resource": ""
}
|
q11871
|
_set_common
|
train
|
function _set_common(stack_name, thing){
var ret = null;
if( stack_name == 'css_libs' ||
stack_name == 'js_libs' ||
stack_name == 'js_vars' ){
_add_permanently_to(stack_name, thing);
ret = thing;
}
//console.log('added ' + thing.length + ' to ' + stack_name);
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q11872
|
_use_zcache_p
|
train
|
function _use_zcache_p(yes_no){
if( yes_no == true ){
use_zcache_p = true;
}else if( yes_no == false ){
use_zcache_p = false;
}
return use_zcache_p;
}
|
javascript
|
{
"resource": ""
}
|
q11873
|
_get
|
train
|
function _get(key){
var ret = null;
// Pull from cache or re-read from fs.
//console.log('key: ' + key)
//console.log('use_zcache_p: ' + use_zcache_p)
if( use_zcache_p ){
ret = zcache[key];
}else{
ret = afs.read_file(path_cache[key]);
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q11874
|
_apply
|
train
|
function _apply (tmpl_name, tmpl_args){
var ret = null;
var tmpl = _get(tmpl_name);
if( tmpl ){
ret = mustache.render(tmpl, tmpl_args);
}
// if( tmpl ){ console.log('rendered string length: ' + ret.length); }
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q11875
|
replaceSensitive
|
train
|
function replaceSensitive(chr, dbl) {
var result,
dbl_result;
if (typeof baseDiacriticsMap[chr] === 'undefined') {
return chr;
}
result = '[' + chr
result += baseDiacriticsMap[chr];
result += ']';
if (dbl && baseDiacriticsMap[dbl]) {
dbl_result = baseDiacriticsMap[dbl];
// Make the previous group optional,
// but do require one of these groups then
result = '?(?:' + result + '|[' + dbl_result + '])';
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q11876
|
replaceInsensitive
|
train
|
function replaceInsensitive(chr, dbl) {
var lower = chr.toLowerCase(),
upper = chr.toUpperCase(),
result,
dbl_result;
if (lower == upper) {
return chr;
}
result = '[' + lower + upper;
result += (baseDiacriticsMap[lower]||'');
result += (baseDiacriticsMap[upper]||'');
result += ']';
if (dbl) {
lower = dbl.toLowerCase();
upper = dbl.toUpperCase();
dbl_result = baseDiacriticsMap[lower] || '';
dbl_result += baseDiacriticsMap[upper] || '';
if (dbl_result) {
// Make the previous group optional,
// but do require one of these groups then
result = '?(?:' + result + '|[' + dbl_result + '])';
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q11877
|
resolveConfig
|
train
|
function resolveConfig (fileName, options) {
options = options || {}
var schema = options.schema
var resolvePackageJson = options.resolvePackageJson || false
var fileNames = [fileName, resolvePackageJson ? 'package.json' : null].filter(
item => !!item
)
const results = upResolve(fileNames)
return Promise.all(results.map(readFileAsync))
.then(parseFiles(options))
.then(validateSchema(schema))
.then(reduceConfigs)
}
|
javascript
|
{
"resource": ""
}
|
q11878
|
list
|
train
|
async function list(torrentHandler, config) {
try {
const list = await clientTorrent.list(config.pid);
for(const i in list) {
torrentHandler.handle(list[i], config.pid);
}
torrentHandler.checkState(list, config.pid);
} catch (error) {
lError(`Exception ${error}`);
}
}
|
javascript
|
{
"resource": ""
}
|
q11879
|
load
|
train
|
function load() {
if (process.env.BABEL_DISABLE_CACHE) return;
process.on("exit", save);
process.nextTick(save);
if (!_pathExists2["default"].sync(FILENAME)) return;
try {
data = JSON.parse(_fs2["default"].readFileSync(FILENAME));
} catch (err) {
return;
}
}
|
javascript
|
{
"resource": ""
}
|
q11880
|
makeReactive
|
train
|
function makeReactive(componentDefinition, renderFn, ...stateStreamNames) {
class ReactiveComponent extends PureComponent {
constructor(props, context) {
super(props, context);
this.state = { childProps: {} }
this.omnistream = this.context.omnistream;
// Make the dispatch function accessible to be passed as a prop to child components.
this.dispatch = this.omnistream.dispatch.bind(context.omnistream);
this.dispatchObservableFn = this.omnistream.dispatchObservableFn.bind(context.omnistream);
}
componentDidMount() {
// Creates a new substream for each action type based on the provided "streamNames"
const stateStreams = stateStreamNames.map(name => this.omnistream.store[name]);
const state$ = combineStreamsToState(stateStreams);
// Subscribes to the props stream. This will trigger a re-render whenever a new action has been dispatched to
// any filtered stream passed down as props to a component.
this.subscription = state$.subscribe((props) => {
this.setState({ childProps: Object.assign({}, this.props, props) });
});
}
componentWillUnmount() {
this.subscription.unsubscribe();
}
render() {
return renderFn.call(this, componentDefinition);
}
}
ReactiveComponent.contextTypes = { omnistream: React.PropTypes.object.isRequired }
return ReactiveComponent;
}
|
javascript
|
{
"resource": ""
}
|
q11881
|
getStatementParent
|
train
|
function getStatementParent() {
var path = this;
do {
if (Array.isArray(path.container)) {
return path;
}
} while (path = path.parentPath);
}
|
javascript
|
{
"resource": ""
}
|
q11882
|
getDeepestCommonAncestorFrom
|
train
|
function getDeepestCommonAncestorFrom(paths, filter) {
// istanbul ignore next
var _this = this;
if (!paths.length) {
return this;
}
if (paths.length === 1) {
return paths[0];
}
// minimum depth of the tree so we know the highest node
var minDepth = Infinity;
// last common ancestor
var lastCommonIndex, lastCommon;
// get the ancestors of the path, breaking when the parent exceeds ourselves
var ancestries = paths.map(function (path) {
var ancestry = [];
do {
ancestry.unshift(path);
} while ((path = path.parentPath) && path !== _this);
// save min depth to avoid going too far in
if (ancestry.length < minDepth) {
minDepth = ancestry.length;
}
return ancestry;
});
// get the first ancestry so we have a seed to assess all other ancestries with
var first = ancestries[0];
// check ancestor equality
depthLoop: for (var i = 0; i < minDepth; i++) {
var shouldMatch = first[i];
var _arr2 = ancestries;
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var ancestry = _arr2[_i2];
if (ancestry[i] !== shouldMatch) {
// we've hit a snag
break depthLoop;
}
}
// next iteration may break so store these so they can be returned
lastCommonIndex = i;
lastCommon = shouldMatch;
}
if (lastCommon) {
if (filter) {
return filter(lastCommon, lastCommonIndex, ancestries);
} else {
return lastCommon;
}
} else {
throw new Error("Couldn't find intersection");
}
}
|
javascript
|
{
"resource": ""
}
|
q11883
|
getAncestry
|
train
|
function getAncestry() {
var path = this;
var paths = [];
do {
paths.push(path);
} while (path = path.parentPath);
return paths;
}
|
javascript
|
{
"resource": ""
}
|
q11884
|
inShadow
|
train
|
function inShadow(key) {
var path = this;
do {
if (path.isFunction()) {
var shadow = path.node.shadow;
if (shadow) {
// this is because sometimes we may have a `shadow` value of:
//
// { this: false }
//
// we need to catch this case if `inShadow` has been passed a `key`
if (!key || shadow[key] !== false) {
return path;
}
} else if (path.isArrowFunctionExpression()) {
return path;
}
// normal function, we've found our function context
return null;
}
} while (path = path.parentPath);
return null;
}
|
javascript
|
{
"resource": ""
}
|
q11885
|
getRealHeaderCheck
|
train
|
function getRealHeaderCheck(expectedHeader, caseSensitive, fieldNames) {
return function (content) {
let actualHeader;
if (caseSensitive) {
actualHeader = content;
} else {
actualHeader = arrayToUpperCase(content);
expectedHeader = arrayToUpperCase(expectedHeader);
}
// the header must have all the expected columns but may have more
return _getRealHeader(expectedHeader, actualHeader, fieldNames);
};
}
|
javascript
|
{
"resource": ""
}
|
q11886
|
getStrictCheck
|
train
|
function getStrictCheck(expectedHeader, caseSensitive, severity) {
return function (content) {
let actualHeader;
if (caseSensitive) {
actualHeader = content;
} else {
actualHeader = arrayToUpperCase(content);
expectedHeader = arrayToUpperCase(expectedHeader);
}
if (expectedHeader.length !== actualHeader.length) {
// If the length is different, it could not be the same
return {
errorCode: 'CHECK_HEADER_NO_STRICT_MATCH',
severity: severity,
message: 'The expected header [' + expectedHeader +
'] has a different column count to the actual header [' + actualHeader +
']'
};
} else {
// no we need to compare field by field because the expected array could be an array of arrays
// The expected header may contain alternative names for one column.
for (let i = 0; i < expectedHeader.length; i++) {
let match = false;
const actualVal = actualHeader[i];
let expectedVal = expectedHeader[i];
if (Array.isArray(expectedVal)) {
for (let j = 0; j < expectedVal.length; j++) {
if (actualVal === expectedVal[j]) {
match = true;
}
}
} else {
if (actualVal === expectedVal) {
match = true;
}
}
if (!match) {
return {
errorCode: 'CHECK_HEADER_NO_STRICT_MATCH',
severity: severity,
message: 'The expected header [' + expectedHeader +
'] does not match the actual header [' +
actualHeader +
']'
};
}
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
q11887
|
getMissingColumnCheck
|
train
|
function getMissingColumnCheck(expectedHeader, caseSensitive, severity) {
return function (content) {
let actualHeader;
if (caseSensitive) {
actualHeader = content;
} else {
actualHeader = arrayToUpperCase(content);
expectedHeader = arrayToUpperCase(expectedHeader);
}
// the header must have all the expected columns but may have more
let err = _missingColumns(expectedHeader, actualHeader);
if (err) {
return {
errorCode: 'CHECK_HEADER_MISSING_COLUMNS',
severity: severity,
message: 'The following columns are missing in the header: [' + err.join() + ']'
};
}
};
}
|
javascript
|
{
"resource": ""
}
|
q11888
|
getMandatoryColumnCheck
|
train
|
function getMandatoryColumnCheck(mandatoryColumns, severity) {
/**
* @param the coluns found and matched.
*/
return function (foundColumns) {
// the header must have all the expected columns but may have more
let err = _missingColumns(mandatoryColumns, foundColumns);
if (err) {
return {
errorCode: 'CHECK_HEADER_MANDATORY_COLUMNS',
severity: severity,
message: 'The following columns are missing in the header and are mandatory: [' + err.join() + ']'
};
}
};
}
|
javascript
|
{
"resource": ""
}
|
q11889
|
ReaddirPlusFile
|
train
|
function ReaddirPlusFile(source) {
/**
* File name. Eg. "file.txt"
* @type {string}
*/
this.name = null;
/**
* Full path. Eg. "/home/myname/path/to/directory/subdir/file.txt"
* @type {string}
*/
this.path = null;
/**
* Relative path, based on the directory you submitted to readdir. Eg. "subdir/file.txt"
* @type {string}
*/
this.relativePath = null;
/**
* File name without extension. Eg. "file"
* @type {string}
*/
this.basename = null;
/**
* Extension with leading dot. Eg. ".txt"
* @type {string}
*/
this.extension = null;
/**
* One of vars.FILE_TYPES
* @type {FILE_TYPES}
*/
this.type = null;
/**
* File or directory stats
* @type {fs.Stats}
*/
this.stat = null;
Object.assign(this, source);
}
|
javascript
|
{
"resource": ""
}
|
q11890
|
toExports
|
train
|
function toExports(dir, patterns, recurse, options, fn) {
if (arguments.length === 1 && !isGlob(dir)) {
var key = 'toExports:' + dir;
if (cache.hasOwnProperty(key)) {
return cache[key];
}
var result = lookup(dir, false, {}).reduce(function (res, fp) {
if (filter(fp, fn)) {
res[basename(fp)] = read(fp, fn);
}
return res;
}, {});
return (cache[key] = result);
}
return explode.apply(explode, arguments);
}
|
javascript
|
{
"resource": ""
}
|
q11891
|
lookup
|
train
|
function lookup(dir, recurse) {
if (typeof dir !== 'string') {
throw new Error('export-files expects a string as the first argument.');
}
var key = 'lookup:' + dir + ('' + recurse);
if (cache.hasOwnProperty(key)) {
return cache[key];
}
var files = fs.readdirSync(dir);
var len = files.length;
var res = [];
if (recurse === false) return map(files, resolve(dir));
while (len--) {
var fp = path.resolve(dir, files[len]);
if (isDir(fp)) {
res.push.apply(res, lookup(fp, recurse));
} else {
res.push(fp);
}
}
return (cache[key] = res);
}
|
javascript
|
{
"resource": ""
}
|
q11892
|
renameKey
|
train
|
function renameKey(fp, opts) {
if (opts && opts.renameKey) {
return opts.renameKey(fp, opts);
}
return basename(fp);
}
|
javascript
|
{
"resource": ""
}
|
q11893
|
read
|
train
|
function read(fp, opts, fn) {
opts = opts || {};
opts.encoding = opts.encoding || 'utf8';
if (opts.read) {
return opts.read(fp, opts);
} else if (fn) {
return fn(fp, opts);
}
if (endsWith(fp, '.js')) {
return tryRequire(fp);
} else {
var str = tryCatch(fs.readFileSync, fp, opts);
if (endsWith(fp, '.json')) {
return tryCatch(JSON.parse, str);
}
return str;
}
}
|
javascript
|
{
"resource": ""
}
|
q11894
|
isBinding
|
train
|
function isBinding(node, parent) {
var keys = _retrievers.getBindingIdentifiers.keys[parent.type];
if (keys) {
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var val = parent[key];
if (Array.isArray(val)) {
if (val.indexOf(node) >= 0) return true;
} else {
if (val === node) return true;
}
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q11895
|
isSpecifierDefault
|
train
|
function isSpecifierDefault(specifier) {
return t.isImportDefaultSpecifier(specifier) || t.isIdentifier(specifier.imported || specifier.exported, { name: "default" });
}
|
javascript
|
{
"resource": ""
}
|
q11896
|
isScope
|
train
|
function isScope(node, parent) {
if (t.isBlockStatement(node) && t.isFunction(parent, { body: node })) {
return false;
}
return t.isScopable(node);
}
|
javascript
|
{
"resource": ""
}
|
q11897
|
isImmutable
|
train
|
function isImmutable(node) {
if (t.isType(node.type, "Immutable")) return true;
if (t.isLiteral(node)) {
if (node.regex) {
// regexs are mutable
return false;
} else {
// immutable!
return true;
}
} else if (t.isIdentifier(node)) {
if (node.name === "undefined") {
// immutable!
return true;
} else {
// no idea...
return false;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q11898
|
train
|
function (data, ctxModel, ctxVars) {
const options = xtend(this.options, { ctxVars, logger: this.logger });
const parser = new kevs.Parser();
const ast = parser.parse(data);
if (ast.type !== 'kevScript') {
const err = new Error('Unable to parse script');
err.parser = ast;
err.warnings = options.warnings || [];
return Promise.reject(err);
} else {
return interpreter(ast, ctxModel, options)
.then(({ error, warnings, model }) => {
if (error) {
error.warnings = warnings;
throw error;
} else {
return { model, warnings };
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q11899
|
setPropertyVal
|
train
|
function setPropertyVal (pObj, pProp, pNewVal) {
if (typeof pProp === 'string') {
pProp = pProp || '';
pProp = pProp.split('.');
}
if (pProp.length > 1) {
var prop = pProp.shift();
pObj[prop] = (typeof pObj[prop] !== 'undefined'
|| typeof pObj[prop] !== 'null') ? pObj[prop] : {};
setPropertyVal(pObj[prop], pProp, pNewVal);
} else {
pObj[ pProp[0] ] = pNewVal;
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.