_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q400 | train | function(filedata, callback) {
var lines;
lines = filedata.toString().split(/(?:\r\n|\r|\n)/gm);
if (module.exports.verify(lines)) {
return callback(undefined, lines);
}
return callback('INVALID_SRT_FORMAT');
} | javascript | {
"resource": ""
} |
|
q401 | train | function(data) {
var json = {},
index = 0,
id,
text,
startTimeMicro,
durationMicro,
invalidText = /^\s+$/,
endTimeMicro,
time,
lastNonEmptyLine;
function getLastNonEmptyLine(linesArray) {
var idx = linesArray.length - 1;
while (idx >= 0 && !linesArray[idx]) {
idx--;
}
return idx;
}
json.captions = [];
lastNonEmptyLine = getLastNonEmptyLine(data) + 1;
while (index < lastNonEmptyLine) {
if (data[index]) {
text = [];
//Find the ID line..
if (/^[0-9]+$/.test(data[index])) {
//found id line
id = parseInt(data[index], 10);
index++;
}
if (!data[index].split) {
// for some reason this is not a string
index++;
continue;
}
//next line has to be timestamp right? right?
time = data[index].split(/[\t ]*-->[\t ]*/);
startTimeMicro = module.exports.translateTime(time[0]);
endTimeMicro = module.exports.translateTime(time[1]);
durationMicro = parseInt(parseInt(endTimeMicro, 10) - parseInt(startTimeMicro, 10), 10);
if (!startTimeMicro || !endTimeMicro) {
// no valid timestamp
index++;
continue;
}
index++;
while (data[index]) {
text.push(data[index]);
index++;
if (!data[index] && !invalidText.test(text.join('\n'))) {
json.captions.push({
id: id,
text: module.exports.addMacros(text.join('\n')),
startTimeMicro: startTimeMicro,
durationSeconds: parseInt(durationMicro / 1000, 10) / 1000,
endTimeMicro: endTimeMicro
});
break;
}
}
}
index++;
}
return json.captions;
} | javascript | {
"resource": ""
} |
|
q402 | train | function(timestamp) {
if (!timestamp) {
return;
}
//TODO check this
//var secondsPerStamp = 1.001,
var timesplit = timestamp.replace(',', ':').split(':');
return (parseInt(timesplit[0], 10) * 3600 +
parseInt(timesplit[1], 10) * 60 +
parseInt(timesplit[2], 10) +
parseInt(timesplit[3], 10) / 1000) * 1000 * 1000;
} | javascript | {
"resource": ""
} |
|
q403 | train | function(text) {
return macros.cleanMacros(text.replace(/\n/g, '{break}').replace(/<i>/g, '{italic}').replace(/<\/i>/g, '{end-italic}'));
} | javascript | {
"resource": ""
} |
|
q404 | finishBasicPromise | train | function finishBasicPromise (resolve, reject) {
return (err, res) => {
if (err) {
return reject(err);
} else {
return resolve(res);
}
};
} | javascript | {
"resource": ""
} |
q405 | initRoutes | train | function initRoutes (ravelInstance, koaRouter) {
const proto = Object.getPrototypeOf(this);
// handle class-level @mapping decorators
const classMeta = Metadata.getClassMeta(proto, '@mapping', Object.create(null));
for (const r of Object.keys(classMeta)) {
buildRoute(ravelInstance, this, koaRouter, r, classMeta[r]);
}
// handle methods decorated with @mapping
const meta = Metadata.getMeta(proto).method;
const annotatedMethods = Object.keys(meta);
for (const r of annotatedMethods) {
const methodMeta = Metadata.getMethodMetaValue(proto, r, '@mapping', 'info');
if (methodMeta) {
buildRoute(ravelInstance, this, koaRouter, r, methodMeta);
}
}
} | javascript | {
"resource": ""
} |
q406 | getClasses | train | function getClasses(element) {
const className = element.className;
const classes = {};
if (className !== null && className.length > 0) {
className.split(' ').forEach((className) => {
if (className.trim().length) {
classes[className.trim()] = true;
}
});
}
return classes;
} | javascript | {
"resource": ""
} |
q407 | getStyle | train | function getStyle(element) {
const style = element.style;
const styles = {};
for (let i = 0; i < style.length; i++) {
const name = style.item(i);
const transformedName = transformName(name);
styles[transformedName] = style.getPropertyValue(name);
}
return styles;
} | javascript | {
"resource": ""
} |
q408 | train | function (value) {
const IllegalValue = this.$err.IllegalValue;
if (typeof value !== 'string') {
return value;
}
const result = value.replace(ENVVAR_PATTERN, function () {
const varname = arguments[1];
if (process.env[varname] === undefined) {
throw new IllegalValue(`Environment variable ${varname} was referenced but not set`);
}
return process.env[varname];
});
return result;
} | javascript | {
"resource": ""
} |
|
q409 | normalize | train | function normalize(obj, caseType = 'camel') {
let ret = obj;
const method = methods[caseType];
if (Array.isArray(obj)) {
ret = [];
let i = 0;
while (i < obj.length) {
ret.push(normalize(obj[i], caseType));
++i;
}
} else if (isPlainObject(obj)) {
ret = {};
// eslint-disable-next-line guard-for-in, no-restricted-syntax
for (const k in obj) {
ret[method(k)] = normalize(obj[k], caseType);
}
}
return ret;
} | javascript | {
"resource": ""
} |
q410 | connectHandlers | train | function connectHandlers (decorator, event) {
const handlers = Metadata.getClassMeta(Object.getPrototypeOf(self), decorator, Object.create(null));
for (const f of Object.keys(handlers)) {
ravelInstance.once(event, (...args) => {
ravelInstance.$log.trace(`${name}: Invoking ${decorator} ${f}`);
handlers[f].apply(self, args);
});
}
} | javascript | {
"resource": ""
} |
q411 | translateX | train | function translateX(progress) {
var to = (this.options.to !== undefined) ? this.options.to : 0;
var from = (this.options.from !== undefined) ? this.options.from : 0;
var offset = (to - from) * progress + from;
this.transforms.position[0] = offset;
} | javascript | {
"resource": ""
} |
q412 | scale | train | function scale(progress) {
var to = (this.options.to !== undefined) ? this.options.to : 1;
var from = (this.options.from !== undefined) ? this.options.from : this.transforms.scale[0];
var scale = (to - from) * progress + from;
this.transforms.scale[0] = scale;
this.transforms.scale[1] = scale;
} | javascript | {
"resource": ""
} |
q413 | fade | train | function fade(progress) {
var to = (this.options.to !== undefined) ? this.options.to : 0;
var from = (this.options.from !== undefined) ? this.options.from : 1;
var opacity = (to - from) * progress + from;
this.element.style.opacity = opacity;
} | javascript | {
"resource": ""
} |
q414 | blur | train | function blur(progress) {
var to = (this.options.to !== undefined) ? this.options.to : 0;
var from = (this.options.from !== undefined) ? this.options.from : 0;
var amount = (to - from) * progress + from;
this.element.style.filter = 'blur(' + amount + 'px)';
} | javascript | {
"resource": ""
} |
q415 | parallax | train | function parallax(progress) {
var range = this.options.range || 0;
var offset = progress * range; // TODO add provision for speed as well
this.transforms.position[1] = offset; // just vertical for now
} | javascript | {
"resource": ""
} |
q416 | toggle | train | function toggle(progress) {
var opts = this.options;
var element = this.element;
var times = Object.keys(opts);
times.forEach(function(time) {
var css = opts[time];
if (progress > time) {
element.classList.add(css);
} else {
element.classList.remove(css);
}
});
} | javascript | {
"resource": ""
} |
q417 | Diagram | train | function Diagram(index, options, question) {
this.index = index;
this.options = options;
this.question = question;
this.element = createElement(h('li.list-group-item', {
style: {
width: '100%',
height: '500px'
}
}));
this.viewer;
if (options.xml) {
// Load XML
this.xml = options.xml;
} else if (options.url) {
var that = this;
// Load XML via AJAX
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
that.xml = xhr.responseText;
}
};
xhr.open("GET", options.url, true);
xhr.send();
} else {
throw new Error('Unable to load diagram, no resource specified');
}
this.initState = Immutable({
selected: []
});
this.state = this.initState.asMutable({deep: true});
} | javascript | {
"resource": ""
} |
q418 | createClient | train | function createClient (ravelInstance, restrict = true) {
const localRedis = ravelInstance.get('redis port') === undefined || ravelInstance.get('redis host') === undefined;
ravelInstance.on('post init', () => {
ravelInstance.$log.info(localRedis
? 'Using in-memory key-value store. Please do not scale this app horizontally.'
: `Using redis at ${ravelInstance.get('redis host')}:${ravelInstance.get('redis port')}`);
});
let client;
if (localRedis) {
const mock = require('redis-mock');
mock.removeAllListeners(); // redis-mock doesn't clean up after itself very well.
client = mock.createClient();
client.flushall(); // in case this has been required before
} else {
client = redis.createClient(
ravelInstance.get('redis port'),
ravelInstance.get('redis host'),
{
'no_ready_check': true,
'retry_strategy': retryStrategy(ravelInstance)
});
}
if (ravelInstance.get('redis password')) {
client.auth(ravelInstance.get('redis password'));
}
// log errors
client.on('error', ravelInstance.$log.error);
// keepalive when not testing
const redisKeepaliveInterval = setInterval(() => {
client && client.ping && client.ping();
}, ravelInstance.get('redis keepalive interval'));
ravelInstance.once('end', () => {
clearInterval(redisKeepaliveInterval);
});
if (restrict) {
disable(client, 'quit');
disable(client, 'subscribe');
disable(client, 'psubscribe');
disable(client, 'unsubscribe');
disable(client, 'punsubscribe');
} else {
const origQuit = client.quit;
client.quit = function (...args) {
clearInterval(redisKeepaliveInterval);
return origQuit.apply(client, args);
};
}
client.clone = function () {
return createClient(ravelInstance, false);
};
return client;
} | javascript | {
"resource": ""
} |
q419 | BpmnQuestionnaire | train | function BpmnQuestionnaire(options) {
// Check if options was provided
if (!options) {
throw new Error('No options provided');
}
if (has(options, 'questionnaireJson')) {
this.questionnaireJson = options.questionnaireJson;
} else {
// Report error
throw new Error('No questionnaire specified');
}
// Events
this.events = new EventEmitter();
// Services
this.services = {
translator: (function(){
var translator;
if(has(options, 'plugins.translator')) {
// translator = new Translator(options.plugins.translator)
translator = new Translator(options.plugins.translator);
} else {
translator = new Translator();
}
return translator.translate.bind(translator);
}())
}
// Check if types were provided
if (options.types) {
this.types = options.types;
}
// Check if questions were provided
if (this.questionnaireJson.questions.length) {
this.questions = [];
var that = this;
// Create questions
this.questionnaireJson.questions.forEach(function(question, index) {
// Check if type of question was provided
if (!typeof that.types[question.type] === 'function') {
// Report error
throw new Error('Type not specified');
} else {
// Add instance of question to array of questions
that.questions.push(
new that.types[question.type](index, question, that)
);
}
});
} else {
// Report error
throw new Error('No questions specified');
}
// Initial state is immutable
this.initState = Immutable({
currentQuestion: 0,
progress: 0,
view: 'intro'
});
// Set state to mutable copy of initial state
this.state = this.initState.asMutable({deep: true});
// Set up loop
this.loop = mainLoop(this.state, this.render.bind(this), {
create: require("virtual-dom/create-element"),
diff: require("virtual-dom/diff"),
patch: require("virtual-dom/patch")
});
// Check if container element was specified
if (!options.container) {
throw new Error('No container element specified');
}
// Append questionnaire to container element
if (typeof options.container === 'string') {
// Search for element with given ID
var container = document.getElementById(options.container);
// Error handling
if (!container) {
throw new Error('Container element not found');
}
this.container = container;
} else if (options.container.appendChild) {
// Append questionnaire
this.container = options.container;
} else {
throw new Error('Container element not found');
}
// Append questionnaire
this.container.appendChild(this.loop.target);
} | javascript | {
"resource": ""
} |
q420 | train | function (index, options, questionnaire) {
this.index = index;
this.options = options;
this.questionnaire = questionnaire;
if (options.diagram) {
this.diagram = new Diagram(index, options.diagram, this);
}
// Initial state is immutable
this.initState = Immutable({
validAnswer: false,
rightAnswer: false,
view: 'question'
});
// Prevent overwriting default properties of state and assign provided properties to initial state
if (has(spec, 'addToState')) {
if(!has(spec.addToState, 'validAnswer')
&& !has(spec.addToState, 'rightAnswer')
&& !has(spec.addToState, 'view')) {
// Merge immutable with object
this.initState = this.initState.merge(spec.addToState);
}
}
// Set state to mutable copy of initial state
this.state = this.initState.asMutable({deep: true});
} | javascript | {
"resource": ""
} |
|
q421 | parseString | train | function parseString(xml, cb) {
return fastxml2js.parseString(xml, function(err, data) {
//So that it's asynchronous
process.nextTick(function() {
cb(err, data);
});
});
} | javascript | {
"resource": ""
} |
q422 | _callIfFn | train | function _callIfFn(thing, context, properties) {
return _.isFunction(thing) ? thing(context, properties) : thing;
} | javascript | {
"resource": ""
} |
q423 | servicesRunning | train | function servicesRunning() {
var composeArgs = ['ps'];
// If we're tailing just the main service's logs, then we only check that service
if (service === '<%= dockerCompose.options.mainService %>') {
composeArgs.push(grunt.config.get('dockerCompose.options.mainService'));
}
// get the stdout of docker-compose ps, store as Array, and drop the header lines.
var serviceList = spawn('docker-compose', composeArgs).stdout.toString().split('\n').slice(2),
upCount = 0;
// if we are left with 1 line or less, then nothing is running.
if (serviceList.length <= 1) {
return false;
}
function isUp(service) {
if (service.indexOf('Up') > 0) {
upCount++;
}
}
serviceList.forEach(isUp);
return upCount > 0;
} | javascript | {
"resource": ""
} |
q424 | _define | train | function _define(/* <exports>, name, dependencies, factory */) {
var
// extract arguments
argv = arguments,
argc = argv.length,
// extract arguments from function call - (exports?, name?, modules?, factory)
exports = argv[argc - 4] || {},
name = argv[argc - 3] || Math.floor(new Date().getTime() * (Math.random())), // if name is undefined or falsy value we add some timestamp like to name.
dependencies = argv[argc - 2] || [],
factory = argv[argc - 1],
// helper variables
params = [],
dependencies_satisfied = true,
dependency_name,
result,
config_dependencies_iterator = 0,
dependencies_iterator = 0,
config_dependencies_index = -1;
if (DEVELOPMENT) {
_set_debug_timer();
}
// config dependecies
if (_define.prototype.config_dependencies && _define.prototype.config_dependencies.constructor === Array) {
var config_dependencies = _define.prototype.config_dependencies || [];
var config_dependencies_size = config_dependencies.length;
for (; config_dependencies_iterator < config_dependencies_size; config_dependencies_iterator++) {
if (name === config_dependencies[config_dependencies_iterator]) {
config_dependencies_index = config_dependencies_iterator;
}
}
if (config_dependencies_index !== -1) {
config_dependencies.splice(config_dependencies_index, 1)
} else {
dependencies = dependencies.concat(config_dependencies);
}
}
// find params
for (; dependencies_iterator < dependencies.length; dependencies_iterator++) {
dependency_name = dependencies[dependencies_iterator];
// if this dependency exists, push it to param injection
if (modules.hasOwnProperty(dependency_name)) {
params.push(modules[dependency_name]);
} else if (dependency_name === 'exports') {
params.push(exports);
} else {
if (argc !== 4) { // if 4 values, is reexecuting
// no module found. save these arguments for future execution.
define_queue[dependency_name] = define_queue[dependency_name] || [];
define_queue[dependency_name].push([exports, name, dependencies, factory]);
}
dependencies_satisfied = false;
}
}
// all dependencies are satisfied, so proceed
if (dependencies_satisfied) {
if (!modules.hasOwnProperty(name)) {
// execute this module
result = factory.apply(this, params);
if (result) {
modules[name] = result;
} else {
// assuming result is in exports object
modules[name] = exports;
}
}
// execute others waiting for this module
while (define_queue[name] && (argv = define_queue[name].pop())) {
_define.apply(this, argv);
}
}
} | javascript | {
"resource": ""
} |
q425 | matches | train | function matches(node, selector) {
var parent, matches, i;
if (node.matches) {
return node.matches(selector);
} else {
parent = node.parentElement;
matches = parent ? parent.querySelectorAll(selector) : [];
i = 0;
while (matches[i] && matches[i] !== node) {
i++;
}
return !!matches[i];
}
} | javascript | {
"resource": ""
} |
q426 | closest | train | function closest(node, parentSelector) {
var cursor = node;
if (!parentSelector || typeof parentSelector !== 'string') {
throw new Error('Please specify a selector to match against!');
}
while (cursor && !matches(cursor, parentSelector)) {
cursor = cursor.parentNode;
}
if (!cursor) {
return null;
} else {
return cursor;
}
} | javascript | {
"resource": ""
} |
q427 | wrapElements | train | function wrapElements(els, wrapper) {
var wrapperEl = document.createElement(wrapper);
// make sure elements are in an array
if (els instanceof HTMLElement) {
els = [els];
} else {
els = Array.prototype.slice.call(els);
}
_each(els, function (el) {
// put it into the wrapper, remove it from its parent
el.parentNode.removeChild(el);
wrapperEl.appendChild(el);
});
// return the wrapped elements
return wrapperEl;
} | javascript | {
"resource": ""
} |
q428 | unwrapElements | train | function unwrapElements(parent, wrapper) {
var el = wrapper.childNodes[0];
// ok, so this looks weird, right?
// turns out, appending nodes to another node will remove them
// from the live NodeList, so we can keep iterating over the
// first item in that list and grab all of them. Nice!
while (el) {
parent.appendChild(el);
el = wrapper.childNodes[0];
}
parent.removeChild(wrapper);
} | javascript | {
"resource": ""
} |
q429 | createRemoveNodeHandler | train | function createRemoveNodeHandler(el, fn) {
return function (mutations, observer) {
mutations.forEach(function (mutation) {
if (_includes(mutation.removedNodes, el)) {
fn();
observer.disconnect();
}
});
};
} | javascript | {
"resource": ""
} |
q430 | getPos | train | function getPos(el) {
var rect = el.getBoundingClientRect(),
scrollY = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
return {
top: rect.top + scrollY,
bottom: rect.top + rect.height + scrollY,
height: rect.height
};
} | javascript | {
"resource": ""
} |
q431 | train | function(tokenService, domainPrefix) {
var tokenUrl = tokenService.replace(/\{DOMAIN_PREFIX\}/, domainPrefix);
log.debug('token Url: '+ tokenUrl);
return tokenUrl;
} | javascript | {
"resource": ""
} |
|
q432 | AdapterFactory | train | function AdapterFactory(injector) {
if (!injector.adapters) { return; }
var me = this;
this.adapterMap = {};
_.each(injector.adapterMap, function (adapterName, adapterType) {
var adapter = injector.adapters[adapterName];
if (adapter) {
me.adapterMap[adapterType + 'adapter'] = adapter;
}
});
} | javascript | {
"resource": ""
} |
q433 | getCamelCase | train | function getCamelCase(filePath) {
if (!filePath) {
return '';
}
// clip off everything by after the last slash and the .js
filePath = filePath.substring(filePath.lastIndexOf(delim) + 1);
if (filePath.substring(filePath.length - 3) === '.js') {
filePath = filePath.substring(0, filePath.length - 3);
}
// replace dots with caps
var parts = filePath.split('.');
var i;
for (i = 1; i < parts.length; i++) {
parts[i] = parts[i].substring(0, 1).toUpperCase() +
parts[i].substring(1);
}
// replace dashs with caps
filePath = parts.join('');
parts = filePath.split('-');
for (i = 1; i < parts.length; i++) {
parts[i] = parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1);
}
return parts.join('');
} | javascript | {
"resource": ""
} |
q434 | getPascalCase | train | function getPascalCase(filePath) {
var camelCase = getCamelCase(filePath);
return camelCase.substring(0, 1).toUpperCase() + camelCase.substring(1);
} | javascript | {
"resource": ""
} |
q435 | getModulePath | train | function getModulePath(filePath, fileName) {
if (isJavaScript(fileName)) {
fileName = fileName.substring(0, fileName.length - 3);
}
return filePath + '/' + fileName;
} | javascript | {
"resource": ""
} |
q436 | parseIfJson | train | function parseIfJson(val) {
if (_.isString(val)) {
val = val.trim();
if (val.substring(0, 1) === '{' && val.substring(val.length - 1) === '}') {
try {
val = JSON.parse(val);
}
catch (ex) {
/* eslint no-console:0 */
console.log(ex);
}
}
}
return val;
} | javascript | {
"resource": ""
} |
q437 | chainPromises | train | function chainPromises(calls, val) {
if (!calls || !calls.length) { return Q.when(val); }
return calls.reduce(Q.when, Q.when(val));
} | javascript | {
"resource": ""
} |
q438 | checksum | train | function checksum(str) {
crcTbl = crcTbl || makeCRCTable();
/* jslint bitwise: true */
var crc = 0 ^ (-1);
for (var i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTbl[(crc ^ str.charCodeAt(i)) & 0xFF];
}
return (crc ^ (-1)) >>> 0;
} | javascript | {
"resource": ""
} |
q439 | DependencyInjector | train | function DependencyInjector(opts) {
var rootDefault = p.join(__dirname, '../../..');
this.rootDir = opts.rootDir || rootDefault; // project base dir (default is a guess)
this.require = opts.require || require; // we need require from the project
this.container = opts.container || 'api'; // resource has diff profiles for diff containers
this.servicesDir = opts.servicesDir || 'services'; // dir where services reside
this.tplDir = opts.tplDir || 'dist/tpls'; // precompiled templates
this.debug = opts.debug || false; // debug mode will have us firing more events
this.debugPattern = opts.debugPattern; // by default if debug on, we view EVERYTHING
this.debugHandler = opts.debugHandler; // function used when debug event occurs
this.adapters = opts.adapters || {}; // if client uses plugins, they will pass in adapters
this.reactors = opts.reactors || {}; // if client uses plugins, they will pass in reactors
this.adapterMap = this.loadAdapterMap(opts); // mappings from adapter type to impl
this.aliases = this.loadAliases(opts); // mapping of names to locations
this.factories = this.loadFactories(opts); // load all the factories
} | javascript | {
"resource": ""
} |
q440 | loadFactories | train | function loadFactories(opts) {
this.flapjackFactory = new FlapjackFactory(this);
return [
new InternalObjFactory(this),
new AdapterFactory(this),
new ServiceFactory(this),
new ModelFactory(this),
new UipartFactory(this),
this.flapjackFactory,
new ModulePluginFactory(this, opts.modulePlugins),
new DefaultFactory(this)
];
} | javascript | {
"resource": ""
} |
q441 | loadMappings | train | function loadMappings(rootDir, paths) {
var mappings = {}, i, j, fullPath, fileNames, fileName, path, name, val;
if (!paths) {
return mappings;
}
for (i = 0; i < paths.length; i++) {
path = paths[i];
fullPath = rootDir + '/' + path;
// if the directory doesn't exist, then skip to the next loop iteration
if (!fs.existsSync(p.normalize(fullPath))) {
continue;
}
// loop through all files in this folder
fileNames = fs.readdirSync(p.normalize(fullPath));
for (j = 0; j < fileNames.length; j++) {
fileName = fileNames[j];
// if it is a javascript file and it DOES NOT end in .service.js, then save the mapping
if (utils.isJavaScript(fileName) && !fileName.match(/^.*\.service\.js$/)) {
name = utils.getCamelCase(fileName);
val = utils.getModulePath(path, fileName);
mappings[name] = val;
mappings[name.substring(0, 1).toUpperCase() + name.substring(1)] = val; // store PascalCase as well
}
// else if we are dealing with a directory, recurse down into the folder
else if (fs.lstatSync(p.join(fullPath, fileName)).isDirectory()) {
_.extend(mappings, this.loadMappings(rootDir, [path + '/' + fileName]));
}
}
}
return mappings;
} | javascript | {
"resource": ""
} |
q442 | exists | train | function exists(modulePath, options) {
if (this.aliases[modulePath]) {
modulePath = this.aliases[modulePath];
}
var len = this.factories.length - 1; // -1 because we don't want the default factory
for (var i = 0; this.factories && i < len; i++) {
if (this.factories[i].isCandidate(modulePath, options)) {
return true;
}
}
return false;
} | javascript | {
"resource": ""
} |
q443 | loadModule | train | function loadModule(modulePath, moduleStack, options) {
var newModule, i;
options = options || {};
// if modulePath is null return null
if (!modulePath) {
return null;
}
// if actual flapjack sent in as the module path then switch things around so modulePath name is unique
if (_.isFunction(modulePath)) {
options.flapjack = modulePath;
modulePath = 'module-' + (new Date()).getTime();
}
// if we already have a flapjack, make the modulePath unique per the options
else if (options.flapjack) {
modulePath = (options.app || 'common') + '.' + modulePath + '.' + (options.type || 'default');
}
// else we need to get code from the file system, so check to see if we need to switch a mapped name to its path
else if (this.aliases[modulePath]) {
modulePath = this.aliases[modulePath];
}
// if module name already in the stack, then circular reference
moduleStack = moduleStack || [];
if (moduleStack.indexOf(modulePath) >= 0) {
throw new Error('Circular reference since ' + modulePath + ' is in ' + JSON.stringify(moduleStack));
}
// add the path to the stack so we don't have a circular dependency
moduleStack.push(modulePath);
// try to find a factory that can create/get a module for the given path
for (i = 0; this.factories && i < this.factories.length; i++) {
if (this.factories[i].isCandidate(modulePath, options)) {
newModule = this.factories[i].create(modulePath, moduleStack, options);
break;
}
}
// if no module found log error
if (!newModule && moduleStack && moduleStack.length > 1) {
/* eslint no-console:0 */
console.log('ERROR: ' + moduleStack[moduleStack.length - 2] + ' dependency ' + modulePath + ' not found.');
}
// pop the current item off the stack
moduleStack.pop();
// return the new module (or the default {} if no factories found)
return newModule;
} | javascript | {
"resource": ""
} |
q444 | injectFlapjack | train | function injectFlapjack(flapjack, moduleStack, options) {
options = options || {};
// if server is false, then return null
var moduleInfo = annotations.getModuleInfo(flapjack);
if (moduleInfo && moduleInfo.server === false && !options.test) {
return null;
}
// param map is combo of param map set by user, params discovered and current annotation
var aliases = _.extend({}, this.aliases, annotations.getServerAliases(flapjack, null));
var params = annotations.getParameters(flapjack);
var deps = options.dependencies || {};
var paramModules = [];
var me = this;
// loop through the params so we can collect the object that will be injected
_.each(params, function (param) {
var dep = deps[param];
// if mapping exists, switch to the mapping (ex. pancakes -> lib/pancakes)
if (aliases[param]) {
param = aliases[param];
}
// either get the module from the input dependencies or recursively call inject
try {
paramModules.push(dep || deps[param] || me.loadModule(param, moduleStack));
}
catch (ex) {
var errMsg = ex.stack || ex;
throw new Error('While injecting function, ran into invalid parameter.\nparam: ' + param +
'\nstack: ' + JSON.stringify(moduleStack) + '\nfunction: ' +
flapjack.toString().substring(0, 100) + '...\nerror: ' + errMsg);
}
});
// call the flapjack function passing in the array of modules as parameters
return flapjack.apply(null, paramModules);
} | javascript | {
"resource": ""
} |
q445 | loadModulePlugins | train | function loadModulePlugins(modulePlugins) {
var serverModules = {};
var me = this;
// add modules from each plugin to the serverModules map
_.each(modulePlugins, function (modulePlugin) {
_.extend(serverModules, me.loadModules(modulePlugin.rootDir, modulePlugin.serverModuleDirs));
});
return serverModules;
} | javascript | {
"resource": ""
} |
q446 | loadModules | train | function loadModules(rootDir, paths) {
var serverModules = {};
var me = this;
// return empty object if no rootDir or paths
if (!rootDir || !paths) { return serverModules; }
// loop through paths and load all modules in those directories
_.each(paths, function (relativePath) {
var fullPath = path.normalize(rootDir + delim + relativePath);
// if the directory doesn't exist, then skip to the next loop iteration
if (fs.existsSync(fullPath)) {
_.each(fs.readdirSync(fullPath), function (fileName) {
// if it is a javascript file and it DOES NOT end in .service.js, then save the mapping
if (utils.isJavaScript(fileName) && !fileName.match(/^.*\.service\.js$/)) {
var nameLower = utils.getCamelCase(fileName).toLowerCase();
var fullFilePath = path.normalize(fullPath + '/' + fileName);
// there are 2 diff potential aliases for any given server module
serverModules[nameLower + 'fromplugin'] = serverModules[nameLower] = require(fullFilePath);
}
// else if we are dealing with a directory, recurse down into the folder
else if (fs.lstatSync(path.join(fullPath, fileName)).isDirectory()) {
_.extend(serverModules, me.loadModules(rootDir, [relativePath + '/' + fileName]));
}
});
}
});
return serverModules;
} | javascript | {
"resource": ""
} |
q447 | traverseFilters | train | function traverseFilters(config, levels, levelIdx) {
var lastIdx = levels.length - 1;
var val, filters;
if (!config || levelIdx > lastIdx) { return null; }
val = config[levels[levelIdx]];
if (levelIdx === lastIdx) {
if (val) {
return val;
}
else {
return config.all;
}
}
else {
filters = traverseFilters(val, levels, levelIdx + 1);
if (!filters) {
filters = traverseFilters(config.all, levels, levelIdx + 1);
}
return filters;
}
} | javascript | {
"resource": ""
} |
q448 | getFilters | train | function getFilters(resourceName, adapterName, operation) {
var filterConfig = injector.loadModule('filterConfig');
var filters = { before: [], after: [] };
if (!filterConfig) { return filters; }
var levels = [resourceName, adapterName, operation, 'before'];
filters.before = (traverseFilters(filterConfig, levels, 0) || []).map(function (name) {
return injector.loadModule(name + 'Filter');
});
levels = [resourceName, adapterName, operation, 'after'];
filters.after = (traverseFilters(filterConfig, levels, 0) || []).map(function (name) {
return injector.loadModule(name + 'Filter');
});
return filters;
} | javascript | {
"resource": ""
} |
q449 | processApiCall | train | function processApiCall(resource, operation, requestParams) {
var service = injector.loadModule(utensils.getCamelCase(resource.name + '.service'));
var adapterName = resource.adapters.api;
// remove the keys that start with onBehalfOf
_.each(requestParams, function (val, key) {
if (key.indexOf('onBehalfOf') === 0) { delete requestParams[key]; }
});
// hack fix for when _id not filled in
if (requestParams._id === '{_id}') {
delete requestParams._id;
}
// loop through request values and parse json
for (var key in requestParams) {
if (requestParams.hasOwnProperty(key)) {
requestParams[key] = utensils.parseIfJson(requestParams[key]);
}
}
var filters = getFilters(resource.name, adapterName, operation);
return utensils.chainPromises(filters.before, requestParams)
.then(function (filteredRequest) {
requestParams = filteredRequest;
return service[operation](requestParams);
})
.then(function (data) {
return utensils.chainPromises(filters.after, {
caller: requestParams.caller,
lang: requestParams.lang,
resource: resource,
inputData: requestParams.data,
data: data
});
});
} | javascript | {
"resource": ""
} |
q450 | loadInlineCss | train | function loadInlineCss(rootDir, apps) {
_.each(apps, function (app, appName) {
_.each(app.routes, function (route) {
var filePath = rootDir + '/app/' + appName + '/inline/' + route.name + '.css';
if (route.inline && fs.existsSync(filePath)) {
inlineCssCache[appName + '||' + route.name] = fs.readFileSync(filePath, { encoding: 'utf8' });
}
});
});
} | javascript | {
"resource": ""
} |
q451 | convertUrlSegmentToRegex | train | function convertUrlSegmentToRegex(segment) {
// if it has this format "{stuff}" - then it's regex-y
var beginIdx = segment.indexOf('{');
var endIdx = segment.indexOf('}');
if (beginIdx < 0) {
return segment;
}
// if capturing regex and trim trailing "}"
// this could be a named regex {id:[0-9]+} or just name {companySlug}
var pieces = segment.split(':');
if (pieces.length === 2) {
if ( pieces[1] === (urlPathPatternSymbol + '}') ) {
// special case where we want to capture the whole remaining path, even slashes, like /search/a/b/c/
return urlPathPattern;
}
else {
return '(' + pieces[1].substring(0, pieces[1].length - 1) + ')';
}
}
else if (pieces.length === 1) {
return segment.substring(0, beginIdx) + '[^\\/]+' + segment.substring(endIdx + 1);
}
else {
throw new Error('Weird URL segment- don\'t know how to parse! ' + segment);
}
} | javascript | {
"resource": ""
} |
q452 | getTokenValuesFromUrl | train | function getTokenValuesFromUrl(pattern, url) {
var tokenValues = {},
urlSegments = url.split('/');
pattern.split('/').forEach(function (segment, idx) {
// this has this form {stuff}, so let's dig
var beginIdx = segment.indexOf('{');
var endIdx = segment.indexOf('}');
var endLen = segment.length - endIdx - 1;
var urlSegment = urlSegments[idx];
if (beginIdx > -1) {
// peel off the { and } at the ends
segment = segment.substring(beginIdx + 1, endIdx);
var pieces = segment.split(':');
if (pieces.length === 2 && pieces[1] === urlPathPatternSymbol ) {
var vals = [urlSegment.substring(beginIdx, urlSegment.length - endLen)];
for ( var i = idx + 1, len = urlSegments.length; i < len; i++ ) {
vals.push(urlSegments[i]);
}
tokenValues[pieces[0]] = vals.join('%20'); // join any remaining segments with a space
}
else if (pieces.length === 2 || pieces.length === 1) {
tokenValues[pieces[0]] = urlSegment.substring(beginIdx, urlSegment.length - endLen);
}
} // else no token to grab
});
return tokenValues;
} | javascript | {
"resource": ""
} |
q453 | getRouteInfo | train | function getRouteInfo(appName, urlRequest, query, lang, user, referrer) {
var activeUser = user ? {
_id: user._id,
name: user.username,
role: user.role,
user: user
} : {};
// if route info already in cache, return it
var cacheKey = appName + '||' + lang + '||' + urlRequest;
var cachedRouteInfo = routeInfoCache[cacheKey];
if (!user && cachedRouteInfo) {
cachedRouteInfo.query = query; // query shouldn't be cached
return cachedRouteInfo;
}
// if urlRequest ends in .html it is an amp request so treat it as such
var isAmp = /\.html$/.test(urlRequest);
if (isAmp) {
urlRequest = urlRequest.substring(0, urlRequest.length - 5);
}
// get the routes and then find the info that matches the current URL
var url = urlRequest.toLowerCase();
var i, route, routeInfo;
var routes = getRoutes(appName);
if (routes) {
// loop through routes trying to find the one that matches
for (i = 0; i < routes.length; i++) {
route = routes[i];
// if there is a match, save the info to cache and return it
if (route.urlRegex.test(url)) {
routeInfo = _.extend({
appName: appName,
referrer: referrer,
lang: lang,
url: urlRequest,
query: query,
activeUser: activeUser,
isAmp: isAmp,
tokens: getTokenValuesFromUrl(route.urlPattern, urlRequest)
}, route);
// change layout wrapper to amp if request is for amp
if (isAmp) {
routeInfo.wrapper = 'amp';
}
// if no user, then save request in cache
if (!user) {
routeInfoCache[cacheKey] = routeInfo;
}
return routeInfo;
}
}
}
// if we get here, then no route found, so throw 404 error
throw new Error('404: ' + appName + ' ' + urlRequest + ' is not a valid request');
} | javascript | {
"resource": ""
} |
q454 | setDefaults | train | function setDefaults(model, defaults) {
if (!defaults) { return; }
_.each(defaults, function (value, key) {
if (model[key] === undefined) {
model[key] = value;
}
});
} | javascript | {
"resource": ""
} |
q455 | getInitialModel | train | function getInitialModel(routeInfo, page) {
var initModelDeps = {
appName: routeInfo.appName,
tokens: routeInfo.tokens,
routeInfo: routeInfo,
defaults: page.defaults,
activeUser: routeInfo.activeUser || {},
currentScope: {}
};
// if no model, just return empty object
if (!page.model) {
return Q.when({});
}
// if function, inject and the returned value is the model
else if (_.isFunction(page.model)) {
return Q.when(injector.loadModule(page.model, null, { dependencies: initModelDeps }));
}
else {
throw new Error(routeInfo.name + ' page invalid model() format: ' + page.model);
}
} | javascript | {
"resource": ""
} |
q456 | processWebRequest | train | function processWebRequest(routeInfo, callbacks) {
var appName = routeInfo.appName;
var serverOnly = !!routeInfo.query.server;
var page = injector.loadModule('app/' + appName + '/pages/' + routeInfo.name + '.page');
// get the callbacks
var serverPreprocessing = callbacks.serverPreprocessing || function () { return false; };
var appAddToModel = callbacks.addToModel || function () {};
var pageCacheService = callbacks.pageCacheService || defaultPageCache;
var initialModel, cacheKey;
return getInitialModel(routeInfo, page)
.then(function (model) {
initialModel = model || {};
// if the server pre-processing returns true, then return without doing anything
// this is because the pre-processor sent a reply to the user already
if (serverPreprocessing(routeInfo, page, model)) {
return true;
}
//TODO: may be weird edge cases with this. need to test more to ensure performance and uniqueness
// but note that we have an hour default timeout for the redis cache just in case
// and we have the redis LRU config set up so the least recently used will get pushed out
cacheKey = utensils.checksum(routeInfo.lang + '||' + routeInfo.appName + '||' +
routeInfo.url + '||' + JSON.stringify(model));
return pageCacheService.get({ key: cacheKey });
})
.then(function (cachedPage) {
if (cachedPage === true) { return null; }
if (cachedPage && !serverOnly) { return cachedPage; }
// allow the app level to modify the model before rendering
appAddToModel(initialModel, routeInfo);
// finally use the client side plugin to do the rendering
return clientPlugin.renderPage(routeInfo, page, initialModel, inlineCssCache[appName + '||' + routeInfo.name]);
})
.then(function (renderedPage) {
if (!serverOnly && renderedPage) {
pageCacheService.set({ key: cacheKey, value: renderedPage });
}
return renderedPage;
});
} | javascript | {
"resource": ""
} |
q457 | generateTransformer | train | function generateTransformer(name, transformerFns, templateDir, pluginOptions) {
var Transformer = function () {};
var transformer = new Transformer();
// add function mixins to the transformer
_.extend(transformer, transformerFns, baseTransformer, annotationHelper, utensils, pluginOptions);
// add reference to the template function
transformer.setTemplate(templateDir, name, pluginOptions.clientType);
// each transformer can reference each other
transformer.transformers = cache;
// return the transformer
return transformer;
} | javascript | {
"resource": ""
} |
q458 | getTransformer | train | function getTransformer(name, clientPlugin, pluginOptions) {
// if in cache, just return it
if (cache[name]) { return cache[name]; }
var transformers = clientPlugin.transformers;
var templateDir = clientPlugin.templateDir;
// if no transformer, throw error
if (!transformers[name]) { throw new Error('No transformer called ' + name); }
// generate all the transformers
_.each(transformers, function (transformer, transformerName) {
cache[transformerName] = generateTransformer(transformerName, transformer, templateDir, pluginOptions);
});
// return the specific one that was requested
return cache[name];
} | javascript | {
"resource": ""
} |
q459 | init | train | function init(opts) {
opts = opts || {};
// include pancakes instance into options that we pass to plugins
opts.pluginOptions = opts.pluginOptions || {};
opts.pluginOptions.pancakes = exports;
injector = new DependencyInjector(opts);
var ClientPlugin = opts.clientPlugin;
var ServerPlugin = opts.serverPlugin;
if (ClientPlugin) { clientPlugin = new ClientPlugin(opts); }
if (ServerPlugin) { serverPlugin = new ServerPlugin(opts); }
apiRouteHandler.init({ injector: injector });
webRouteHandler.init({ injector: injector, clientPlugin: clientPlugin, rootDir: opts.rootDir });
} | javascript | {
"resource": ""
} |
q460 | initContainer | train | function initContainer(opts) {
var apps, appDir;
container = opts.container;
// if batch, preload that dir
container === 'batch' ?
opts.preload.push('batch') :
opts.preload.push('middleware');
if (container === 'webserver') {
appDir = path.join(opts.rootDir, '/app');
apps = fs.readdirSync(appDir);
_.each(apps, function (app) {
opts.preload = opts.preload.concat([
'app/' + app + '/filters',
'app/' + app + '/utils'
]);
});
}
init(opts);
} | javascript | {
"resource": ""
} |
q461 | requireModule | train | function requireModule(filePath, refreshFlag) {
if (refreshFlag) {
delete injector.require.cache[filePath];
}
return injector.require(filePath);
} | javascript | {
"resource": ""
} |
q462 | getService | train | function getService(name) {
if (name.indexOf('.') >= 0) {
name = utils.getCamelCase(name);
}
if (!name.match(/^.*Service$/)) {
name += 'Service';
}
return cook(name);
} | javascript | {
"resource": ""
} |
q463 | transform | train | function transform(flapjack, pluginOptions, runtimeOptions) {
var name = runtimeOptions.transformer;
var transformer = transformerFactory.getTransformer(name, clientPlugin, pluginOptions);
var options = _.extend({}, pluginOptions, runtimeOptions);
return transformer.transform(flapjack, options);
} | javascript | {
"resource": ""
} |
q464 | train | function(e) {
var tooltip = this.$(".ui-tooltip-top");
var val = this.input.val();
tooltip.fadeOut();
if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout);
if (val == '' || val == this.input.attr('placeholder')) return;
var show = function(){ tooltip.show().fadeIn(); };
this.tooltipTimeout = _.delay(show, 1000);
} | javascript | {
"resource": ""
} |
|
q465 | getUiPart | train | function getUiPart(modulePath, options) {
var rootDir = this.injector.rootDir;
var tplDir = (options && options.tplDir) || 'dist' + delim + 'tpls';
var pathParts = modulePath.split(delim);
var appName = pathParts[1];
var len = modulePath.length;
var filePath, fullModulePath, uipart, viewObj;
// filePath has .js, modulePath does not
if (modulePath.substring(len - 3) === '.js') {
filePath = rootDir + delim + modulePath;
fullModulePath = rootDir + delim + modulePath.substring(0, len - 3);
}
else {
filePath = rootDir + delim + modulePath + '.js';
fullModulePath = rootDir + delim + modulePath;
}
// if exists, get it
if (fs.existsSync(filePath)) {
uipart = this.injector.require(fullModulePath);
}
// else if in an app folder, try the common folder
else if (appName !== 'common') {
fullModulePath = fullModulePath.replace(delim + appName + delim, delim + 'common' + delim);
uipart = this.injector.require(fullModulePath);
appName = 'common';
}
// if no view, check to see if precompiled in tpl dir
var viewFile = fullModulePath.replace(
delim + 'app' + delim + appName + delim,
delim + tplDir + delim + appName + delim
);
if (!uipart.view && fs.existsSync(viewFile + '.js')) {
viewObj = this.injector.require(viewFile);
uipart.view = function () {
return viewObj;
};
}
return uipart;
} | javascript | {
"resource": ""
} |
q466 | ServiceFactory | train | function ServiceFactory(injector) {
this.cache = {};
this.injector = injector || {};
// if we are in debug mode, then add the debug handler
var pattern = this.injector.debugPattern || '*.*.*.*.*';
var handler = this.injector.debugHandler || debugHandler;
if (this.injector.debug) {
eventBus.on(pattern, handler);
}
} | javascript | {
"resource": ""
} |
q467 | isCandidate | train | function isCandidate(modulePath) {
modulePath = modulePath || '';
var len = modulePath.length;
return modulePath.indexOf('/') < 0 && len > 7 &&
modulePath.substring(modulePath.length - 7) === 'Service';
} | javascript | {
"resource": ""
} |
q468 | getServiceInfo | train | function getServiceInfo(serviceName, adapterMap) {
var serviceInfo = { serviceName: serviceName };
var serviceParts = utils.splitCamelCase(serviceName); // turn oneTwoThree into ['one', 'two', 'three']
var nbrParts = serviceParts.length;
// first check to see if the second to last part is an adapter
serviceInfo.adapterName = serviceParts[nbrParts - 2]; // NOTE: last item in array is 'Service'
if (adapterMap[serviceInfo.adapterName]) {
serviceInfo.resourceName = serviceParts.slice(0, nbrParts - 2).join('.');
}
// if not, it means we are dealing with a straight service (ex. postService)
else {
serviceInfo.adapterName = 'service';
serviceInfo.resourceName = serviceParts.slice(0, nbrParts - 1).join('.');
}
serviceInfo.adapterImpl = adapterMap[serviceInfo.adapterName];
return serviceInfo;
} | javascript | {
"resource": ""
} |
q469 | getResource | train | function getResource(serviceInfo, moduleStack) {
var resourceName = serviceInfo.resourceName;
var resourcePath = '/resources/' + resourceName + '/' + resourceName + '.resource';
return this.loadIfExists(resourcePath, moduleStack, 'Could not find resource file');
} | javascript | {
"resource": ""
} |
q470 | getAdapter | train | function getAdapter(serviceInfo, resource, moduleStack) {
var adapterName = serviceInfo.adapterName;
// if adapter name is 'service' and there is a default, switch to the default
if (adapterName === 'service' && resource.adapters[this.injector.container]) {
adapterName = serviceInfo.adapterName = resource.adapters[this.injector.container];
serviceInfo.adapterImpl = this.injector.adapterMap[adapterName];
serviceInfo.serviceName = utils.getCamelCase(serviceInfo.resourceName + '.' +
serviceInfo.adapterName + '.service');
}
// if that doesn't work, we will assume the adapter is in the current codebase, so go get it
var overridePath = '/resources/' + serviceInfo.resourceName + '/' + serviceInfo.resourceName + '.' +
(adapterName === 'service' ? adapterName : adapterName + '.service');
var adapterPath = '/adapters/' + adapterName + '/' +
serviceInfo.adapterImpl + '.' + adapterName + '.adapter';
// if override exists, use that one, else use the lower level adapter
var Adapter =
this.loadIfExists(overridePath, moduleStack, null) ||
this.injector.adapters[serviceInfo.adapterImpl] ||
this.loadIfExists(adapterPath, moduleStack, null);
// if still no adapter found, then there is an issue
if (!Adapter) {
throw new Error('ServiceFactory could not find adapter ' + adapterName +
' paths ' + overridePath + ' and ' + adapterPath);
}
return new Adapter(resource);
} | javascript | {
"resource": ""
} |
q471 | loadIfExists | train | function loadIfExists(path, moduleStack, errMsg) {
var servicesDir = this.injector.servicesDir;
var servicesFullPath = this.injector.rootDir + '/' + servicesDir;
// if the file doesn't exist, either throw an error (if msg passed in), else just return null
if (!fs.existsSync(p.join(servicesFullPath, path + '.js'))) {
if (errMsg) {
throw new Error(errMsg + ' ' + servicesFullPath + path + '.js');
}
else {
return null;
}
}
// else load the module
return this.injector.loadModule(servicesDir + path, moduleStack);
} | javascript | {
"resource": ""
} |
q472 | putItAllTogether | train | function putItAllTogether(serviceInfo, resource, adapter) {
var me = this;
var debug = this.injector.debug;
// loop through the methods
_.each(resource.methods[serviceInfo.adapterName], function (method) {
if (!adapter[method]) {
return;
}
// we are going to monkey patch the target method on the adapter, so save the original method
var origMethod = adapter[method].bind(adapter);
var eventNameBase = {
resource: serviceInfo.resourceName,
adapter: serviceInfo.adapterName,
method: method
};
// create the new service function
adapter[method] = function (req) {
req = req || {};
// clean out request
_.each(req, function (value, name) {
if (value && value === 'undefined') {
delete req[name];
}
});
// add event for data before anything happens (used only for debugging)
if (debug) { me.emitEvent(req, eventNameBase, { type: 'service', timing: 'before' }); }
// first validate the request
return me.validateRequestParams(req, resource, method, serviceInfo.adapterName)
.then(function () {
// add event before calling the original method (used only for debugging)
if (debug) { me.emitEvent(req, eventNameBase, { type: 'service', timing: 'before' }); }
// call the original target method on the adapter
return origMethod(req);
})
.then(function (res) {
// emit event after origin method called; this is what most
// reactors key off of (can be disabled with noemit flag)
if (!req.noemit && !req.multi && method !== 'find') {
var payload = {
caller: req.caller,
inputId: req._id,
targetId: req.targetId,
inputData: req.data,
data: res
};
me.emitEvent(payload, eventNameBase, null);
}
// return the response that will go back to the calling client
return res;
});
};
});
// so essentially the service is the adapter with each method bulked up with some extra stuff
return adapter;
} | javascript | {
"resource": ""
} |
q473 | emitEvent | train | function emitEvent(payload, eventNameBase, debugParams) {
// create a copy of the payload so that nothing modifies the original object
try {
payload = JSON.parse(JSON.stringify(payload));
}
catch (err) {
/* eslint no-console:0 */
console.log('issue parsing during emit ' + JSON.stringify(eventNameBase));
}
// we don't want to emit the potentially huge resource file
if (payload && payload.resource) {
delete payload.resource;
}
// create the event data and emit the event
var name = _.extend({}, eventNameBase, debugParams);
var eventData = {
name: name,
payload: payload
};
var eventName = name.resource + '.' + name.adapter + '.' + name.method;
eventName += debugParams ? '.' + name.type + '.' + name.timing : '';
eventBus.emit(eventName, eventData);
} | javascript | {
"resource": ""
} |
q474 | validateRequestParams | train | function validateRequestParams(req, resource, method, adapter) {
req = req || {};
var params = resource.params || {};
var methodParams = _.extend({}, params[method], params[adapter + '.' + method] );
var requiredParams = methodParams.required || [];
var eitherorParams = methodParams.eitheror || [];
var optional = methodParams.optional || [];
var eitherorExists, param;
var err, reqObj;
// make sure all the required params are there
for (var i = 0; i < requiredParams.length; i++) {
param = requiredParams[i];
if (req[param] === undefined || req[param] === null) {
reqObj = _.extend({}, req);
delete reqObj.resource;
err = new Error('Invalid request');
err.code = 'invalid_request_error';
err.message = resource.name + ' ' + method + ' missing ' + param +
'. Required params: ' + JSON.stringify(requiredParams) +
' req is: ' + JSON.stringify(reqObj);
return Q.reject(err);
}
}
// make sure at least one of the eitheror params are there
if (eitherorParams.length) {
eitherorExists = false;
_.each(eitherorParams, function (eitherorParam) {
if (req[eitherorParam]) { eitherorExists = true; }
});
if (!eitherorExists) {
delete req.caller;
delete req.resource;
err = new Error('Invalid request');
err.code = 'invalid_request_error';
err.message = resource.name + ' ' + method +
' must have one of the following params: ' + JSON.stringify(eitherorParams) +
' request is ' + JSON.stringify(req);
return Q.reject(err);
}
}
// now loop through the values and error if invalid param in there; also do JSON parsing if an object
var validParams = requiredParams.concat(eitherorParams, optional,
['lang', 'caller', 'resource', 'method', 'auth', 'noemit']);
for (var key in req) {
if (req.hasOwnProperty(key)) {
if (validParams.indexOf(key) < 0) {
delete req.caller;
delete req.resource;
err = new Error('Invalid request');
err.code = 'invalid_request_error';
err.message = 'For ' + resource.name + ' ' + method + ' the key ' +
key + ' is not allowed. Valid params: ' + JSON.stringify(validParams) +
' request is ' + JSON.stringify(req);
return Q.reject(err);
}
}
}
// no errors, so return resolved promise
return new Q();
} | javascript | {
"resource": ""
} |
q475 | logWrap | train | function logWrap(level) {
return function log() {
let context, message, args, trace, err;
if (arguments[0] instanceof Error) {
// log.<level>(err, ...)
context = API.getContext();
args = Array.prototype.slice.call(arguments, 1);
if (!args.length) {
// log.<level>(err)
err = arguments[0];
message = err.name + ': ' + err.message;
} else {
// log.<level>(err, "More %s", "things")
// Use the err as context information
err = arguments[0];
message = arguments[1];
args = Array.prototype.slice.call(args, 1);
}
} else if (arguments[0] == null || (typeof (arguments[0]) !== 'object' && arguments[0] !== null) ||
Array.isArray(arguments[0])) {
// log.<level>(msg, ...)
context = API.getContext();
message = arguments[0];
args = Array.prototype.slice.call(arguments, 1);
} else {
// log.<level>(fields, msg, ...)
context = merge(API.getContext(), arguments[0]);
message = arguments[1];
args = Array.prototype.slice.call(arguments, 2);
}
trace = API.format(level, context || {}, message, args, err);
API.stream.write(trace + '\n');
};
} | javascript | {
"resource": ""
} |
q476 | setLevel | train | function setLevel(level) {
opts.level = level;
let logLevelIndex = levels.indexOf(opts.level.toUpperCase());
levels.forEach((logLevel) => {
let fn;
if (logLevelIndex <= levels.indexOf(logLevel)) {
fn = logWrap(logLevel);
} else {
fn = noop;
}
API[logLevel.toLowerCase()] = fn;
});
} | javascript | {
"resource": ""
} |
q477 | merge | train | function merge(obj1, obj2) {
var res = {}, attrname;
for (attrname in obj1) {
res[attrname] = obj1[attrname];
}
for (attrname in obj2) {
res[attrname] = obj2[attrname];
}
return res;
} | javascript | {
"resource": ""
} |
q478 | loadUIPart | train | function loadUIPart(appName, filePath) {
var idx = filePath.indexOf(delim + appName + delim);
var modulePath = filePath.substring(idx - 3);
return this.pancakes.cook(modulePath);
} | javascript | {
"resource": ""
} |
q479 | setTemplate | train | function setTemplate(transformDir, templateName, clientType) {
clientType = clientType ? (clientType + '.') : '';
if (templateCache[templateName]) {
this.template = templateCache[templateName];
}
else {
var fileName = transformDir + '/' + clientType + templateName + '.template';
if (fs.existsSync(path.normalize(fileName))) {
var file = fs.readFileSync(path.normalize(fileName));
this.template = templateCache[templateName] = dot.template(file);
}
else {
throw new Error('No template at ' + fileName);
}
}
} | javascript | {
"resource": ""
} |
q480 | getParamInfo | train | function getParamInfo(params, aliases) {
var paramInfo = { converted: [], list: [], ngrefs: [] };
_.each(params, function (param) {
var mappedVal = aliases[param] || param;
if (mappedVal === 'angular') {
paramInfo.ngrefs.push(param);
}
else {
paramInfo.list.push(param);
paramInfo.converted.push(mappedVal);
}
});
return paramInfo;
} | javascript | {
"resource": ""
} |
q481 | getFilteredParamInfo | train | function getFilteredParamInfo(flapjack, options) {
if (!flapjack) { return {}; }
var aliases = this.getClientAliases(flapjack, options);
var params = this.getParameters(flapjack) || [];
params = params.filter(function (param) {
return ['$scope', 'defaults', 'initialModel'].indexOf(param) < 0;
});
return this.getParamInfo(params, aliases) || {};
} | javascript | {
"resource": ""
} |
q482 | getModuleBody | train | function getModuleBody(flapjack) {
if (!flapjack) { return ''; }
var str = flapjack.toString();
var openingCurly = str.indexOf('{');
var closingCurly = str.lastIndexOf('}');
// if can't find the opening or closing curly, just return the entire string
if (openingCurly < 0 || closingCurly < 0) {
return str;
}
var body = str.substring(openingCurly + 1, closingCurly);
return body.replace(/\n/g, '\n\t');
} | javascript | {
"resource": ""
} |
q483 | updateInfo | train | function updateInfo(info, override, source, sourceId) {
if (source) {
if (source.minzoom !== undefined) {
// eslint-disable-next-line no-param-reassign
info.minzoom = source.minzoom;
}
if (source.maxzoom !== undefined) {
// eslint-disable-next-line no-param-reassign
info.maxzoom = source.maxzoom;
}
}
if (sourceId !== undefined) {
// eslint-disable-next-line no-param-reassign
info.name = sourceId;
}
if (override) {
_.each(override, (v, k) => {
if (v === null) {
// When override.key == null, delete that key
// eslint-disable-next-line no-param-reassign
delete info[k];
} else {
// override info of the parent
// eslint-disable-next-line no-param-reassign
info[k] = v;
}
});
}
} | javascript | {
"resource": ""
} |
q484 | qcertEval | train | function qcertEval(inputConfig) {
console.log("qcertEval chosen");
var handler = function(result) {
console.log("Compiler returned");
console.log(result);
postMessage(result.eval);
console.log("reply message posted");
// Each spawned worker is designed to be used once
close();
}
qcertWhiskDispatch(inputConfig, handler);
} | javascript | {
"resource": ""
} |
q485 | getAnnotationInfo | train | function getAnnotationInfo(name, fn, isArray) {
if (!fn) { return null; }
var str = fn.toString();
var rgx = new RegExp('(?:@' + name + '\\()(.*)(?:\\))');
var matches = rgx.exec(str);
if (!matches || matches.length < 2) {
return null;
}
var annotation = matches[1];
if (isArray) {
annotation = '{ "data": ' + annotation + '}';
}
// we want all double quotes in our string
annotation = annotation.replace(/'/g, '"');
// parse out the object from the string
var obj = null;
try {
obj = JSON.parse(annotation);
}
catch (ex) {
/* eslint no-console:0 */
console.log('Annotation parse error with ' + annotation);
throw ex;
}
if (isArray) {
obj = obj.data;
}
return obj;
} | javascript | {
"resource": ""
} |
q486 | getAliases | train | function getAliases(name, flapjack) {
var moduleInfo = getModuleInfo(flapjack) || {};
var aliases = moduleInfo[name] || {};
return aliases === true ? {} : aliases;
} | javascript | {
"resource": ""
} |
q487 | getServerAliases | train | function getServerAliases(flapjack, options) {
options = options || {};
var aliases = getAliases('server', flapjack);
var serverAliases = options && options.serverAliases;
return _.extend({}, aliases, serverAliases);
} | javascript | {
"resource": ""
} |
q488 | getClientAliases | train | function getClientAliases(flapjack, options) {
options = options || {};
var aliases = getAliases('client', flapjack);
return _.extend({}, aliases, options.clientAliases);
} | javascript | {
"resource": ""
} |
q489 | getParameters | train | function getParameters(flapjack) {
if (!_.isFunction(flapjack)) {
throw new Error('Flapjack not a function ' + JSON.stringify(flapjack));
}
var str = flapjack.toString();
var pattern = /(?:\()([^\)]*)(?:\))/;
var matches = pattern.exec(str);
if (matches === null || matches.length < 2) {
throw new Error('Invalid flapjack: ' + str.substring(0, 200));
}
var unfiltered = matches[1].replace(/\s/g, '').split(',');
var params = [], i;
for (i = 0; i < unfiltered.length; i++) {
if (unfiltered[i]) {
params.push(unfiltered[i]);
}
}
return params;
} | javascript | {
"resource": ""
} |
q490 | getResourceNames | train | function getResourceNames() {
var resourceNames = {};
var resourcesDir = this.injector.rootDir + '/' + this.injector.servicesDir + '/resources';
if (!fs.existsSync(path.normalize(resourcesDir))) {
return resourceNames;
}
var names = fs.readdirSync(path.normalize(resourcesDir));
_.each(names, function (name) {
if (name.substring(name.length - 3) !== '.js') { // only dirs, not js files
resourceNames[utils.getPascalCase(name)] = utils.getCamelCase(name);
}
});
return resourceNames;
} | javascript | {
"resource": ""
} |
q491 | getModel | train | function getModel(service, mixins) {
// model constructor takes in data and saves it along with the model mixins
var Model = function (data) {
_.extend(this, data, mixins);
};
if (service.save) {
Model.prototype.save = function () {
if (this._id) {
return service.save({ where: { _id: this._id }, data: this });
}
else {
return service.save({ data: this });
}
};
}
else if (service.create && service.update) {
Model.prototype.save = function () {
if (this._id) {
return service.update({ where: { _id: this._id }, data: this });
}
else {
return service.create({ data: this });
}
};
}
if (service.remove) {
Model.prototype.remove = function () {
return service.remove({ where: { _id: this._id } });
};
}
// the service methods are added as static references on the model
_.each(service, function (method, methodName) {
Model[methodName] = function () {
return service[methodName].apply(service, arguments);
};
});
return Model;
} | javascript | {
"resource": ""
} |
q492 | create | train | function create(modulePath, moduleStack) {
// first check the cache to see if we already loaded it
if (this.cache[modulePath]) {
return this.cache[modulePath];
}
// try to get the resource for this module
var resource;
if (this.resources[modulePath]) {
resource = this.resources[modulePath];
}
else if (this.resourceNames[modulePath]) {
resource = this.injector.loadModule(this.resourceNames[modulePath] + 'Resource');
}
else {
return null;
}
// get the service for this model
var serviceName = modulePath.substring(0, 1).toLowerCase() + modulePath.substring(1) + 'Service';
var service = this.injector.loadModule(serviceName, moduleStack);
// save the model to cache and return it
var Model = this.getModel(service, resource.mixins);
this.cache[modulePath] = Model;
return Model;
} | javascript | {
"resource": ""
} |
q493 | InternalObjectFactory | train | function InternalObjectFactory(injector) {
this.injector = injector;
this.internalObjects = {
resources: true,
reactors: true,
adapters: true,
appConfigs: true,
eventBus: eventBus,
chainPromises: utils.chainPromises
};
} | javascript | {
"resource": ""
} |
q494 | loadResources | train | function loadResources() {
var resources = {};
var resourcesDir = path.join(this.injector.rootDir, this.injector.servicesDir + '/resources');
if (!fs.existsSync(resourcesDir)) {
return resources;
}
var me = this;
var resourceNames = fs.readdirSync(resourcesDir);
_.each(resourceNames, function (resourceName) {
if (resourceName.substring(resourceName.length - 3) !== '.js') { // only dirs, not js files
resources[resourceName] = me.injector.loadModule(utils.getCamelCase(resourceName + '.resource'));
}
});
return resources;
} | javascript | {
"resource": ""
} |
q495 | loadAdapters | train | function loadAdapters() {
var adapters = {};
var adaptersDir = path.join(this.injector.rootDir, this.injector.servicesDir + '/adapters');
if (!fs.existsSync(adaptersDir)) {
return this.injector.adapters || {};
}
var me = this;
var adapterNames = fs.readdirSync(adaptersDir);
_.each(adapterNames, function (adapterName) {
if (adapterName.substring(adapterName.length - 3) !== '.js') { // only dirs, not js files
var adapterImpl = me.injector.adapterMap[adapterName];
adapterName = utils.getPascalCase(adapterImpl + '.' + adapterName + '.adapter');
adapters[adapterName] = me.injector.loadModule(adapterName);
}
});
// add the adapters that come from plugins to the list
_.extend(adapters, this.injector.adapters);
// return the adapters
return adapters;
} | javascript | {
"resource": ""
} |
q496 | loadReactors | train | function loadReactors() {
var reactors = {};
var reactorsDir = path.join(this.injector.rootDir, this.injector.servicesDir + '/reactors');
if (!fs.existsSync(reactorsDir)) {
return reactors;
}
var me = this;
var reactorNames = fs.readdirSync(reactorsDir);
_.each(reactorNames, function (reactorName) {
reactorName = reactorName.substring(0, reactorName.length - 3);
reactors[reactorName] = me.injector.loadModule(utils.getCamelCase(reactorName));
});
// add the reactors that come from plugins to the list
_.extend(reactors, this.injector.reactors);
return reactors;
} | javascript | {
"resource": ""
} |
q497 | loadAppConfigs | train | function loadAppConfigs() {
var appConfigs = {};
var appDir = path.join(this.injector.rootDir, '/app');
if (!fs.existsSync(appDir)) {
return appConfigs;
}
var me = this;
var appNames = fs.readdirSync(appDir);
_.each(appNames, function (appName) {
appConfigs[appName] = me.injector.loadModule('app/' + appName + '/' + appName + '.app');
});
return appConfigs;
} | javascript | {
"resource": ""
} |
q498 | create | train | function create(objectName) {
// for resources we need to load them the first time they are referenced
if (objectName === 'resources' && this.internalObjects[objectName] === true) {
this.internalObjects[objectName] = this.loadResources();
}
// for reactors we need to load them the first time they are referenced
else if (objectName === 'reactors' && this.internalObjects[objectName] === true) {
this.internalObjects[objectName] = this.loadReactors();
}
// for reactors we need to load them the first time they are referenced
else if (objectName === 'appConfigs' && this.internalObjects[objectName] === true) {
this.internalObjects[objectName] = this.loadAppConfigs();
}
// for adapters we need to load them the first time they are referenced
else if (objectName === 'adapters' && this.internalObjects[objectName] === true) {
this.internalObjects[objectName] = this.loadAdapters();
}
return this.internalObjects[objectName];
} | javascript | {
"resource": ""
} |
q499 | formatDevTrace | train | function formatDevTrace(level, context, message, args, err) {
var str,
mainMessage = util.format.apply(global, [message].concat(args)),
printStack = API.stacktracesWith.indexOf(level) > -1,
errCommomMessage = err && (err.name + ': ' + err.message),
isErrorLoggingWithoutMessage = mainMessage === errCommomMessage;
switch (level) {
case 'DEBUG':
str = colors.grey(level);
break;
case 'INFO':
str = colors.blue(level) + ' '; // Pad to 5 chars
break;
case 'WARN':
str = colors.yellow(level) + ' '; // Pad to 5 chars
break;
case 'ERROR':
str = colors.red(level);
break;
case 'FATAL':
str = colors.red.bold(level);
break;
}
str += ' ' + mainMessage;
if (isErrorLoggingWithoutMessage) {
str += colorize(colors.gray, serializeErr(err).toString(printStack).substr(mainMessage.length));
} else if (err) {
str += '\n' + colorize(colors.gray, serializeErr(err).toString(printStack));
}
var localContext = _.omit(context, formatDevTrace.omit);
str += Object.keys(localContext).length ?
' ' + colorize(colors.gray, util.inspect(localContext)) :
'';
// pad all subsequent lines with as much spaces as "DEBUG " or "INFO " have
return str.replace(new RegExp('\r?\n','g'), '\n ');
} | javascript | {
"resource": ""
} |