_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q55700
|
fetchFunction
|
train
|
function fetchFunction(url, key, data, fetchLinkNames, recursive, fetchMultiple) {
if (config.fetchFunction == undefined) {
var promisesArray = [];
promisesArray.push($injector.get("$http").get(url)
.then(function (responseData) {
// wrap the response again with the adapter and return the promise
if (recursive) {
return processData(responseData.data, fetchLinkNames, true, fetchMultiple).then(function (processedData) {
data[key] = processedData;
});
} else {
return processData(responseData.data).then(function (processedData) {
data[key] = processedData;
});
}
}, function (error) {
if (error.status != 404) {
// just reject the error if its not a 404 as there are links which return a 404 which are not set
return $injector.get("$q").reject(error);
}
}));
// wait for all promises to be resolved and return a new promise
return $injector.get("$q").all(promisesArray);
} else {
return config.fetchFunction(url, key, data, fetchLinkNames, recursive, fetchMultiple);
}
}
|
javascript
|
{
"resource": ""
}
|
q55701
|
getProcessedUrl
|
train
|
function getProcessedUrl(data, resourceName) {
// get the raw URL out of the resource name and check if it is valid
var rawUrl = checkUrl(data[config.linksKey][resourceName][config.linksHrefKey], resourceName,
config.linksHrefKey);
// extract the template parameters of the raw URL
return extractUrl(rawUrl, data[config.linksKey][resourceName].templated);
}
|
javascript
|
{
"resource": ""
}
|
q55702
|
extractUrlTemplates
|
train
|
function extractUrlTemplates(resourceName) {
if (hasUrlTemplate(resourceName)) {
var indexOfSlash = resourceName.indexOf("/");
return [resourceName.substr(0, indexOfSlash), resourceName.substr(indexOfSlash, resourceName.length)];
}
}
|
javascript
|
{
"resource": ""
}
|
q55703
|
train
|
function(e) {
this.hasFocus = true;
this.setSelectionIfNeeded(e.target);
if (this.props.onFocus) {
return this.props.onFocus(e);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55704
|
train
|
function(tagName) {
return function() {
return laconic.apply(this,
[tagName].concat(Array.prototype.slice.call(arguments)));
};
}
|
javascript
|
{
"resource": ""
}
|
|
q55705
|
extractJsdoc
|
train
|
function extractJsdoc(comment) {
var docAst = doctrine.parse(comment, { unwrap: true, sloppy: true });
if (!docAst.tags || docAst.tags.length === 0) {
return null;
}
// only interested in @param @property, and @return
var paramTags = docAst.tags.filter(function(tag) {
return tag.title === "param";
}).map(jsdocTagToFlowTag);
var returnTags = docAst.tags.filter(function(tag) {
return tag.title === "return" || tag.title === "returns";
}).map(jsdocTagToFlowTag);
var propTags = docAst.tags.filter(function(tag) {
return tag.title === "property" || tag.title === "prop";
}).map(jsdocTagToFlowTag);
return {
params: paramTags,
returns: returnTags,
props: propTags
};
}
|
javascript
|
{
"resource": ""
}
|
q55706
|
getCommentedFunctionNode
|
train
|
function getCommentedFunctionNode(node) {
if (!node.leadingComments) {
// JSDoc comments are always before the function, so if there is
// nothing here, we ain't interested.
return null;
}
// console.log("=================");
// console.log("type: " + node.type);
// console.log(util.inspect(node));
/*
* We handle the following function representations:
*
* Type Path to Function Example
* ==========================================================================================
* FunctionDeclaration - function foo(bar) {}
* VariableDeclaration .declarations[0].init var foo = function(bar) {}
* ExpressionStatement .expression.right ObjClass.prototype.foo = function(bar) {}
* MethodDefinition .value class ObjClass { foo(bar) {} }
* Property .value var obj = { key: function(bar) {} }
* ReturnStatement .argument return function(foo, bar) {}
* ArrowFunctionExpression - (foo, bar) => {}
* ExportNamedDeclaration .declaration export function foo(bar) {}
*
*/
var nodeTypes = [
"FunctionDeclaration", "ExpressionStatement", "VariableDeclaration",
"MethodDefinition", "Property", "ReturnStatement", "ArrowFunctionExpression",
"ExportNamedDeclaration"
];
if (nodeTypes.indexOf(node.type) === -1) {
return null;
}
var funcNode = null;
switch (node.type) {
case "FunctionDeclaration":
case "ArrowFunctionExpression":
funcNode = node;
break;
case "VariableDeclaration":
funcNode = node.declarations[0].init;
break;
case "ExpressionStatement":
funcNode = node.expression.right;
break;
case "MethodDefinition":
funcNode = node.value;
break;
case "Property":
funcNode = node.value;
break;
case "ReturnStatement":
funcNode = node.argument;
break;
case "ExportNamedDeclaration":
var declaration = node.declaration;
if (declaration.type === 'VariableDeclaration') {
funcNode = declaration.declarations[0].init;
} else {
funcNode = declaration
}
break;
}
var funcNodeTypes = ["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"];
if (!funcNode || funcNodeTypes.indexOf(funcNode.type) === -1) {
// We can't find a function here which can map to leadingComments.
return null;
}
var funcDocs = null;
for (var i=0; i<node.leadingComments.length; i++) {
// Block comments are either JSDoc or flow-jsdoc specific in-inline syntax
if (node.leadingComments[i].type === "Block") {
funcDocs = extractJsdoc(node.leadingComments[i].value);
if (funcDocs) { break; }
// may be inline form with /* */
funcDocs = extractInlineAnnotations(funcNode, node.leadingComments[i].value);
if (funcDocs) {
node.leadingComments[i].update("");
break;
}
}
else if (node.leadingComments[i].type === "Line") {
// Line comments can only be flow-jsdoc specific in-line syntax.
funcDocs = extractInlineAnnotations(funcNode, node.leadingComments[i].value);
if (funcDocs) {
node.leadingComments[i].update("");
break;
}
}
}
return {
node: funcNode,
jsdoc: funcDocs
};
}
|
javascript
|
{
"resource": ""
}
|
q55707
|
decorateClasses
|
train
|
function decorateClasses(node) {
// check for class nodes
var clsNode = getCommentedClassNode(node);
if (!clsNode || !clsNode.jsdoc || clsNode.jsdoc.props.length === 0) {
return;
}
var clsSrc = clsNode.node.source();
if (clsSrc[0] !== "{") {
// something isn't right, bail.
return;
}
// work out line endings (find first \n and see if it has \r before it)
var nl = "\n";
var newlineIndex = clsSrc.indexOf("\n");
if (clsSrc[newlineIndex-1] === "\r") {
nl = "\r\n";
}
// use the same indent as the next non-blank line
var indent = "";
var lines = clsSrc.split(nl);
for (var i = 1; i < lines.length; i++) { //i=1 to skip the starting {
if (lines[i].length > 0) {
var whitespaceMatch = /^[ \t]+/.exec(lines[i]); // match spaces or tabs
if (whitespaceMatch) {
indent = whitespaceMatch[0];
break;
}
}
}
// work out what to inject into the class definition
var fieldTypeDecls = clsNode.jsdoc.props.map(function(p) {
return indent + p.name + ": " + p.type + ";";
}).join(nl);
clsNode.node.update("{" + nl + fieldTypeDecls + clsSrc.substr(1));
}
|
javascript
|
{
"resource": ""
}
|
q55708
|
validate
|
train
|
function validate(message, type) {
assert(
typeOf(message) === 'object',
'You must pass a message object.',
);
rules.forEach((rule) => {
if (message[rule.name]) {
const types = [].concat(rule.types);
assert(
types.some(t => typeOf(message[rule.name]) === t),
`"${rule.name}" must be ${types.join(' or ')}.`,
);
}
});
if (asserts[type]) {
asserts[type](message);
} else {
throw new TypeError('Invalid event type');
}
}
|
javascript
|
{
"resource": ""
}
|
q55709
|
merge
|
train
|
function merge(src1, src2) {
var merged = {};
extend(merged, src1);
extend(merged, src2);
return merged;
}
|
javascript
|
{
"resource": ""
}
|
q55710
|
getChannelsSchedule
|
train
|
function getChannelsSchedule(channel,date){
var p = '/ibl/v1/channels/{channel}/schedule/{date}';
p = p.replace('{channel}',channel);
p = p.replace('{date}',date);
return p;
}
|
javascript
|
{
"resource": ""
}
|
q55711
|
BehaviorInterfaceError
|
train
|
function BehaviorInterfaceError(baseBehavior, extendingBehavior, missingProps) {
var extendingName = extendingBehavior.behaviorName || 'anonymous behavior',
baseName = baseBehavior.__behaviorName || 'anonymous behavior',
message = 'can-connect: Extending behavior "' + extendingName + '" found base behavior "' + baseName
+ '" was missing required properties: ' + JSON.stringify(missingProps.related),
instance = new Error(message);
if (Object.setPrototypeOf){
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
}
return instance;
}
|
javascript
|
{
"resource": ""
}
|
q55712
|
enableHID
|
train
|
async function enableHID() {
const usbConfig = getstrprop('sys.usb.state');
if (!usbConfig.startsWith('hid,')) {
log.warn('HID function does not seem to be enabled.');
const usbConfigWithHid = `hid,${usbConfig}`;
log.info(`changing USB config to ${usbConfigWithHid}`);
// WARNING! If this device is not Kenzo or this otherwise fails, it's likely
// that adb access will be lost until the next reboot
setprop('sys.usb.config', usbConfigWithHid);
// Wait for USB to be reconfigured.
await sleep(1000);
const newUsbConfig = getstrprop('sys.usb.state');
if (newUsbConfig !== usbConfigWithHid) {
throw new Error(`USB config expected to be ${usbConfigWithHid}, but it was ${newUsbConfig}`);
}
}
// Ensure the two HID devices are present
Promise.all(
['/dev/hidg0', '/dev/hidg1'].map(
file => fs.access(file, fs.constants.R_OK | fs.constants.W_OK)
)
);
}
|
javascript
|
{
"resource": ""
}
|
q55713
|
ensureSetup
|
train
|
function ensureSetup(argv) {
const root = findPackageRoot();
const emulatorBin = path.join(root, 'node_modules/silk-sdk-emulator/vendor/bin');
// Additional paths to search for outside of PATH.
const additionalPaths = [];
if (fs.existsSync(emulatorBin)) {
additionalPaths.push(emulatorBin);
}
argv.arguments = argv.arguments || [];
argv.arguments = [
[['--device', '-d'], {
help: 'Specific device to operate under.',
}],
...argv.arguments,
];
const main = argv.main;
argv.main = function (args) {
const {device} = args;
const api = new SDKApi({
device: device,
additionalPaths: additionalPaths,
});
return main(api, args);
};
return argv;
}
|
javascript
|
{
"resource": ""
}
|
q55714
|
fetchCdnVersion
|
train
|
function fetchCdnVersion(cdnUrl) {
var fullUrl = cdnUrl + path.sep + SONAR_RUNNER_DIST;
console.log('Fetching sonar-runner from CDN url [' + fullUrl + '].');
try {
var response = request('GET', fullUrl);
if(response.statusCode === 200) {
var destination = path.join('.tmp', SONAR_RUNNER_DIST);
fs.mkdirsSync('.tmp', '0775');
fs.writeFileSync(destination, response.getBody(), {replace: true});
return destination;
} else if(response.statusCode === 404) {
console.error('Could not find '+ SONAR_RUNNER_DIST + ' on the specified CDN url[' + fullUrl +'].');
} else {
console.error('Something went wrong while fetching '+ SONAR_RUNNER_DIST + ' on the specified CDN url[' + fullUrl +'], statusCode [' + response.statusCode + '] was received.');
}
} catch (e) {
console.error('Could not connect to CDN url[' + cdnUrl +'], received message [' + e + ']');
}
}
|
javascript
|
{
"resource": ""
}
|
q55715
|
copyFiles
|
train
|
function copyFiles(g, defaultOutputDir, targetDir) {
var files = glob.sync(g.src.toString(), {cwd: g.cwd, root: '/'});
files.forEach(function (file) {
var destinationDirectory = defaultOutputDir + path.sep + targetDir;
var fileDirectory = path.dirname(file);
if (fileDirectory !== '.') {
destinationDirectory = destinationDirectory + path.sep + fileDirectory;
}
fs.mkdirpSync(destinationDirectory);
var source = path.resolve(g.cwd, file);
var extension = path.extname(file);
var destination;
if (targetDir === 'test') {
var base = path.basename(file, extension);
if (extension === '.js') {
destination = destinationDirectory + path.sep + path.basename(base.replace(/\./g, '_') + extension);
} else if (extension === '.feature') {
destination = destinationDirectory + path.sep + path.basename(base.concat(extension).replace(/\./g, '_') + '.js');
}
} else {
destination = destinationDirectory + path.sep + path.basename(file);
}
fs.copySync(source, destination, {replace: true});
});
}
|
javascript
|
{
"resource": ""
}
|
q55716
|
mergeJson
|
train
|
function mergeJson(original, override) {
return _.merge(original, override, function (a, b, key, aParent, bParent) {
if (_.isUndefined(b)) {
aParent[key] = undefined;
return;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q55717
|
buildArgs
|
train
|
function buildArgs(sonarOptions, data) {
// Default arguments
var args = [
'-Dsonar.sources=src',
'-Dsonar.tests=test',
'-Dsonar.javascript.jstestdriver.reportsPath=results',
'-Dsonar.genericcoverage.unitTestReportPaths=' + 'results' + path.sep + 'TESTS-junit.xml',
'-Dsonar.javascript.jstestdriver.itReportsPath=results',
'-Dsonar.javascript.lcov.reportPaths=' + 'results' + path.sep + 'coverage_report.lcov' + ',' + 'results' + path.sep + 'it_coverage_report.lcov',
'-Dsonar.javascript.lcov.reportPath=' + 'results' + path.sep + 'coverage_report.lcov',
'-Dsonar.javascript.lcov.itReportPath=' + 'results' + path.sep + 'it_coverage_report.lcov'
];
// Add the parameter (-D) only when the 'key' exists in the 'object'
function addParameter(prop, object, key) {
var value = _.result(object, key);
if (value !== undefined && value !== null && sonarOptions.excludedProperties.indexOf(prop) === -1) {
args.push('-D' + prop + '=' + value);
}
}
addParameter('sonar.host.url', sonarOptions.instance, 'hostUrl');
addParameter('sonar.jdbc.url', sonarOptions.instance, 'jdbcUrl');
addParameter('sonar.jdbc.username', sonarOptions.instance, 'jdbcUsername');
addParameter('sonar.jdbc.password', sonarOptions.instance, 'jdbcPassword');
addParameter('sonar.login', sonarOptions.instance, 'login');
addParameter('sonar.password', sonarOptions.instance, 'password');
addParameter('sonar.sourceEncoding', sonarOptions, 'sourceEncoding');
addParameter('sonar.language', sonarOptions, 'language');
addParameter('sonar.dynamicAnalysis', sonarOptions, 'dynamicAnalysis');
addParameter('sonar.projectBaseDir', sonarOptions, 'defaultOutputDir');
addParameter('sonar.scm.disabled', sonarOptions, 'scmDisabled');
addParameter('sonar.projectKey', data.project, 'key');
addParameter('sonar.projectName', data.project, 'name');
addParameter('sonar.projectVersion', data.project, 'version');
addParameter('sonar.exclusions', data, 'exclusions');
return args;
}
|
javascript
|
{
"resource": ""
}
|
q55718
|
createPage
|
train
|
function createPage() {
var page = new View(view.clone(), lazy.extend({}, view.options, opts));
page.data.pagination = new Parent(lazy.extend({}, self.options, {Item: Item}));
return page;
}
|
javascript
|
{
"resource": ""
}
|
q55719
|
train
|
function (prop, fn) {
if (typeof prop === 'function') {
fn = prop;
prop = undefined;
}
if (typeof prop === 'undefined') {
return this.sortByKeys(fn);
}
return this.sortByItems(prop, fn);
}
|
javascript
|
{
"resource": ""
}
|
|
q55720
|
train
|
function (fn) {
var items = this.items;
var sorted = lazy.sortObject(this.keyMap, {prop: undefined, get: fn});
var keys = Object.keys(sorted);
var len = keys.length, i = -1;
var arr = new Array(len);
while (++i < len) {
var key = keys[i];
arr[i] = items[sorted[key]];
sorted[key] = i;
}
this.items = arr;
this.keyMap = sorted;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q55721
|
train
|
function (prop) {
var keys = Object.keys(this.keyMap);
var items = this.items.map(function (item, i) {
item.key = keys[i];
return item;
});
var sorted = lazy.arraySort(items, prop);
this.items = sorted;
this.keyMap = this.items.reduce(function (acc, item, i) {
acc[item.key] = i;
return acc;
}, {});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q55722
|
File
|
train
|
function File(file, options) {
Item.call(this, file, options);
this.initFile(file);
return file;
}
|
javascript
|
{
"resource": ""
}
|
q55723
|
train
|
function (file) {
this.src = file.src || {};
if (this.path) {
this.src.path = this.path;
}
if (Buffer.isBuffer(this.contents)) {
this.content = this.contents.toString();
}
if (this.content) {
this.options.orig = this.content;
}
// ensure that `file` has `path` and `content` properties
this.validate(file);
this.options.orig = file.content;
this.options.plural = this.collection.options.plural;
this.options.handled = this.options.handled = [];
this.src = file.src || {};
this.src.path = this.src.path || this.path;
// add non-emumerable properties
this.defineOption('route', this.options.route);
this.define('_callbacks', this._callbacks);
file.__proto__ = this;
file.path = this.path;
// handle `onLoad` middleware routes
this.app.handle('onLoad', file);
}
|
javascript
|
{
"resource": ""
}
|
|
q55724
|
train
|
function(key) {
var fn = this.pickOption('renameKey');
if (!fn) {
fn = this.collection.renameKey || this.app.renameKey;
}
if (typeof fn !== 'function') return key;
return fn(key);
}
|
javascript
|
{
"resource": ""
}
|
|
q55725
|
View
|
train
|
function View(view, options) {
this.history = [];
Item.call(this, view, options);
this.init(view);
return view;
}
|
javascript
|
{
"resource": ""
}
|
q55726
|
train
|
function (view) {
view.base = view.base || view.cwd || process.cwd();
this.src = this.src || {};
// ensure that `view` has `path` and `content` properties
this.validate(view);
this.options.orig = view.content;
this.options.plural = this.collection.options.plural;
this.options.viewType = this.options.viewType = [];
this.options.handled = this.options.handled = [];
this.contexts = view.contexts = {};
this.locals = view.locals || {};
this.data = view.data || {};
mixins(this);
// add non-emumerable properties
this.defineOption('route', this.options.route);
this.define('_callbacks', this._callbacks);
if (view.stat) {
utils.defineProp(view, 'history', view.history);
utils.defineProp(view, '_contents', view._contents);
utils.defineProp(view, 'stat', view.stat);
}
view.__proto__ = this;
utils.defineProp(view, '_callbacks', view._callbacks);
// handle `onLoad` middleware routes
this.app.handleView('onLoad', view, view.locals);
this.ctx('locals', view.locals);
this.ctx('data', view.data);
}
|
javascript
|
{
"resource": ""
}
|
|
q55727
|
train
|
function(locals, cb) {
if (typeof locals === 'function') {
cb = locals;
locals = {};
}
this.app.render(this, locals, cb);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q55728
|
train
|
function(locals, fn) {
if (typeof locals === 'function') {
fn = locals;
locals = {};
}
var res = this.locals;
var data = this.app.cache.data;
this.ctx('global', data);
// extend context with same-named data-property from `app.cache.data`
if (!this.hint('extended')) {
this.hint('extended', true);
var name = this.collection.renameKey(this.path);
this.ctx('matched', data[name]);
}
this.ctx('data', this.data);
this.ctx('options', this.options);
// build up the array of context keys to calculate
var keys = ['global', 'compile', 'render', 'options', 'matched'];
if (this.pickOption('prefer locals') === true) {
keys = keys.concat(['data', 'locals']);
} else {
keys = keys.concat(['locals', 'data']);
}
keys = keys.concat(['helper', 'custom']);
function calculate(obj, contexts, props) {
var len = props.length, i = -1;
while (++i < len) {
var key = props[i];
lazy.extend(obj, contexts[key] || {});
}
}
fn = fn || this.pickOption('context');
if (typeof fn === 'function') {
fn.call(this, res, this.contexts, keys, calculate);
} else {
calculate(res, this.contexts, keys);
}
locals = locals || {};
lazy.extend(res, this.app.mergePartials(locals));
lazy.extend(res, locals);
return res;
}
|
javascript
|
{
"resource": ""
}
|
|
q55729
|
Collection
|
train
|
function Collection(options) {
Base.call(this, options);
this.define('lists', {});
this.define('_items', {});
this.define('Item', this.options.Item || require('./item'));
this.define('List', this.options.List || require('./list'));
mixins(this);
/**
* Get an object representing the current items on the instance.
*
* ```js
* var items = this.items;
* ```
*
* @return {Object} Object of items
*/
Object.defineProperty(this, 'items', {
enumerable: false,
configurable: true,
get: function () {
return this._items;
},
set: function (items) {
lazy.forIn(items, function (item, key) {
delete this._items[key];
delete this[key];
this.set(key, item);
}, this);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q55730
|
train
|
function (prop, val) {
this.setItem(prop, val);
if (prop === 'app' || prop === 'collection') {
this.define(prop, val);
} else {
lazy.set(this, prop, val);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q55731
|
train
|
function (prop, val) {
if (prop === 'app' || prop === 'collection') {
utils.defineProp(this._items, prop, val);
} else {
this._items[prop] = val;
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q55732
|
train
|
function (name, items) {
var List = this.get('List');
var list = this.lists[name];
if (typeof list === 'undefined') {
var opts = lazy.clone(this.options);
opts.items = items || this.items;
opts.collection = this;
this.lists[name] = list = new List(opts);
}
return list;
}
|
javascript
|
{
"resource": ""
}
|
|
q55733
|
train
|
function (prop, fn) {
if (typeof prop === 'function') {
fn = prop;
prop = undefined;
}
var items = this.items;
this.items = lazy.sortObj(items, {
prop: prop,
get: fn
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q55734
|
Item
|
train
|
function Item(item, options) {
Base.call(this, options);
this.define('collection', this.options.collection);
if (typeof item === 'object') {
this.visit('set', item);
}
}
|
javascript
|
{
"resource": ""
}
|
q55735
|
train
|
function(prop) {
var opt = this.option(prop);
if (typeof opt === 'undefined') {
opt = this.collection && this.collection.option(prop);
}
if (typeof opt === 'undefined') {
return this.app && this.app.option(prop);
}
return opt;
}
|
javascript
|
{
"resource": ""
}
|
|
q55736
|
train
|
function (data) {
var parse = function() {
var parsed = lazy.extend({}, lazy.parseFilepath(this.path), data);
if (typeof parsed.ext === 'undefined') {
parsed.ext = parsed.extname;
}
return parsed;
}.bind(this);
return this.fragmentCache('path', parse);
}
|
javascript
|
{
"resource": ""
}
|
|
q55737
|
train
|
function(filepath, fn) {
fn = fn || lazy.dashify;
if (typeof filepath === 'undefined') {
var ctx = this.context();
filepath = ctx.slug || this.path;
}
return fn(filepath);
}
|
javascript
|
{
"resource": ""
}
|
|
q55738
|
train
|
function(str) {
if (typeof str !== 'string') {
str = this.content;
}
if (typeof str !== 'string') return '';
str = str.replace(/(<([^>]+)>)/g, '');
return str.trim();
}
|
javascript
|
{
"resource": ""
}
|
|
q55739
|
train
|
function (options) {
options = options || {};
lazy.extend(options, this.options.excerpt || {});
var re = /<!--+\s*more\s*--+>/;
var str = this.content;
var view = this;
var link = options.link || '<a id="more"></a>';
this.content = str.replace(re, function (match, i) {
view.data.excerpt = str.slice(0, i).trim();
view.data.more = str.slice(i + match.length).trim() + link;
return '';
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q55740
|
train
|
function (structure, locals) {
if (typeof structure !== 'string') {
locals = structure;
structure = null;
}
var self = this;
var data = {};
lazy.extend(data, this);
lazy.extend(data, this.parsePath());
lazy.extend(data, this.context(locals));
this.data.dest = this.data.dest || {};
var opts = lazy.get(data, 'permalinks') || {};
lazy.extend(opts, this.options.permalinks || {});
if (typeof structure !== 'string') {
structure = opts.structure || ':path';
}
return structure.replace(/:(\w+)(?:\((.*)\))?/g, function (m, param, prop) {
var res = data[param] || param;
if (typeof res === 'function' && prop) {
return res.call(data, prop);
}
self.data.dest = res;
return res;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q55741
|
Views
|
train
|
function Views(options) {
Collection.call(this, options);
this.options.collection = this.options.collection || this;
this.define('View', this.options.View || require('./view'));
this.define('Item', this.View);
}
|
javascript
|
{
"resource": ""
}
|
q55742
|
train
|
function (key, val) {
if (lazy.typeOf(val) !== 'object') {
lazy.set(this, key, val);
return this;
}
this.addView(key, val);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q55743
|
train
|
function (key, val) {
var opts = lazy.clone(this.options);
var View = this.get('View');
val.path = val.path || key;
key = val.key = this.renameKey(key);
this.setItem(key, (this[key] = new View(val, opts)));
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q55744
|
train
|
function(prop) {
var res = this[prop];
if (typeof res === 'undefined') {
var name = this.renameKey(prop);
if (name && name !== prop) {
res = this[name];
}
}
if (typeof res === 'undefined') {
res = lazy.get(this, prop);
}
if (typeof res === 'undefined') {
res = this.find(prop);
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
|
q55745
|
train
|
function (pattern, options) {
var self = this;
function find() {
var isMatch = lazy.mm.matcher(pattern, options);
for (var key in self) {
var val = self[key];
if (typeof val === 'object' && isMatch(key)) {
return val;
}
}
}
var res = this.fragmentCache(pattern, find);
res.__proto__ = this;
return res;
}
|
javascript
|
{
"resource": ""
}
|
|
q55746
|
train
|
function (view/*, locals, fn*/) {
var args = [].slice.call(arguments, 1);
var app = this.app;
if (typeof view === 'string') view = this[view];
app.render.apply(app, [view].concat(args));
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q55747
|
train
|
function (prop, pattern, options) {
options = options || {};
var views = this.items;
var res = Object.create(this);
var matcher = pattern ? lazy.mm.isMatch(pattern, options) : null;
for (var key in views) {
if (views.hasOwnProperty(key)) {
var file = views[key];
if (prop === 'key') {
if (matcher) {
if (matcher(path.relative(process.cwd(), key))) {
res[key] = file;
}
} else {
res[key] = file;
}
} else {
var val = lazy.get(file, prop);
if (prop === 'path' || prop === 'cwd') {
val = path.relative(process.cwd(), val);
}
if (lazy.has(val)) {
if (matcher) {
if (matcher(val)) {
res[key] = file;
}
} else {
res[key] = file;
}
}
}
}
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
|
q55748
|
train
|
function() {
this.options.viewType = utils.arrayify(this.options.viewType || []);
if (this.options.viewType.length === 0) {
this.options.viewType.push('renderable');
}
return this.options.viewType;
}
|
javascript
|
{
"resource": ""
}
|
|
q55749
|
Base
|
train
|
function Base(options) {
this.define('options', options || {});
this.define('hints', this.hints || {});
this.define('data', this.data || {});
this.define('app', this.app || this.options.app || {});
this.define('_cache', {});
this.define('_callbacks', this._callbacks);
if (typeof this.options.mixins === 'object') {
this.visit('mixin', this.options.mixins);
}
}
|
javascript
|
{
"resource": ""
}
|
q55750
|
train
|
function (key, val) {
if (this._cache[key]) {
return this._cache[key];
}
if (typeof val === 'function') {
val = val.call(this);
}
return (this._cache[key] = val);
}
|
javascript
|
{
"resource": ""
}
|
|
q55751
|
train
|
function (keys) {
var Parent = this.constructor;
var opts = lazy.clone(this.options);
var res = new Parent(opts);
lazy.omit(this, keys, function (val, key) {
res[key] = lazy.clone(val);
});
return res;
}
|
javascript
|
{
"resource": ""
}
|
|
q55752
|
train
|
function(prop) {
var opt = this.option(prop);
if (typeof opt === 'undefined') {
return this.app && this.app.option ? this.app.option(prop) : null;
}
return opt;
}
|
javascript
|
{
"resource": ""
}
|
|
q55753
|
train
|
function (key, fn) {
if (typeof key === 'function') {
fn = key;
key = null;
}
if (typeof fn !== 'function') {
fn = this.pickOption('renameKey');
}
if (typeof fn !== 'function') {
fn = utils.identity;
}
this.options.renameKey = fn;
if (arguments.length === 2) {
return fn(key);
}
if (typeof key === 'string') {
return fn(key);
}
return fn;
}
|
javascript
|
{
"resource": ""
}
|
|
q55754
|
shortenUrl
|
train
|
function shortenUrl ( url , length ) {
if( !isBlank( url ) && url.length > length) {
url = url.substr( 0 , length ) + "...";
}
return url;
}
|
javascript
|
{
"resource": ""
}
|
q55755
|
train
|
function(helpers, options) {
if (typeof helpers === 'object') {
this.visit('helper', helpers);
return this;
}
if (lazy.isGlob(helpers)) {
this.loader('helpers-glob', ['base-glob'], function (files) {
return files.map(function (fp) {
return require(path.resolve(fp));
});
});
var res = this.compose('helpers-glob')(helpers, options);
this.visit('helper', res);
return this;
}
if (typeof helpers === 'string') {
console.log('loading helpers from a string is not implemented yet.');
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q55756
|
List
|
train
|
function List(options) {
Base.call(this, options || {});
this.items = [];
this.define('keyMap', {});
this.define('Item', this.options.Item || require('./item'));
this.visit('item', this.options.items || {});
delete this.options.items;
mixins(this);
}
|
javascript
|
{
"resource": ""
}
|
q55757
|
train
|
function(key, value) {
if (typeof key !== 'string') {
throw new TypeError('item key must be a string.');
}
if (typeof value === 'undefined') {
return this.getItem(key);
}
this.addItem(key, value);
return value;
}
|
javascript
|
{
"resource": ""
}
|
|
q55758
|
train
|
function (key, value) {
var Item = this.get('Item');
if (!(value instanceof Item)) {
value = new Item(value);
}
value.key = value.key || key;
var i = this.indexOf(key);
if (i !== -1) {
this.items[i] = value;
} else {
this.items.push(value);
this.keyMap[key] = this.items.length - 1;
}
this.emit('item', key, value);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q55759
|
train
|
function (locals, cb) {
if (typeof locals === 'function') {
cb = locals;
locals = {};
}
lazy.each(this.items, function (item, next) {
this.app.render(item, locals, next);
}.bind(this), cb);
}
|
javascript
|
{
"resource": ""
}
|
|
q55760
|
train
|
function(exts, fn, options) {
if (arguments.length === 1 && typeof exts === 'string') {
return this.getEngine(exts);
}
exts = utils.arrayify(exts);
var len = exts.length;
while (len--) {
var ext = exts[len];
if (ext && ext[0] !== '.') ext = '.' + ext;
this._.engines.setEngine(ext, fn, options);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q55761
|
train
|
function(ext) {
ext = ext || this.option('view engine');
if (ext && ext[0] !== '.') {
ext = '.' + ext;
}
return this._.engines.getEngine(ext);
}
|
javascript
|
{
"resource": ""
}
|
|
q55762
|
train
|
function(key, val) {
if (arguments.length === 1) {
if (typeof key === 'string') {
if (key.indexOf('.') === -1) {
return this.cache.data[key];
}
if (lazy.isGlob(key)) {
this.compose('data')(key, val);
return this;
}
return lazy.get(this.cache.data, key);
}
}
if (typeof key === 'object') {
var args = [].slice.call(arguments);
key = [].concat.apply([], args);
this.visit('data', key);
return this;
}
lazy.set(this.cache.data, key, val);
this.emit('data', key, val);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q55763
|
train
|
function (methods) {
this.lazyLoaders();
var loaders = this.loaders;
var self = this;
utils.arrayify(methods).forEach(function (method) {
self.define(method, function() {
return loaders[method].apply(loaders, arguments);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q55764
|
train
|
function (name, opts, loaders) {
var args = utils.slice(arguments, 1);
opts = lazy.clone(args.shift());
loaders = args;
var single = lazy.inflect.singularize(name);
var plural = lazy.inflect.pluralize(name);
this.inflections[single] = plural;
if (typeof opts.renameKey === 'undefined' && this.options.renameKey) {
opts.renameKey = this.options.renameKey;
}
opts.plural = plural;
opts.inflection = single;
opts.loaders = loaders;
opts.app = this;
opts = lazy.extend({}, opts, this.options);
if (!opts.loaderType) {
opts.loaderType = 'sync';
}
var Views = this.get('Views');
var views = new Views(opts);
this.viewType(plural, views.viewType());
// add custom View constructor for collection items
var ViewClass = viewFactory(single, opts);
var classKey = single[0].toUpperCase() + single.slice(1);
this.define(classKey, ViewClass);
// init the collection object on `views`
this.views[plural] = views;
this.loader(plural, opts, loaders);
// wrap loaders to expose the collection and opts
utils.defineProp(opts, 'wrap', views.wrap.bind(views, opts));
opts.defaultLoader = opts.defaultLoader || 'default';
// create the actual loader function
var fn = this.compose(plural, opts);
views.forward(fn, ['forOwn']);
// forward collection methods onto loader
utils.setProto(fn, views);
// add loader methods to the instance: `app.pages()`
this.mixin(single, fn);
this.mixin(plural, fn);
// decorate named loader methods back to the collection
// to allow chaining like `.pages().pages()` etc
utils.defineProp(views, plural, fn);
utils.defineProp(views, single, fn);
// add collection and view (item) helpers
helpers.collection(this, views, opts);
helpers.view(this, views, opts);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q55765
|
train
|
function (method, view, locals, cb) {
if (typeof locals === 'function') {
cb = locals;
locals = {};
}
this.lazyRouter();
view.options = view.options || {};
view.options.handled = view.options.handled || [];
if (typeof cb !== 'function') {
cb = this.handleError(method, view);
}
view.options.method = method;
view.options.handled.push(method);
if (view.emit) {
view.emit('handle', method);
}
this.router.handle(view, function (err) {
if (err) return cb(err);
cb(null, view);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q55766
|
train
|
function (method, view, locals/*, cb*/) {
if (view.options.handled.indexOf(method) === -1) {
this.handle.apply(this, arguments);
}
this.emit(method, view, locals);
}
|
javascript
|
{
"resource": ""
}
|
|
q55767
|
train
|
function(method, view) {
return function (err) {
if (err) {
err.reason = 'Template#handle' + method + ': ' + view.path;
return err;
}
};
}
|
javascript
|
{
"resource": ""
}
|
|
q55768
|
train
|
function(path/*, callback*/) {
this.lazyRouter();
var route = this.router.route(path);
route.all.apply(route, [].slice.call(arguments, 1));
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q55769
|
train
|
function(view) {
if (view.options.layoutApplied) {
return view;
}
// handle pre-layout middleware
this.handle('preLayout', view);
var opts = {};
lazy.extend(opts, this.options);
lazy.extend(opts, view.options);
lazy.extend(opts, view.context());
// get the layout stack
var stack = {};
var alias = this.viewTypes.layout;
var len = alias.length, i = 0;
while (len--) {
var views = this.views[alias[i++]];
for (var key in views) {
var val = views[key];
if (views.hasOwnProperty(key) && typeof val !== 'function' && val.path) {
stack[key] = val;
}
}
}
// get the name of the first layout
var name = view.layout;
var str = view.content;
var self = this;
if (!name) return view;
// Handle each layout before it's applied to a view
function handleLayout(layoutObj) {
view.currentLayout = layoutObj.layout;
self.handle('onLayout', view);
delete view.currentLayout;
}
// actually apply the layout
var res = lazy.layouts(str, name, stack, opts, handleLayout);
view.option('layoutStack', res.history);
view.option('layoutApplied', true);
view.content = res.result;
// handle post-layout middleware
this.handle('postLayout', view);
return view;
}
|
javascript
|
{
"resource": ""
}
|
|
q55770
|
train
|
function(view, locals, isAsync) {
if (typeof locals === 'boolean') {
isAsync = locals;
locals = {};
}
// get the engine to use
locals = locals || {};
var engine = this.engine(locals.engine ? locals.engine : view.engine);
if (typeof engine === 'undefined') {
throw this.error('compile', 'engine', view);
}
if (!engine.hasOwnProperty('compile')) {
throw this.error('compile', 'method', engine);
}
view.ctx('compile', locals);
// build the context to pass to the engine
var ctx = view.context(locals);
// apply layout
view = this.applyLayout(view, ctx);
// handle `preCompile` middleware
this.handleView('preCompile', view, locals);
// Bind context to helpers before passing to the engine.
this.bindHelpers(view, locals, ctx, (locals.async = isAsync));
var settings = lazy.extend({}, ctx, locals);
// compile the string
view.fn = engine.compile(view.content, settings);
// handle `postCompile` middleware
this.handleView('postCompile', view, locals);
return view;
}
|
javascript
|
{
"resource": ""
}
|
|
q55771
|
train
|
function (view, locals, cb) {
if (typeof locals === 'function') {
cb = locals;
locals = {};
}
// if `view` is a function, it's probably from chaining
// a collection method
if (typeof view === 'function') {
return view.call(this);
}
// if `view` is a string, see if it's a cache view
if (typeof view === 'string') {
view = this.lookup(view);
}
locals = locals || {};
// add `locals` to `view.contexts`
view.ctx('render', locals);
var data = this.cache.data;
for (var key in locals) {
if (locals.hasOwnProperty(key) && !data.hasOwnProperty(key)) {
data[key] = locals[key];
}
}
// handle `preRender` middleware
this.handleView('preRender', view, locals);
// build the context for the view
var ctx = this.context(locals);
// get the engine
var engine = this.engine(locals.engine ? locals.engine : view.engine);
if (typeof cb !== 'function') {
throw this.error('render', 'callback');
}
if (typeof engine === 'undefined') {
throw this.error('render', 'engine', path.extname(view.path));
}
if (!engine.hasOwnProperty('render')) {
throw this.error('render', 'method', JSON.stringify(view));
}
// if it's not already compiled, do that first
if (typeof view.fn !== 'function') {
try {
var isAsync = typeof cb === 'function';
view = this.compile(view, locals, isAsync);
return this.render(view, locals, cb);
} catch (err) {
this.emit('error', err);
return cb.call(this, err);
}
}
var context = this.context(view, ctx, locals);
// render the view
return engine.render(view.fn, context, function (err, res) {
if (err) {
this.emit('error', err);
return cb.call(this, err);
}
// handle `postRender` middleware
view.content = res;
this.handle('postRender', view, locals, cb);
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q55772
|
train
|
function (locals, viewTypes) {
var names = viewTypes || this.viewTypes.partial;
var opts = lazy.extend({}, this.options, locals);
return names.reduce(function (acc, name) {
var collection = this.views[name];
lazy.forOwn(collection, function (view, key) {
// handle `onMerge` middleware
this.handleView('onMerge', view, locals);
if (view.options.nomerge) return;
if (opts.mergePartials !== false) {
name = 'partials';
}
acc[name] = acc[name] || {};
acc[name][key] = view.content;
}, this);
return acc;
}.bind(this), {});
}
|
javascript
|
{
"resource": ""
}
|
|
q55773
|
train
|
function (view, ctx, locals) {
var obj = {};
lazy.mixin(obj, ctx);
lazy.mixin(obj, this.cache.data);
lazy.mixin(obj, view.data);
lazy.mixin(obj, view.locals);
lazy.mixin(obj, locals);
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q55774
|
train
|
function (view, locals, context, isAsync) {
var helpers = {};
lazy.extend(helpers, this.options.helpers);
lazy.extend(helpers, this._.helpers.sync);
if (isAsync) lazy.extend(helpers, this._.helpers.async);
lazy.extend(helpers, locals.helpers);
// build the context to expose as `this` in helpers
var thisArg = {};
thisArg.options = lazy.extend({}, this.options, locals);
thisArg.context = context || {};
thisArg.context.view = view;
thisArg.app = this;
// bind template helpers to the instance
locals.helpers = utils.bindAll(helpers, thisArg);
}
|
javascript
|
{
"resource": ""
}
|
|
q55775
|
train
|
function (methods) {
this.lazyRouter();
this.router.method(methods);
utils.arrayify(methods).forEach(function (method) {
this.define(method, function(path) {
var route = this.router.route(path);
var args = [].slice.call(arguments, 1);
route[method].apply(route, args);
return this;
}.bind(this));
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q55776
|
train
|
function(collection, pattern, options) {
var views = this.getViews(collection);
if (views.hasOwnProperty(pattern)) {
return views[pattern];
}
return utils.matchKey(views, pattern, options);
}
|
javascript
|
{
"resource": ""
}
|
|
q55777
|
train
|
function(collection, pattern, options) {
var views = this.getViews(collection);
return utils.matchKeys(views, pattern, options);
}
|
javascript
|
{
"resource": ""
}
|
|
q55778
|
train
|
function(collection, key, fn) {
var views = this.getViews(collection);
// if a custom renameKey function is passed, try using it
if (typeof fn === 'function') {
key = fn(key);
}
if (views.hasOwnProperty(key)) {
return views[key];
}
// try again with the default renameKey function
fn = this.option('renameKey');
var name;
if (typeof fn === 'function') {
name = fn(key);
}
if (name && name !== key && views.hasOwnProperty(name)) {
return views[name];
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q55779
|
train
|
function(plural) {
if (lazy.isObject(plural)) return plural;
if (!this.views.hasOwnProperty(plural)) {
plural = this.inflections[plural];
}
if (!this.views.hasOwnProperty(plural)) {
throw new Error('getViews cannot find collection' + plural);
}
return this.views[plural];
}
|
javascript
|
{
"resource": ""
}
|
|
q55780
|
train
|
function (view, collection) {
if (typeof view === 'string') {
if (typeof collection === 'string') {
return this[collection].get(view);
}
var collections = this.viewTypes.renderable;
var len = collections.length, i = 0;
while (len--) {
var plural = collections[i++];
var views = this.views[plural];
var res;
if (res = views[view]) {
return res;
}
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q55781
|
register
|
train
|
function register(client) {
const appId = client.appId;
if (registry[appId] && !registry[appId].isDestroyed) {
registry[appId].destroy();
}
registry[appId] = client;
defer(() => listeners.forEach(listener => listener(client)));
}
|
javascript
|
{
"resource": ""
}
|
q55782
|
removeListener
|
train
|
function removeListener(listener) {
if (listener) {
const index = listeners.indexOf(listener);
if (index >= 0) listeners.splice(index, 1);
} else {
listeners.splice(0, listeners.length);
}
}
|
javascript
|
{
"resource": ""
}
|
q55783
|
getBin
|
train
|
function getBin(filename) {
try {
return escape(whichLocal.sync(filename));
} catch (unused) {
return escape(whichCwd.sync(filename));
}
}
|
javascript
|
{
"resource": ""
}
|
q55784
|
train
|
function (sources, tmp) {
var instrumenter = new istanbul.Instrumenter();
var instrumentedSources = [];
sources.forEach(function (source) {
var instrumentedSource = instrumenter.instrumentSync(
grunt.file.read(source), source);
var tmpSource = source;
// don't try to write "C:" as part of a folder name on Windows
if (process.platform == 'win32') {
tmpSource = tmpSource.replace(/^([a-z]):/i, '$1');
}
tmpSource = path.join(tmp, tmpSource);
grunt.file.write(tmpSource, instrumentedSource);
instrumentedSources.push(tmpSource);
});
return instrumentedSources;
}
|
javascript
|
{
"resource": ""
}
|
|
q55785
|
train
|
function (type, options, collector) {
istanbul.Report.create(type, options).writeReport(collector, true);
}
|
javascript
|
{
"resource": ""
}
|
|
q55786
|
train
|
function (collector, options) {
if (typeof options == 'string' || options instanceof String) {
// default to html report at options directory
writeReport('html', {
dir: options
}, collector);
} else if (options instanceof Array) {
// multiple reports
for (var i = 0; i < options.length; i = i + 1) {
var report = options[i];
writeReport(report.type, report.options, collector);
}
} else {
// single report
writeReport(options.type, options.options, collector);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55787
|
train
|
function (collector, options) {
var summaries = [];
var thresholds = options.thresholds;
var files = collector.files();
files.forEach(function(file) {
summaries.push(istanbul.utils.summarizeFileCoverage(
collector.fileCoverageFor(file)));
});
var finalSummary = istanbul.utils.mergeSummaryObjects.apply(null,
summaries);
grunt.util._.each(thresholds, function (threshold, metric) {
var actual = finalSummary[metric];
if(!actual) {
grunt.warn('unrecognized metric: ' + metric);
}
if(actual.pct < threshold) {
grunt.warn('expected ' + metric + ' coverage to be at least '
+ threshold + '% but was ' + actual.pct + '%');
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q55788
|
train
|
function (grunt, task, context) {
var template = context.options.template;
if (!template) {
template = DEFAULT_TEMPLATE;
}
// clone context
var mixedInContext = JSON.parse(JSON.stringify(context));
// transit templateOptions
mixedInContext.options = context.options.templateOptions || {};
if (template.process) {
return template.process(grunt, task, mixedInContext);
} else {
return grunt.util._.template(grunt.file.read(template), mixedInContext);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55789
|
parseArgs
|
train
|
function parseArgs(obj) {
var args = [];
_.each(obj, function (val, key) {
if (_.isArray(val)) {
_.each(val, function (val) {
addArg(args, key, val);
});
} else {
addArg(args, key, val);
}
});
return args;
}
|
javascript
|
{
"resource": ""
}
|
q55790
|
addArg
|
train
|
function addArg(args, name, val) {
if (!val && val !== 0) {
return;
}
var arg = name.length > 1 ? '--' + _.kebabCase(name) : '-' + name;
// --max-old-space-size argument requires an `=`
if (arg === '--max-old-space-size') {
args.push(arg + '=' + val);
return;
} else {
args.push(arg);
}
if (_.isString(val) || _.isNumber(val)) {
args.push(val);
}
}
|
javascript
|
{
"resource": ""
}
|
q55791
|
expose
|
train
|
function expose(obj, namespace, name) {
var app = this.app || this;
var req = this.req;
app._exposed = app._exposed || {};
// support second arg as name
// when a string or function is given
if ('string' === typeof obj || 'function' === typeof obj) {
name = namespace || _name;
} else {
name = name || _name;
namespace = namespace || _namespace;
}
// buffer string
if ('string' === typeof obj) {
this.js = this.js || {};
var buf = this.js[name] = this.js[name] || [];
buf.push(obj);
// buffer function
} else if ('function' === typeof obj && obj.name) {
this.expose(obj.toString(), name);
// buffer self-calling function
} else if ('function' === typeof obj) {
this.expose(';(' + obj + ')();', name);
// buffer object
} else {
this.expose(renderNamespace(namespace), name);
this.expose(renderObject(obj, namespace), name);
this.expose('\n');
}
// locals
function locals(req, res) {
var appjs = app.exposed(name);
var resjs = res.exposed(name);
var js = '';
if (appjs || resjs) {
js += '// app: \n' + appjs;
js += '// res: \n' + resjs;
}
res.locals[name] = js;
}
// app level locals
if (!req && !app._exposed[name]) {
app._exposed[name] = true;
app.use(function(req, res, next){
locals(req, res);
next();
});
// request level locals
} else if (req) {
locals(req, this);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q55792
|
exposed
|
train
|
function exposed(name) {
name = name || _name;
this.js = this.js || {};
return this.js[name]
? this.js[name].join('\n')
: '';
}
|
javascript
|
{
"resource": ""
}
|
q55793
|
renderNamespace
|
train
|
function renderNamespace(str) {
var parts = [];
var split = str.split('.');
var len = split.length;
return str.split('.').map(function(part, i) {
parts.push(part);
part = parts.join('.');
return (i ? '' : 'window.') + part + ' = window.' + part + ' || {};';
}).join('\n');
}
|
javascript
|
{
"resource": ""
}
|
q55794
|
renderObject
|
train
|
function renderObject(obj, namespace) {
return Object.keys(obj).map(function(key){
var val = obj[key];
return namespace + '["' + key + '"] = ' + string(val) + ';';
}).join('\n');
}
|
javascript
|
{
"resource": ""
}
|
q55795
|
string
|
train
|
function string(obj) {
if ('function' === typeof obj) {
return obj.toString();
} else if (obj instanceof Date) {
return 'new Date("' + obj + '")';
} else if (Array.isArray(obj)) {
return '[' + obj.map(string).join(', ') + ']';
} else if ('[object Object]' === Object.prototype.toString.call(obj)) {
return '{' + Object.keys(obj).map(function(key){
return '"' + key + '":' + string(obj[key]);
}).join(', ') + '}';
} else {
return JSON.stringify(obj);
}
}
|
javascript
|
{
"resource": ""
}
|
q55796
|
MurmurHash3
|
train
|
function MurmurHash3(seed, data) {
/* jshint maxstatements: 32, maxcomplexity: 10 */
var c1 = 0xcc9e2d51;
var c2 = 0x1b873593;
var r1 = 15;
var r2 = 13;
var m = 5;
var n = 0x6b64e654;
var hash = seed;
function mul32(a, b) {
return (a & 0xffff) * b + (((a >>> 16) * b & 0xffff) << 16) & 0xffffffff;
}
function sum32(a, b) {
return (a & 0xffff) + (b >>> 16) + (((a >>> 16) + b & 0xffff) << 16) & 0xffffffff;
}
function rotl32(a, b) {
return (a << b) | (a >>> (32 - b));
}
var k1;
for (var i = 0; i + 4 <= data.length; i += 4) {
k1 = data[i] |
(data[i + 1] << 8) |
(data[i + 2] << 16) |
(data[i + 3] << 24);
k1 = mul32(k1, c1);
k1 = rotl32(k1, r1);
k1 = mul32(k1, c2);
hash ^= k1;
hash = rotl32(hash, r2);
hash = mul32(hash, m);
hash = sum32(hash, n);
}
k1 = 0;
switch(data.length & 3) {
case 3:
k1 ^= data[i + 2] << 16;
/* falls through */
case 2:
k1 ^= data[i + 1] << 8;
/* falls through */
case 1:
k1 ^= data[i];
k1 = mul32(k1, c1);
k1 = rotl32(k1, r1);
k1 = mul32(k1, c2);
hash ^= k1;
}
hash ^= data.length;
hash ^= hash >>> 16;
hash = mul32(hash, 0x85ebca6b);
hash ^= hash >>> 13;
hash = mul32(hash, 0xc2b2ae35);
hash ^= hash >>> 16;
return hash >>> 0;
}
|
javascript
|
{
"resource": ""
}
|
q55797
|
train
|
function ()
{
var mask = this.mask;
var included =
_Array_prototype_every.call
(
arguments,
function (arg)
{
var otherMask = validMaskFromArrayOrStringOrFeature(arg);
var result = maskIncludes(mask, otherMask);
return result;
}
);
return included;
}
|
javascript
|
{
"resource": ""
}
|
|
q55798
|
train
|
function (environment, engineFeatureObjs)
{
var resultMask = maskNew();
var thisMask = this.mask;
var attributeCache = createEmpty();
ELEMENTARY.forEach
(
function (featureObj)
{
var otherMask = featureObj.mask;
var included = maskIncludes(thisMask, otherMask);
if (included)
{
var attributeValue = featureObj.attributes[environment];
if
(
attributeValue === undefined ||
engineFeatureObjs !== undefined &&
!isExcludingAttribute(attributeCache, attributeValue, engineFeatureObjs)
)
resultMask = maskUnion(resultMask, otherMask);
}
}
);
var result = featureFromMask(resultMask);
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q55799
|
train
|
function ()
{
var name = this.name;
if (name === undefined)
name = '{' + this.canonicalNames.join(', ') + '}';
var str = '[Feature ' + name + ']';
return str;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.