_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
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)) {
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; }
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 +
javascript
{ "resource": "" }
q403
train
function(text) { return macros.cleanMacros(text.replace(/\n/g,
javascript
{ "resource": "" }
q404
finishBasicPromise
train
function finishBasicPromise (resolve, reject) { return (err, res) => { if (err) { return reject(err);
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,
javascript
{ "resource": "" }
q406
getClasses
train
function getClasses(element) { const className = element.className; const classes = {}; if (className !== null && className.length > 0) { className.split(' ').forEach((className) => {
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);
javascript
{ "resource": "" }
q408
train
function (value) { const IllegalValue = this.$err.IllegalValue; if (typeof value !== 'string') { return value; } const result = value.replace(ENVVAR_PATTERN, function ()
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 = {};
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)
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;
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
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;
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
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
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)
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;
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
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'); } //
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,
javascript
{ "resource": "" }
q421
parseString
train
function parseString(xml, cb) { return fastxml2js.parseString(xml, function(err, data) { //So that it's asynchronous
javascript
{ "resource": "" }
q422
_callIfFn
train
function _callIfFn(thing, context, properties) { return
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
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)) {
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) : [];
javascript
{ "resource": "" }
q426
closest
train
function closest(node, parentSelector) { var cursor = node; if (!parentSelector || typeof parentSelector !== 'string') { throw new Error('Please specify
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];
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
javascript
{ "resource": "" }
q429
createRemoveNodeHandler
train
function createRemoveNodeHandler(el, fn) { return function (mutations, observer) { mutations.forEach(function (mutation) { if
javascript
{ "resource": "" }
q430
getPos
train
function getPos(el) { var rect = el.getBoundingClientRect(), scrollY = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; return {
javascript
{ "resource": "" }
q431
train
function(tokenService, domainPrefix) { var tokenUrl = tokenService.replace(/\{DOMAIN_PREFIX\}/,
javascript
{ "resource": "" }
q432
AdapterFactory
train
function AdapterFactory(injector) { if (!injector.adapters) { return; } var me = this; this.adapterMap = {}; _.each(injector.adapterMap, function
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);
javascript
{ "resource": "" }
q434
getPascalCase
train
function getPascalCase(filePath) { var camelCase = getCamelCase(filePath);
javascript
{ "resource": "" }
q435
getModulePath
train
function getModulePath(filePath, fileName) { if (isJavaScript(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) === '}') {
javascript
{ "resource": "" }
q437
chainPromises
train
function chainPromises(calls, val) { if (!calls || !calls.length)
javascript
{ "resource": "" }
q438
checksum
train
function checksum(str) { crcTbl = crcTbl || makeCRCTable(); /* jslint bitwise: true */ var crc = 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 || {};
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),
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);
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++) {
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);
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
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) {
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
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; }
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
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)
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)) {
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;
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)];
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,
javascript
{ "resource": "" }
q454
setDefaults
train
function setDefaults(model, defaults) { if (!defaults) { return; } _.each(defaults, function
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({});
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 + '||' +
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
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
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) {
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);
javascript
{ "resource": "" }
q461
requireModule
train
function requireModule(filePath, refreshFlag) { if (refreshFlag) {
javascript
{ "resource": "" }
q462
getService
train
function getService(name) { if (name.indexOf('.') >= 0) { name = utils.getCamelCase(name); }
javascript
{ "resource": "" }
q463
transform
train
function transform(flapjack, pluginOptions, runtimeOptions) { var name = runtimeOptions.transformer; var transformer = transformerFactory.getTransformer(name, clientPlugin, pluginOptions); var 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);
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);
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 =
javascript
{ "resource": "" }
q467
isCandidate
train
function isCandidate(modulePath) { modulePath = modulePath || ''; var len = modulePath.length; return modulePath.indexOf('/') < 0 && len > 7 &&
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]; //
javascript
{ "resource": "" }
q469
getResource
train
function getResource(serviceInfo, moduleStack) { var resourceName = serviceInfo.resourceName; var resourcePath = '/resources/' + resourceName + '/' + resourceName + '.resource';
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 + '/' +
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) {
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) {
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
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);
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) ||
javascript
{ "resource": "" }
q476
setLevel
train
function setLevel(level) { opts.level = level; let logLevelIndex = levels.indexOf(opts.level.toUpperCase()); levels.forEach((logLevel) => {
javascript
{ "resource": "" }
q477
merge
train
function merge(obj1, obj2) { var res = {}, attrname; for (attrname in obj1) {
javascript
{ "resource": "" }
q478
loadUIPart
train
function loadUIPart(appName, filePath) { var idx = filePath.indexOf(delim + appName + delim); var
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
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);
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) {
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
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;
javascript
{ "resource": "" }
q484
qcertEval
train
function qcertEval(inputConfig) { console.log("qcertEval chosen"); var handler = function(result) { console.log("Compiler returned");
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 {
javascript
{ "resource": "" }
q486
getAliases
train
function getAliases(name, flapjack) { var moduleInfo = getModuleInfo(flapjack) || {}; var aliases =
javascript
{ "resource": "" }
q487
getServerAliases
train
function getServerAliases(flapjack, options) { options = options || {}; var aliases = getAliases('server', flapjack); var serverAliases =
javascript
{ "resource": "" }
q488
getClientAliases
train
function getClientAliases(flapjack, options) { options = options || {}; var aliases = getAliases('client', flapjack);
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)); }
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) {
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 });
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
javascript
{ "resource": "" }
q493
InternalObjectFactory
train
function InternalObjectFactory(injector) { this.injector = injector; this.internalObjects = { resources: true, reactors: true,
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) {
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) {
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);
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);
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) {
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 += '
javascript
{ "resource": "" }