_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q50300
routeObjToRouteName
train
function routeObjToRouteName(route, path) { var name = route.controllerAs; var controller = route.controller; if (!name && controller) { if (angular.isArray(controller)) { controller = controller[controller.length - 1]; } name = controller.name; } if (!name) { var segments = path.split('/'); name = segments[segments.length - 1]; } if (name) { name = name + 'AutoCmp'; } return name; }
javascript
{ "resource": "" }
q50301
Validator
train
function Validator(options) { options = options || {}; this.cwd = options.cwd || process.cwd(); this.debug = !!options.debug; }
javascript
{ "resource": "" }
q50302
hmsToSeconds
train
function hmsToSeconds(time) { var arr = time.split(':'), s = 0, m = 1; while (arr.length > 0) { s += m * parseInt(arr.pop(), 10); m *= 60; } return s; }
javascript
{ "resource": "" }
q50303
secondsToHms
train
function secondsToHms(seconds) { var h = Math.floor(seconds / 3600); var m = Math.floor((seconds / 60) % 60); var s = seconds % 60; var pad = function (n) { n = String(n); return n.length >= 2 ? n : "0" + n; }; if (h > 0) { return pad(h) + ':' + pad(m) + ':' + pad(s); } else { return pad(m) + ':' + pad(s); } }
javascript
{ "resource": "" }
q50304
timeParamToSeconds
train
function timeParamToSeconds(param) { var componentValue = function (si) { var regex = new RegExp('(\\d+)' + si); return param.match(regex) ? parseInt(RegExp.$1, 10) : 0; }; return componentValue('h') * 3600 + componentValue('m') * 60 + componentValue('s'); }
javascript
{ "resource": "" }
q50305
internalAction
train
function internalAction(scope, page) { // Block clicks we try to load the active page if (scope.page == page) { return; } // Block if we are forcing disabled if(scope.isDisabled) { return; } // Update the page in scope scope.page = page; // Pass our parameters to the paging action scope.pagingAction({ page: scope.page, pageSize: scope.pageSize, total: scope.total }); // If allowed scroll up to the top of the page if (scope.scrollTop) { scrollTo(0, 0); } }
javascript
{ "resource": "" }
q50306
addRange
train
function addRange(start, finish, scope) { // Add our items where i is the page number var i = 0; for (i = start; i <= finish; i++) { var pgHref = scope.pgHref.replace(regex, i); var liClass = scope.page == i ? scope.activeClass : ''; // Handle items that are affected by disabled if(scope.isDisabled){ pgHref = ''; liClass = scope.disabledClass; } scope.List.push({ value: i, title: scope.textTitlePage.replace(regex, i), liClass: liClass, pgHref: pgHref, action: function () { internalAction(scope, this.value); } }); } }
javascript
{ "resource": "" }
q50307
buildDataTable
train
function buildDataTable() { var self = this; var dataTable = new google.visualization.DataTable(); _.each(self.columns, function (value) { dataTable.addColumn(value); }); if (!_.isEmpty(self.rows)) { dataTable.addRows(self.rows); } return dataTable; }
javascript
{ "resource": "" }
q50308
updateDataTable
train
function updateDataTable() { var self = this; // Remove all data from the datatable. self.dataTable.removeRows(0, self.dataTable.getNumberOfRows()); self.dataTable.removeColumns(0, self.dataTable.getNumberOfColumns()); // Add _.each(self.columns, function (value) { self.dataTable.addColumn(value); }); if (!_.isEmpty(self.rows)) { self.dataTable.addRows(self.rows); } }
javascript
{ "resource": "" }
q50309
buildWrapper
train
function buildWrapper(chartType, dataTable, options, containerId) { var wrapper = new google.visualization.ChartWrapper({ chartType: chartType, dataTable: dataTable, options: options, containerId: containerId }); return wrapper; }
javascript
{ "resource": "" }
q50310
buildChart
train
function buildChart() { var self = this; // If dataTable isn't set, build it var dataTable = _.isEmpty(self.dataTable) ? self.buildDataTable() : self.dataTable; self.wrapper = self.buildWrapper(self.chartType, dataTable, self.options, self.chartId); // Set the datatable on this instance self.dataTable = self.wrapper.getDataTable(); // After chart is built, set it on this instance and resolve the promise. google.visualization.events.addOneTimeListener(self.wrapper, 'ready', function () { self.chart = self.wrapper.getChart(); chartDeferred.resolve(); }); }
javascript
{ "resource": "" }
q50311
drawChart
train
function drawChart() { var self = this; // We don't have any (usable) data, or we don't have columns. We can't draw a chart without those. if (!_.isEmpty(self.rows) && !_.isObjectLike(self.rows) || _.isEmpty(self.columns)) { return; } if (_.isNull(self.chart)) { // We haven't built the chart yet, so JUST. DO. IT! self.buildChart(); } else { // Chart already exists, just update the data self.updateDataTable(); } // Chart has been built/Data has been updated, draw the chart. self.wrapper.draw(); // Return promise. Resolves when chart finishes loading. return chartDeferred.promise; }
javascript
{ "resource": "" }
q50312
prepareParams
train
function prepareParams(msg, config) { var params = {}, inputlang = config.inputlang ? config.inputlang : 'en', outputlang = config.outputlang ? config.outputlang : 'en'; if (msg.piparams) { if (msg.piparams.inputlanguage && -1 < VALID_INPUT_LANGUAGES.indexOf(msg.piparams.inputlanguage)) { inputlang = msg.piparams.inputlanguage; } if (msg.piparams.responselanguage && -1 < VALID_RESPONSE_LANGUAGES.indexOf(msg.piparams.responselanguage)) { outputlang = msg.piparams.responselanguage; } } params = { content: msg.payload, consumption_preferences: config.consumption ? config.consumption : false, raw_scores: config.rawscores ? config.rawscores : false, headers: { 'content-language': inputlang, 'accept-language': outputlang, 'accept': 'application/json' } }; if ('string' === typeof msg.payload) { params.content_type = 'text/plain'; } else { params.content_type = 'application/json'; } return Promise.resolve(params); }
javascript
{ "resource": "" }
q50313
Node
train
function Node(config) { RED.nodes.createNode(this,config); var node = this, message = ''; this.on('input', function (msg) { node.status({}); payloadCheck(msg) .then(function(){ return wordcountCheck(msg, config); }) .then(function(){ return credentialsCheck(node); }) .then(function(){ return setEndPoint(config); }) .then(function(){ return prepareParams(msg, config); }) .then(function(params){ node.status({fill:'blue', shape:'dot', text:'requesting'}); return executeService(msg, params); }) .then(function(){ node.status({}); node.send(msg); }) .catch(function(err){ payloadutils.reportError(node, msg, err); node.send(msg); }); }); }
javascript
{ "resource": "" }
q50314
AlchemyFeatureExtractNode
train
function AlchemyFeatureExtractNode (config) { RED.nodes.createNode(this, config); var node = this; this.on('input', function (msg) { if (!msg.payload) { this.status({fill:'red', shape:'ring', text:'missing payload'}); var message = 'Missing property: msg.payload'; node.error(message, msg); return; } // If it is present the newly provided user entered key takes precedence over the existing one. apikey = s_apikey || this.credentials.apikey; this.status({}); if (!apikey) { this.status({fill:'red', shape:'ring', text:'missing credentials'}); var message = 'Missing Alchemy API service credentials'; node.error(message, msg); return; } var alchemy_language = watson.alchemy_language( { api_key: apikey } ); // Check which features have been requested. var enabled_features = Object.keys(FEATURES).filter(function (feature) { return config[feature] }); if (!enabled_features.length) { this.status({fill:'red', shape:'ring', text:'no features selected'}); var message = 'AlchemyAPI node must have at least one selected feature.'; node.error(message, msg); return; } var params = buildParams(enabled_features, config, msg); // Splice in the additional options from msg.alchemy_options // eg. The user may have entered msg.alchemy_options = {maxRetrieve: 2}; for (var key in msg.alchemy_options) { params[key] = msg.alchemy_options[key]; } alchemy_language.combined(params, function (err, response) { if (err || response.status === 'ERROR') { node.status({fill:'red', shape:'ring', text:'call to alchmeyapi language service failed'}); console.log('Error:', msg, err); node.error(err, msg); } else { msg.features = {}; //msg.features['all'] = response; Object.keys(FEATURES).forEach(function (feature) { var answer_feature = FEATURES[feature]; msg.features[feature] = response[answer_feature] || {}; }); node.send(msg); } }); }); }
javascript
{ "resource": "" }
q50315
NLUNode
train
function NLUNode (config) { RED.nodes.createNode(this, config); var node = this; this.on('input', function (msg) { var message = '', options = {}; node.status({}); username = sUsername || this.credentials.username; password = sPassword || this.credentials.password; apikey = sApikey || this.credentials.apikey; endpoint = sEndpoint; if ((!config['default-endpoint']) && config['service-endpoint']) { endpoint = config['service-endpoint']; } initialCheck(username, password, apikey) .then(function(){ return payloadCheck(msg, options); }) .then(function(){ return checkAdditonalMsgOptions(msg, options); }) .then(function(){ return checkFeatureRequest(config, options); }) .then(function(){ return checkFeatureOptions(msg, config, options); }) .then(function(){ return checkNonFeatureOptions(config, options); }) .then(function(){ node.status({fill:'blue', shape:'dot', text:'requesting'}); return invokeService(options); }) .then(function(data){ msg.features = data; node.send(msg); node.status({}); }) .catch(function(err){ reportError(node,msg,err); }); }); }
javascript
{ "resource": "" }
q50316
overrideCheck
train
function overrideCheck(msg) { if (msg.srclang){ var langCode = payloadutils.langTransToSTTFormat(msg.srclang); config.lang = langCode; } return Promise.resolve(); }
javascript
{ "resource": "" }
q50317
payloadNonStreamCheck
train
function payloadNonStreamCheck(msg) { var message = ''; // The input comes in on msg.payload, and can either be an audio file or a string // representing a URL. if (!msg.payload instanceof Buffer || !typeof msg.payload === 'string') { message = 'Invalid property: msg.payload, can only be a URL or a Buffer.'; } else if (!(msg.payload instanceof Buffer)) { // This check is repeated just before the call to the service, but // its also performed here as a double check. if (typeof msg.payload === 'string' && !payloadutils.urlCheck(msg.payload)) { message = 'Invalid URL.'; } } else { var f = 'txt', ft = ''; ft = fileType(msg.payload); if (ft) { f = ft.ext; } switch (f) { case 'wav': case 'flac': case 'ogg': case 'mp3': case 'mpeg': break; default: if (! ft.mime.toLowerCase().includes('audio')) { message = 'Audio format (' + f + ') not supported, must be encoded as WAV, MP3, FLAC or OGG.'; } } } if (message) { return Promise.reject(message); } return Promise.resolve(); }
javascript
{ "resource": "" }
q50318
processInputStream
train
function processInputStream(msg) { var tmp = msg.payload; if ('string' === typeof msg.payload) { msg.payload = JSON.parse(tmp); } if (msg.payload.action) { if ('start' === msg.payload.action) { startPacket = msg.payload; } } else { msg.payload = { 'action' : 'data', 'data' : tmp }; } return Promise.resolve(msg.payload); }
javascript
{ "resource": "" }
q50319
connectIfNeeded
train
function connectIfNeeded() { // console.log('re-establishing the connect'); websocket = null; socketCreationInProcess = false; // The token may have expired so test for it. getToken(determineService()) .then(() => { return processSTTSocketStart(false); }) .then(() => { //return Promise.resolve(); return; }) .catch((err) => { //return Promise.resolve(); return; }); }
javascript
{ "resource": "" }
q50320
train
function(serviceName, returnBoolean, alchemyRegex) { var regex = alchemyRegex ? RegExp('(http|https)(://)('+serviceName+').*') : RegExp('(http|https)(://)([^\/]+)(/)('+serviceName+').*'); var services = appEnv.getServices(); for (var service in services) { if (services[service].hasOwnProperty('credentials')) { if (services[service].credentials.hasOwnProperty('url')){ if (services[service].credentials.url.search(regex) === 0){ return returnBoolean ? true : services[service].credentials; } } } } return returnBoolean ? false : null; }
javascript
{ "resource": "" }
q50321
train
function(credentials) { var taSettings = {}; username = sUsername || credentials.username; password = sPassword || credentials.password; apikey = sApikey || credentials.apikey; if (apikey) { taSettings.iam_apikey = apikey; } else if (username && password) { taSettings.username = username; taSettings.password = password; } else { taSettings = null; } return taSettings; }
javascript
{ "resource": "" }
q50322
train
function(msg, node) { var message = null, taSettings = null; taSettings = checkCreds(node.credentials); if (!taSettings) { message = 'Missing Tone Analyzer service credentials'; } else if (msg.payload) { message = toneutils.checkPayload(msg.payload); } else { message = 'Missing property: msg.payload'; } if (message) { return Promise.reject(message); } else { return Promise.resolve(taSettings); } }
javascript
{ "resource": "" }
q50323
train
function(msg, config, node) { checkConfiguration(msg, node) .then(function(settings) { var options = toneutils.parseOptions(msg, config); options = toneutils.parseLanguage(msg, config, options); node.status({fill:'blue', shape:'dot', text:'requesting'}); return invokeService(config, options, settings); }) .then(function(data){ node.status({}) msg.response = data; node.send(msg); node.status({}); }) .catch(function(err){ payloadutils.reportError(node,msg,err); node.send(msg); }); }
javascript
{ "resource": "" }
q50324
Node
train
function Node (config) { RED.nodes.createNode(this, config); var node = this; // Invoked when the node has received an input as part of a flow. this.on('input', function (msg) { processOnInput(msg, config, node); }); }
javascript
{ "resource": "" }
q50325
performAction
train
function performAction(params, feature, cbdone, cbcleanup) { var alchemy_vision = watson.alchemy_vision( { api_key: apikey } ); if (feature == 'imageFaces') { alchemy_vision.recognizeFaces(params, cbdone); } else if (feature == 'imageLink') { alchemy_vision.getImageLinks(params, cbdone); } else if (feature == 'imageKeywords') { alchemy_vision.getImageKeywords(params, cbdone); } else if (feature == 'imageText') { alchemy_vision.getImageSceneText(params, cbdone); } if (cbcleanup) cbcleanup(); }
javascript
{ "resource": "" }
q50326
train
function(err, keywords) { if (err || keywords.status === 'ERROR') { node.status({fill:'red', shape:'ring', text:'call to alchmeyapi vision service failed'}); console.log('Error:', msg, err); node.error(err, msg); } else { msg.result = keywords[FEATURE_RESPONSES[feature]] || []; msg.fullresult = {}; msg.fullresult['all'] = keywords; node.send(msg); } }
javascript
{ "resource": "" }
q50327
executeListExamples
train
function executeListExamples(node, conv, params, msg) { var p = new Promise(function resolver(resolve, reject){ conv.listExamples(params, function (err, response) { if (err) { reject(err); } else { msg['examples'] = response.examples ? response.examples: response; resolve(); } }); }); return p; }
javascript
{ "resource": "" }
q50328
buildParams
train
function buildParams(msg, method, config, params) { var p = buildWorkspaceParams(msg, method, config, params) .then(function(){ return buildIntentParams(msg, method, config, params); }) .then(function(){ return buildExampleParams(msg, method, config, params); }) .then(function(){ return buildEntityParams(msg, method, config, params); }) .then(function(){ return buildEntityValueParams(msg, method, config, params); }) .then(function(){ return buildDialogParams(msg, method, config, params); }) .then(function(){ return buildExportParams(method, config, params); }); return p; }
javascript
{ "resource": "" }
q50329
setWorkspaceParams
train
function setWorkspaceParams(method, params, workspaceObject) { var workspace_id = null; var stash = {}; if ('object' !== typeof workspaceObject) { return Promise.reject('json content expected as input on payload'); } switch(method) { case 'updateIntent': if (params['old_intent']) { stash['old_intent'] = params['old_intent']; } break; case 'updateEntity': if (params['old_entity']) { stash['old_entity'] = params['old_entity']; } break; case 'updateEntityValue': if (params['old_value']) { stash['old_value'] = params['old_value']; } if (params['entity']) { stash['entity'] = params['entity']; } break; case 'updateDialogNode': if (params['old_dialog_node']) { stash['old_dialog_node'] = params['old_dialog_node']; } break; } switch(method) { case 'updateWorkspace': case 'createIntent': case 'updateIntent': case 'createEntity': case 'updateEntity': case 'updateEntityValue': case 'createDialogNode': case 'updateDialogNode': if (params['workspace_id']) { stash['workspace_id'] = params['workspace_id']; } break; } if (workspaceObject) { params = workspaceObject; } if (stash) { for (var k in stash) { params[k] = stash[k]; } } return Promise.resolve(params); }
javascript
{ "resource": "" }
q50330
processFileForWorkspace
train
function processFileForWorkspace(info, method) { var workspaceObject = null; switch (method) { case 'createWorkspace': case 'updateWorkspace': case 'createIntent': case 'updateIntent': case 'createEntity': case 'updateEntity': case 'updateEntityValue': case 'createDialogNode': case 'updateDialogNode': try { workspaceObject = JSON.parse(fs.readFileSync(info.path, 'utf8')); } catch (err) { workspaceObject = fs.createReadStream(info.path); } } return Promise.resolve(workspaceObject); }
javascript
{ "resource": "" }
q50331
loadFile
train
function loadFile(node, method, params, msg) { var fileInfo = null; var p = openTheFile() .then(function(info){ fileInfo = info; return syncTheFile(fileInfo, msg); }) .then(function(){ return processFileForWorkspace(fileInfo, method); }) .then(function(workspaceObject){ return setWorkspaceParams(method, params, workspaceObject); }); return p; }
javascript
{ "resource": "" }
q50332
Node
train
function Node (config) { RED.nodes.createNode(this, config); var node = this; this.on('input', function (msg) { var method = config['cwm-custom-mode'], message = '', params = {}; username = sUsername || this.credentials.username; password = sPassword || this.credentials.password || config.password; apikey = sApikey || this.credentials.apikey || config.apikey; // All method to be overridden if (msg.params) { if (msg.params.method) { method = msg.params.method; } if (msg.params.username) { username = msg.params.username; } if (msg.params.password) { password = msg.params.password; } if (msg.params.apikey) { apikey = msg.params.apikey; } if (msg.params.version) { version = msg.params.version; } } endpoint = sEndpoint; if ((!config['cwm-default-endpoint']) && config['cwm-service-endpoint']) { endpoint = config['cwm-service-endpoint']; } node.status({}); initialCheck(apikey, username, password, method) .then(function(){ return buildParams(msg, method, config, params); }) .then(function(){ return checkForFile(method); }) .then(function(fileNeeded){ if (fileNeeded) { if (msg.payload instanceof Buffer) { return loadFile(node, method, params, msg); } // If the data is a json object then it will not // have been detected as a buffer. return setWorkspaceParams(method, params, msg.payload); } return Promise.resolve(params); }) .then(function(p){ params = p; node.status({fill:'blue', shape:'dot', text:'executing'}); return executeMethod(node, method, params, msg); }) .then(function(){ temp.cleanup(); node.status({}); node.send(msg); }) .catch(function(err){ temp.cleanup(); payloadutils.reportError(node,msg,err); }); }); }
javascript
{ "resource": "" }
q50333
doTranslate
train
function doTranslate(language_translator, msg, model_id) { var p = new Promise(function resolver(resolve, reject){ // Please be careful when reading the below. The first parameter is // a structure, and the tabbing enforced by codeacy imho obfuscates // the code, rather than making it clearer. I would have liked an // extra couple of spaces. language_translator.translate({ text: msg.payload, model_id: model_id }, function (err, response) { if (err) { reject(err); } else { msg.translation = {}; msg.translation.response = response; msg.payload = response.translations[0].translation; resolve(); } }); }); return p; }
javascript
{ "resource": "" }
q50334
performCreate
train
function performCreate(node,dialog,msg) { var params = {} node.status({fill:'blue', shape:'dot', text:'requesting create of new dialog template'}); //if ('file' in msg.dialog_params && 'dialog_name' in msg.dialog_params) { if ('dialog_name' in msg.dialog_params) { // extension supported : only XML // TODO : support other API format (json and encrypted crt) temp.open({suffix: '.xml'}, function (err, info) { if (err) throw err; //var fileBuffer = msg.dialog_params['file']; var fileBuffer = msg.payload; fs.writeFile(info.path, fileBuffer, function (err) { if (err) { console.error(err); throw err; } var aFileStream = fs.createReadStream(info.path); params.file = aFileStream; params.name = msg.dialog_params['dialog_name']; // Watson SDK call dialog.createDialog(params, function(err, dialog_data){ node.status({}); if (err) { node.status({fill:'red', shape:'ring', text:'call to dialog service failed'}); node.error(err, msg); } else { msg.dialog = dialog_data; msg.payload = 'Check msg.dialog dialog data'; node.send(msg); } }); }); }); } /* else if (! 'file' in msg.dialog_params) { var errtxt = 'Missing Dialog template file'; node.status({fill:'red', shape:'ring', text:errtxt}); node.error(errtxt, msg); }*/ else { errtxt = 'dialog_name not specified'; node.status({fill:'red', shape:'ring', text:errtxt}); node.error(errtxt, msg); } }
javascript
{ "resource": "" }
q50335
performDelete
train
function performDelete(node,dialog,msg, config) { var params = {}; var message = ''; node.status({fill:'blue', shape:'dot', text:'requesting delete of a dialog instance'}); if (!config.dialog || '' != config.dialog) { params.dialog_id = config.dialog; dialog.deleteDialog(params, function(err, dialog_data){ node.status({}); if (!err) { message='Dialog deleted successfully'; msg.dialog = dialog_data; msg.payload = message; node.send(msg); } else if (err && err.code==404) { message='Dialog already deleted or not existing (404)'; node.status({fill:'green', shape:'dot', text:message}); msg.payload = message; console.log(err); node.error(message, msg); } else { node.status({fill:'red', shape:'ring', text:'call to dialog service failed'}); node.error(err, msg); console.log(err); } }); } else { message = 'Dialog Id not specified'; node.status({fill:'red', shape:'ring', text:message}); node.error(errmessage, msg); } }
javascript
{ "resource": "" }
q50336
performList
train
function performList(node,dialog,msg) { node.status({fill:'blue', shape:'dot', text:'requesting list of dialogs'}); dialog.getDialogs({}, function(err, dialogs){ node.status({}); if (err) { node.status({fill:'red', shape:'ring', text:'call to dialog service failed'}); node.error(err, msg); } else { msg.dialog = dialogs; msg.payload = 'Check msg.dialog for list of dialogs'; node.send(msg); } }); }
javascript
{ "resource": "" }
q50337
performDeleteAll
train
function performDeleteAll(node,dialog,msg) { node.status({fill:'blue', shape:'dot', text:'requesting Delete All dialogs'}); dialog.getDialogs({}, function(err, dialogs){ node.status({}); if (err) { node.status({fill:'red', shape:'ring', text:'Delete All : call to getDialogs service failed'}); node.error(err, msg); } else { // Array to hold async tasks var asyncTasks = []; var nb_todelete = dialogs.dialogs.length; var nbdeleted = 0; dialogs.dialogs.forEach(function (aDialog) { asyncTasks.push(function (cb) { var parms = {}; parms.dialog_id=aDialog.dialog_id;; dialog.deleteDialog(parms, function(err, dialog_data){ node.status({}); if (err) { node.error(err, msg); console.log('Error with the removal of Dialog ID '+parms.dialog_id +' : ' + err); } else { console.log('Dialog ID '+ aDialog.dialog_id + ' deleted successfully.'); nbdeleted++; } cb(); }); }); }); } // else async.parallel(asyncTasks, function(){ // All tasks are done now console.log('Deleted ' + nbdeleted + ' dialog objects on ' + nb_todelete ); if (nbdeleted==nb_todelete) msg.payload = 'All Dialogs have been deleted'; else msg.payload = 'Some Dialogs could have not been deleted; See node-RED log for errors.'; console.log(msg.payload); node.send(msg); }); }); }
javascript
{ "resource": "" }
q50338
addTask
train
function addTask(asyncTasks, msg, k, listParams, node) { asyncTasks.push(function(callback) { var buffer = msg.params[k]; temp.open({ suffix: '.' + fileType(buffer).ext }, function(err, info) { if (err) { node.status({ fill: 'red', shape: 'ring', text: 'unable to open image stream' }); node.error('Node has been unable to open the image stream', msg); return callback('open error on ' + k); } stream_buffer(info.path, msg.params[k], function() { let example_name = k; if (! (k.includes('positive') || k.includes('negative'))) { example_name = k.replace('examples', 'positive_examples'); } listParams[example_name] = fs.createReadStream(info.path); callback(null, example_name); }); }); }); }
javascript
{ "resource": "" }
q50339
Node
train
function Node (config) { RED.nodes.createNode(this, config); var node = this; this.on('input', function (msg) { var method = config['tts-custom-mode'], message = '', params = {}; username = sUsername || this.credentials.username; password = sPassword || this.credentials.password || config.password; apikey = sApikey || this.credentials.apikey || config.apikey; endpoint = sEndpoint; if ((!config['default-endpoint']) && config['service-endpoint']) { endpoint = config['service-endpoint']; } if (!apikey && (!username || !password)) { message = 'Missing Watson Text to Speech service credentials'; } else if (!method || '' === method) { message = 'Required mode has not been specified'; } else { params = buildParams(msg, method, config); } if (message) { payloadutils.reportError(node, msg, message); return; } if (checkForFile(method)) { if (msg.payload instanceof Buffer) { loadFile(node, method, params, msg); return; } params = setFileParams(method, params, msg); } executeMethod(node, method, params, msg); }); }
javascript
{ "resource": "" }
q50340
assertCollectionSizeLeast
train
function assertCollectionSizeLeast(_super) { return function(n) { if (utils.flag(this, 'immutable.collection.size')) { assertIsIterable(this._obj); const { size } = this._obj; new Assertion(size).a('number'); this.assert( size >= n, 'expected #{this} to have a size of at least #{exp} but got #{act}', 'expected #{this} to not have a size of at least #{exp} but got ' + '#{act}', n, size ); } else { _super.apply(this, arguments); } }; }
javascript
{ "resource": "" }
q50341
request
train
function request( host, method, path, params, query, headers, options, file, cb, debug ) { if (!options) options = {}; // Remove leading/trailing slash from the path/host so that we can join // the two together no matter which way the user chose to provide them. if (path[0] === FSLASH) { path = path.slice(1); } if (host[host.length - 1] === FSLASH) { host = host.slice(0, host.length - 1); } var url = host + FSLASH + path; var req = superagent[method](url); var bar; var prev_loaded = 0; if (!options.withoutCredentials) req.withCredentials(); if (!file) { // Clean up extra parameters that may have gotten in here // if the request came from the CLI module. This is hacky; move elsewhere if (params) { delete params._; delete params.$0; req.send(params); } if (query) { delete query._; delete query.$0; req.query(objectToQueryString(query)); } } else { //for file upload params are sent as query params req.accept('application/json'); req.timeout(600000); if (query.workspaceFileName && global.paperspace_cli && !query.json) { req.on('progress', function _progress(e) { if (!bar) bar = new ProgressBar('Uploading ' + node_path.basename(file) + ' [:bar] :rate/bps :percent :etas', { complete: '=', incomplete: ' ', width: 40, total: e.total, }); var chunkSize = e.loaded - prev_loaded; prev_loaded = e.loaded; bar.tick(chunkSize); }); } req.attach('file', file); delete query._; delete query.$0; if (query.json) delete query.json; req.query(objectToQueryString(query)); } if (headers) { for (var headerKey in headers) { req.set(headerKey, headers[headerKey]); } } // TODO: Add nicer debug utils? Use the 'debug' module? if (debug) { console.log(method, url, params, query, headers); } return req.end(function _requestCallback(err, res) { // if content is gzipped, then body is empty object, and content is in 'text' var body; if (res && res.text) { try { body = JSON.parse(res.text); } catch (parseErr) { //console.error(res.text); //console.error(parseErr); //console.error('res: ' + res) //body = {}; res.body = { message: res.text }; } } else if (res && res.body) { // res.body is expected to be text/json body = res.body; } else body = {}; // only return body in callback if (cb) return cb(err, body); // no callback provided; return the body return body; }); }
javascript
{ "resource": "" }
q50342
eachEndpoint
train
function eachEndpoint(iterator) { for (var namespace in endpoints) { var methods = endpoints[namespace]; for (var name in methods) { var method = methods[name]; iterator(namespace, name, method); } } return endpoints; }
javascript
{ "resource": "" }
q50343
paperspace
train
function paperspace(options) { if (options && !isAnyAuthOptionPresent(options)) { throw NO_CREDS; } var api = {}; eachEndpoint(function _eachEndpoint(namespace, name, method) { if (!api[namespace]) api[namespace] = {}; api[namespace][name] = wrapMethod(method, options); }); return api; }
javascript
{ "resource": "" }
q50344
client
train
function client(method, path, inputs, headers, file, cb) { var body = null; var query = {}; var options = {}; // It's assumed these will be provided, but just in case... if (!headers) headers = {}; headers.ps_client_name = clientName; headers.ps_client_version = clientVersion; // Send input params as the query string if this is a GET, otherwise send // with the HTTP request body switch (method.toLowerCase()) { case 'get': query = inputs; break; case 'post': if (file) { query = inputs; break; } default: // eslint-disable-line no-fallthrough // Don't leave the access token on the inputs object since the jwt // really belongs on the query string (at least, per the way the interface // to the Paperspace API is currently set up). query.access_token = inputs.access_token; delete inputs.access_token; body = inputs; break; } // The rubber finally meets the road with 'request', which initiates // the request via Superagent return request( path === '/jobs/logs' ? config.logHost : config.host, method, path, body, query, headers, options, file, cb, inputs.debug ); }
javascript
{ "resource": "" }
q50345
isSafePositiveInteger
train
function isSafePositiveInteger(x) { // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; // Is it a number? return Object.prototype.toString.call(x) === '[object Number]' && // Is it an integer? x % 1 === 0 && // Is it positive? x > 0 && // Is it less than the maximum safe integer? x <= MAX_SAFE_INTEGER; }
javascript
{ "resource": "" }
q50346
train
function(srcUrl, targetStream, opts, callback) { var listenerErrorIndicator = { errored: false }; if (typeof callback === 'undefined' && typeof opts === 'function') { callback = opts; opts = {}; } if (!validateArgs(srcUrl, opts, callback)) { // bad args, bail return; } // if there is an error writing to the stream, call the completion // callback with the error set addEventListener(listenerErrorIndicator, targetStream, 'error', function(err) { debug('Error ' + JSON.stringify(err)); if (callback) callback(err); }); opts = Object.assign({}, defaults(), opts); const ee = new events.EventEmitter(); // Set up the DB client const backupDB = request.client(srcUrl, opts); // Validate the DB exists, before proceeding to backup proceedIfDbValid(backupDB, function(err) { if (err) { if (err.name === 'DatabaseNotFound') { err.message = `${err.message} Ensure the backup source database exists.`; } // Didn't exist, or another fatal error, exit callback(err); return; } var backup = null; if (opts.mode === 'shallow') { backup = backupShallow; } else { // full mode backup = backupFull; } // If resuming write a newline as it's possible one would be missing from // an interruption of the previous backup. If the backup was clean this // will cause an empty line that will be gracefully handled by the restore. if (opts.resume) { targetStream.write('\n'); } // Get the event emitter from the backup process so we can handle events // before passing them on to the app's event emitter if needed. const internalEE = backup(backupDB, opts); addEventListener(listenerErrorIndicator, internalEE, 'changes', function(batch) { ee.emit('changes', batch); }); addEventListener(listenerErrorIndicator, internalEE, 'received', function(obj, q, logCompletedBatch) { // this may be too verbose to have as well as the "backed up" message // debug(' received batch', obj.batch, ' docs: ', obj.total, 'Time', obj.time); // Callback to emit the written event when the content is flushed function writeFlushed() { ee.emit('written', { total: obj.total, time: obj.time, batch: obj.batch }); if (logCompletedBatch) { logCompletedBatch(obj.batch); } debug(' backed up batch', obj.batch, ' docs: ', obj.total, 'Time', obj.time); } // Write the received content to the targetStream const continueWriting = targetStream.write(JSON.stringify(obj.data) + '\n', 'utf8', writeFlushed); if (!continueWriting) { // The buffer was full, pause the queue to stop the writes until we // get a drain event if (q && !q.isPaused) { q.pause(); targetStream.once('drain', function() { q.resume(); }); } } }); // For errors we expect, may or may not be fatal addEventListener(listenerErrorIndicator, internalEE, 'error', function(err) { debug('Error ' + JSON.stringify(err)); callback(err); }); addEventListener(listenerErrorIndicator, internalEE, 'finished', function(obj) { function emitFinished() { debug('Backup complete - written ' + JSON.stringify(obj)); const summary = { total: obj.total }; ee.emit('finished', summary); if (callback) callback(null, summary); } if (targetStream === process.stdout) { // stdout cannot emit a finish event so use a final write + callback targetStream.write('', 'utf8', emitFinished); } else { // If we're writing to a file, end the writes and register the // emitFinished function for a callback when the file stream's finish // event is emitted. targetStream.end('', 'utf8', emitFinished); } }); }); return ee; }
javascript
{ "resource": "" }
q50347
train
function(srcStream, targetUrl, opts, callback) { var listenerErrorIndicator = { errored: false }; if (typeof callback === 'undefined' && typeof opts === 'function') { callback = opts; opts = {}; } validateArgs(targetUrl, opts, callback); opts = Object.assign({}, defaults(), opts); const ee = new events.EventEmitter(); // Set up the DB client const restoreDB = request.client(targetUrl, opts); // Validate the DB exists, before proceeding to restore proceedIfDbValid(restoreDB, function(err) { if (err) { if (err.name === 'DatabaseNotFound') { err.message = `${err.message} Create the target database before restoring.`; } // Didn't exist, or another fatal error, exit callback(err); return; } restoreInternal( restoreDB, opts, srcStream, ee, function(err, writer) { if (err) { callback(err, null); return; } if (writer != null) { addEventListener(listenerErrorIndicator, writer, 'restored', function(obj) { debug(' restored ', obj.total); ee.emit('restored', { documents: obj.documents, total: obj.total }); }); addEventListener(listenerErrorIndicator, writer, 'error', function(err) { debug('Error ' + JSON.stringify(err)); // Only call destroy if it is available on the stream if (srcStream.destroy && srcStream.destroy instanceof Function) { srcStream.destroy(); } callback(err); }); addEventListener(listenerErrorIndicator, writer, 'finished', function(obj) { debug('restore complete'); ee.emit('finished', { total: obj.total }); callback(null, obj); }); } } ); }); return ee; }
javascript
{ "resource": "" }
q50348
downloadRemainingBatches
train
function downloadRemainingBatches(log, db, ee, startTime, batchesPerDownloadSession, parallelism) { var total = 0; // running total of documents downloaded so far var noRemainingBatches = false; // Generate a set of batches (up to batchesPerDownloadSession) to download from the // log file and download them. Set noRemainingBatches to `true` for last batch. function downloadSingleBatchSet(done) { // Fetch the doc IDs for the batches in the current set to // download them. function batchSetComplete(err, data) { total = data.total; done(); } function processRetrievedBatches(err, batches) { // process them in parallelised queue processBatchSet(db, parallelism, log, batches, ee, startTime, total, batchSetComplete); } readBatchSetIdsFromLogFile(log, batchesPerDownloadSession, function(err, batchSetIds) { if (err) { ee.emit('error', err); // Stop processing changes file for fatal errors noRemainingBatches = true; done(); } else { if (batchSetIds.length === 0) { noRemainingBatches = true; return done(); } logfilegetbatches(log, batchSetIds, processRetrievedBatches); } }); } // Return true if all batches in log file have been downloaded function isFinished() { return noRemainingBatches; } function onComplete() { ee.emit('finished', { total: total }); } async.doUntil(downloadSingleBatchSet, isFinished, onComplete); }
javascript
{ "resource": "" }
q50349
readBatchSetIdsFromLogFile
train
function readBatchSetIdsFromLogFile(log, batchesPerDownloadSession, callback) { logfilesummary(log, function processSummary(err, summary) { if (!summary.changesComplete) { callback(new error.BackupError('IncompleteChangesInLogFile', 'WARNING: Changes did not finish spooling')); return; } if (Object.keys(summary.batches).length === 0) { return callback(null, []); } // batch IDs are the property names of summary.batches var batchSetIds = getPropertyNames(summary.batches, batchesPerDownloadSession); callback(null, batchSetIds); }); }
javascript
{ "resource": "" }
q50350
processBatchSet
train
function processBatchSet(db, parallelism, log, batches, ee, start, grandtotal, callback) { var hasErrored = false; var total = grandtotal; // queue to process the fetch requests in an orderly fashion using _bulk_get var q = async.queue(function(payload, done) { var output = []; var thisBatch = payload.batch; delete payload.batch; delete payload.command; function logCompletedBatch(batch) { if (log) { fs.appendFile(log, ':d batch' + thisBatch + '\n', done); } else { done(); } } // do the /db/_bulk_get request // Note: this should use built-in _bulk_get, but revs is not accepted as // part of the request body by the server yet. Working around using request // method to POST with a query string. db.server.request( { method: 'POST', db: db.config.db, path: '_bulk_get', qs: { revs: true }, body: payload }, function(err, body) { if (err) { if (!hasErrored) { hasErrored = true; err = error.convertResponseError(err); // Kill the queue for fatal errors q.kill(); ee.emit('error', err); } done(); } else { // create an output array with the docs returned body.results.forEach(function(d) { if (d.docs) { d.docs.forEach(function(doc) { if (doc.ok) { output.push(doc.ok); } }); } }); total += output.length; var t = (new Date().getTime() - start) / 1000; ee.emit('received', { batch: thisBatch, data: output, length: output.length, time: t, total: total }, q, logCompletedBatch); } }); }, parallelism); for (var i in batches) { q.push(batches[i]); } q.drain = function() { callback(null, { total: total }); }; }
javascript
{ "resource": "" }
q50351
getPropertyNames
train
function getPropertyNames(obj, count) { // decide which batch numbers to deal with var batchestofetch = []; var j = 0; for (var i in obj) { batchestofetch.push(parseInt(i)); j++; if (j >= count) break; } return batchestofetch; }
javascript
{ "resource": "" }
q50352
bucketAccessible
train
function bucketAccessible(s3, bucketName) { return new Promise(function(resolve, reject) { var params = { Bucket: bucketName }; s3.headBucket(params, function(err, data) { if (err) { reject(new VError(err, 'S3 bucket not accessible')); } else { resolve(); } }); }); }
javascript
{ "resource": "" }
q50353
backupToS3
train
function backupToS3(sourceUrl, s3Client, s3Bucket, s3Key, shallow) { return new Promise((resolve, reject) => { debug(`Setting up S3 upload to ${s3Bucket}/${s3Key}`); // A pass through stream that has couchbackup's output // written to it and it then read by the S3 upload client. // It has a 64MB highwater mark to allow for fairly // uneven network connectivity. const streamToUpload = new stream.PassThrough({ highWaterMark: 67108864 }); // Set up S3 upload. const params = { Bucket: s3Bucket, Key: s3Key, Body: streamToUpload }; s3Client.upload(params, function(err, data) { debug('Object store upload done'); if (err) { debug(err); reject(new VError(err, 'Object store upload failed')); return; } debug('Object store upload succeeded'); debug(data); resolve(); }).httpUploadProgress = (progress) => { debug(`Object store upload progress: ${progress}`); }; debug(`Starting streaming data from ${s(sourceUrl)}`); couchbackup.backup( sourceUrl, streamToUpload, (err, obj) => { if (err) { debug(err); reject(new VError(err, 'CouchBackup failed with an error')); return; } debug(`Download from ${s(sourceUrl)} complete.`); streamToUpload.end(); // must call end() to complete upload. // resolve() is called by the upload } ); }); }
javascript
{ "resource": "" }
q50354
train
function(obj) { if (obj.command === 't') { state[obj.batch] = true; } else if (obj.command === 'd') { delete state[obj.batch]; } else if (obj.command === 'changes_complete') { changesComplete = true; } }
javascript
{ "resource": "" }
q50355
createBackupFile
train
function createBackupFile(sourceUrl, backupTmpFilePath) { return new Promise((resolve, reject) => { couchbackup.backup( sourceUrl, fs.createWriteStream(backupTmpFilePath), (err) => { if (err) { return reject(new VError(err, 'CouchBackup process failed')); } debug('couchbackup to file done; uploading to S3'); resolve('creating backup file complete'); } ); }); }
javascript
{ "resource": "" }
q50356
uploadNewBackup
train
function uploadNewBackup(s3, backupTmpFilePath, bucket, key) { return new Promise((resolve, reject) => { debug(`Uploading from ${backupTmpFilePath} to ${bucket}/${key}`); function uploadFromStream(s3, bucket, key) { const pass = new stream.PassThrough(); const params = { Bucket: bucket, Key: key, Body: pass }; s3.upload(params, function(err, data) { debug('S3 upload done'); if (err) { debug(err); reject(new VError(err, 'Upload failed')); return; } debug('Upload succeeded'); debug(data); resolve(); }).httpUploadProgress = (progress) => { debug(`S3 upload progress: ${progress}`); }; return pass; } const inputStream = fs.createReadStream(backupTmpFilePath); const s3Stream = uploadFromStream(s3, bucket, key); inputStream.pipe(s3Stream); }); }
javascript
{ "resource": "" }
q50357
apiDefaults
train
function apiDefaults() { return { parallelism: 5, bufferSize: 500, requestTimeout: 120000, log: tmp.fileSync().name, resume: false, mode: 'full' }; }
javascript
{ "resource": "" }
q50358
processBuffer
train
function processBuffer(flush, callback) { function taskCallback(err, payload) { if (err && !didError) { debug(`Queue task failed with error ${err.name}`); didError = true; q.kill(); writer.emit('error', err); } } if (flush || buffer.length >= bufferSize) { // work through the buffer to break off bufferSize chunks // and feed the chunks to the queue do { // split the buffer into bufferSize chunks var toSend = buffer.splice(0, bufferSize); // and add the chunk to the queue debug(`Adding ${toSend.length} to the write queue.`); q.push({ docs: toSend }, taskCallback); } while (buffer.length >= bufferSize); // send any leftover documents to the queue if (flush && buffer.length > 0) { debug(`Adding remaining ${buffer.length} to the write queue.`); q.push({ docs: buffer }, taskCallback); } // wait until the queue size falls to a reasonable level async.until( // wait until the queue length drops to twice the paralellism // or until empty on the last write function() { // if we encountered an error, stop this until loop if (didError) { return true; } if (flush) { return q.idle() && q.length() === 0; } else { return q.length() <= parallelism * 2; } }, function(cb) { setTimeout(cb, 20); }, function() { if (flush && !didError) { writer.emit('finished', { total: written }); } // callback when we're happy with the queue size callback(); }); } else { callback(); } }
javascript
{ "resource": "" }
q50359
train
function() { // if we encountered an error, stop this until loop if (didError) { return true; } if (flush) { return q.idle() && q.length() === 0; } else { return q.length() <= parallelism * 2; } }
javascript
{ "resource": "" }
q50360
train
function(lastOne) { if (buffer.length >= bufferSize || (lastOne && buffer.length > 0)) { debug('writing', buffer.length, 'changes to the backup file'); var b = { docs: buffer.splice(0, bufferSize), batch: batch }; logStream.write(':t batch' + batch + ' ' + JSON.stringify(b.docs) + '\n'); ee.emit('changes', batch); batch++; } }
javascript
{ "resource": "" }
q50361
train
function(c) { if (c) { if (c.error) { ee.emit('error', new error.BackupError('InvalidChange', `Received invalid change: ${c}`)); } else if (c.changes) { var obj = { id: c.id }; buffer.push(obj); processBuffer(false); } else if (c.last_seq) { lastSeq = c.last_seq; } } }
javascript
{ "resource": "" }
q50362
train
function(n) { if (n == Infinity) { return 'Infinity'; } else if (n > 1e9) { n = Math.round(n/1e8); return n/10 + 'B'; } else if (n > 1e6) { n = Math.round(n/1e5); return n/10 + 'M'; } else if (n > 1e3) { n = Math.round(n/1e2); return n/10 + 'K'; } return n; }
javascript
{ "resource": "" }
q50363
train
function(count) { var me = this; // Make sure calibration tests have run if (!me.isCalibration && Test.calibrate(function() {me.run(count);})) return; this.error = null; try { var start, f = this.f, now, i = count; // Start the timer start = new Date(); // Now for the money shot. If this is a looping function ... if (this.loopArg) { // ... let it do the iteration itself f(count); } else { // ... otherwise do the iteration for it while (i--) f(); } // Get time test took (in secs) this.time = Math.max(1,new Date() - start)/1000; // Store iteration count and per-operation time taken this.count = count; this.period = this.time/count; // Do we need to do another run? this.running = this.time <= this.MIN_TIME; // ... if so, compute how many times we should iterate if (this.running) { // Bump the count to the nearest power of 2 var x = this.MIN_TIME/this.time; var pow = Math.pow(2, Math.max(1, Math.ceil(Math.log(x)/Math.log(2)))); count *= pow; if (count > this.MAX_COUNT) { throw new Error('Max count exceeded. If this test uses a looping function, make sure the iteration loop is working properly.'); } } } catch (e) { // Exceptions are caught and displayed in the test UI this.reset(); this.error = e; } // Figure out what to do next if (this.running) { me.run(count); } else { jsl.status(''); me.onStop(me); } // Finish up this.onChange(this); }
javascript
{ "resource": "" }
q50364
train
function(/**Boolean*/ normalize) { var p = this.period; // Adjust period based on the calibration test time if (normalize && !this.isCalibration) { var cal = Test.CALIBRATIONS[this.loopArg ? 0 : 1]; // If the period is within 20% of the calibration time, then zero the // it out p = p < cal.period*1.2 ? 0 : p - cal.period; } return Math.round(1/p); }
javascript
{ "resource": "" }
q50365
train
function() { var el = jsl.$('jslitmus_container'); if (!el) document.body.appendChild(el = document.createElement('div')); el.innerHTML = MARKUP; // Render the UI for all our tests for (var i=0; i < JSLitmus._tests.length; i++) JSLitmus.renderTest(JSLitmus._tests[i]); }
javascript
{ "resource": "" }
q50366
train
function(name, f) { // Create the Test object var test = new Test(name, f); JSLitmus._tests.push(test); // Re-render if the test state changes test.onChange = JSLitmus.renderTest; // Run the next test if this one finished test.onStop = function(test) { if (JSLitmus.onTestFinish) JSLitmus.onTestFinish(test); JSLitmus.currentTest = null; JSLitmus._nextTest(); }; // Render the new test this.renderTest(test); }
javascript
{ "resource": "" }
q50367
train
function(e) { e = e || window.event; var reverse = e && e.shiftKey, len = JSLitmus._tests.length; for (var i = 0; i < len; i++) { JSLitmus._queueTest(JSLitmus._tests[!reverse ? i : (len - i - 1)]); } }
javascript
{ "resource": "" }
q50368
train
function() { while (JSLitmus._queue.length) { var test = JSLitmus._queue.shift(); JSLitmus.renderTest(test); } }
javascript
{ "resource": "" }
q50369
train
function() { if (!JSLitmus.currentTest) { var test = JSLitmus._queue.shift(); if (test) { jsl.$('stop_button').disabled = false; JSLitmus.currentTest = test; test.run(); JSLitmus.renderTest(test); if (JSLitmus.onTestStart) JSLitmus.onTestStart(test); } else { jsl.$('stop_button').disabled = true; JSLitmus.renderChart(); } } }
javascript
{ "resource": "" }
q50370
train
function(test) { if (jsl.indexOf(JSLitmus._queue, test) >= 0) return; JSLitmus._queue.push(test); JSLitmus.renderTest(test); JSLitmus._nextTest(); }
javascript
{ "resource": "" }
q50371
train
function() { var n = JSLitmus._tests.length, markers = [], data = []; var d, min = 0, max = -1e10; var normalize = jsl.$('test_normalize').checked; // Gather test data for (var i=0; i < JSLitmus._tests.length; i++) { var test = JSLitmus._tests[i]; if (test.count) { var hz = test.getHz(normalize); var v = hz != Infinity ? hz : 0; data.push(v); markers.push('t' + jsl.escape(test.name + '(' + jsl.toLabel(hz)+ ')') + ',000000,0,' + markers.length + ',10'); max = Math.max(v, max); } } if (markers.length <= 0) return null; // Build chart title var title = document.getElementsByTagName('title'); title = (title && title.length) ? title[0].innerHTML : null; var chart_title = []; if (title) chart_title.push(title); chart_title.push('Ops/sec (' + platform + ')'); // Build labels var labels = [jsl.toLabel(min), jsl.toLabel(max)]; var w = 250, bw = 15; var bs = 5; var h = markers.length*(bw + bs) + 30 + chart_title.length*20; var params = { chtt: escape(chart_title.join('|')), chts: '000000,10', cht: 'bhg', // chart type chd: 't:' + data.join(','), // data set chds: min + ',' + max, // max/min of data chxt: 'x', // label axes chxl: '0:|' + labels.join('|'), // labels chsp: '0,1', chm: markers.join('|'), // test names chbh: [bw, 0, bs].join(','), // bar widths // chf: 'bg,lg,0,eeeeee,0,eeeeee,.5,ffffff,1', // gradient chs: w + 'x' + h }; return 'http://chart.apis.google.com/chart?' + jsl.join(params, '=', '&'); }
javascript
{ "resource": "" }
q50372
mapBreakpointToMedia
train
function mapBreakpointToMedia(stylesheet) { if (angular.isDefined(options.breakpoints)) { if (stylesheet.breakpoint in options.breakpoints) { stylesheet.media = options.breakpoints[stylesheet.breakpoint]; } delete stylesheet.breakpoints; } }
javascript
{ "resource": "" }
q50373
addViaMediaQuery
train
function addViaMediaQuery(stylesheet) { if (!stylesheet) { if(DEBUG) $log.error('No stylesheet provided'); return; } // Media query object mediaQuery[stylesheet.href] = $window.matchMedia(stylesheet.media); // Media Query Listener function mediaQueryListener[stylesheet.href] = function(mediaQuery) { // Trigger digest $timeout(function () { if (mediaQuery.matches) { // Add stylesheet $rootScope.stylesheets.push(stylesheet); } else { var index = $rootScope.stylesheets.indexOf($filter('filter')($rootScope.stylesheets, { href: stylesheet.href })[0]); // Remove stylesheet if (index !== -1) { $rootScope.stylesheets.splice(index, 1); } } }); }; // Listen for media query changes mediaQuery[stylesheet.href].addListener(mediaQueryListener[stylesheet.href]); // Invoke first media query check mediaQueryListener[stylesheet.href](mediaQuery[stylesheet.href]); }
javascript
{ "resource": "" }
q50374
removeViaMediaQuery
train
function removeViaMediaQuery(stylesheet) { if (!stylesheet) { if(DEBUG) $log.error('No stylesheet provided'); return; } // Remove media query listener if ($rootScope && angular.isDefined(mediaQuery) && mediaQuery[stylesheet.href] && angular.isDefined(mediaQueryListener)) { mediaQuery[stylesheet.href].removeListener(mediaQueryListener[stylesheet.href]); } }
javascript
{ "resource": "" }
q50375
requireReporter
train
function requireReporter(name) { const prefix = capitalize(camelcase(name)); const locations = [`./reporters/${prefix}Reporter`, name, path.resolve(name)]; let result = null; for (const location of locations) { try { // eslint-disable-next-line import/no-dynamic-require, global-require result = require(location); } catch (e) { // noop } if (result) { break; } } return result; }
javascript
{ "resource": "" }
q50376
sanitize
train
function sanitize(config) { const configs = [].concat(config).map((conf) => { const result = merge({}, conf); delete result.progress; delete result.reporter; delete result.watchStdin; // TODO: remove the need for this for (const property of ['entry', 'output']) { const target = result[property]; if (target && Object.keys(target).length === 0) { delete result[property]; } } return result; }); // if we always return an array, every compilation will be a MultiCompiler return configs.length > 1 ? configs : configs[0]; }
javascript
{ "resource": "" }
q50377
minusJS
train
function minusJS(name) { var idx = name.indexOf(".js"); return idx === -1 ? name : name.substr(0, idx); }
javascript
{ "resource": "" }
q50378
getLoader
train
function getLoader(data) { if(typeof Loader !== "undefined" && (data instanceof global.Loader)) { return data; } else if(typeof LoaderPolyfill !== "undefined" && (data instanceof global.LoaderPolyfill)) { return data; } else { return data.steal.System; } }
javascript
{ "resource": "" }
q50379
adjustBundlesPath
train
function adjustBundlesPath(data, options) { var path = require("path"); var configuration = clone(data.configuration); var bundlesPath = configuration.bundlesPath; Object.defineProperty(configuration, "bundlesPath", { configurable: true, get: function() { return path.join(bundlesPath, options.target); } }); return assign({}, omit(data, ["configuration"]), { configuration: configuration }); }
javascript
{ "resource": "" }
q50380
mergeIntoMasterAndAddBundle
train
function mergeIntoMasterAndAddBundle(opts) { var mains = opts.mains; var loader = opts.loader; var newGraph = opts.newGraph; var bundleName = opts.bundleName; var masterGraph = opts.masterGraph; for(var name in newGraph) { var oldNode = masterGraph[name]; var newNode = newGraph[name]; if(!oldNode || hasNewDeps(oldNode, newNode)) { masterGraph[name] = newGraph[name]; } // If it's a plugin we'll use the new node but need to copy any previous // bundles onto the new node else if(masterGraph[name] && masterGraph[name].isPlugin) { var oldBundle = masterGraph[name].bundles || []; masterGraph[name] = newGraph[name]; oldBundle.forEach(function(bundle){ addBundle(masterGraph[name], bundle); }); } // If this is the configMain like package.json!npm we need to override // the source every time because it continuously changes. else if(masterGraph[name] && name === loader.configMain) { var node = masterGraph[name]; node.load.source = newGraph[name].load.source; } // do not track bundles of entry point modules (a.k.a mains) unless // it is its own bundle. if (name === bundleName || !includes(mains, name)) { addBundle(masterGraph[name], bundleName); } } }
javascript
{ "resource": "" }
q50381
createModuleConfig
train
function createModuleConfig(loader) { var tmp = require("tmp"); var config = {}; var virtualModules = loader.virtualModules || {}; for(var moduleName in virtualModules) { var filename = tmp.fileSync().name; var source = virtualModules[moduleName]; fs.writeFileSync(filename, source, "utf8"); var paths = config.paths = config.paths || {}; paths[moduleName] = "file:"+filename; } return config; }
javascript
{ "resource": "" }
q50382
copyIfSet
train
function copyIfSet(src, dest, prop) { if (src[prop]) { dest[prop] = src[prop]; } }
javascript
{ "resource": "" }
q50383
addPluginName
train
function addPluginName(data) { var loader = data.loader; var bundles = data.bundles; var promises = bundles.map(function(bundle) { if (!isJavaScriptBundle(bundle)) { return loader.normalize(bundle.name).then(function(name) { bundle.pluginName = name.substring(name.indexOf("!") + 1); }); } }); return Promise.all(promises).then(function() { return data; }); }
javascript
{ "resource": "" }
q50384
getWeightOf
train
function getWeightOf(bundle) { var isCss = bundle.buildType === "css"; var isMainBundle = bundle.bundles.length === 1; if (isCss) { return 1; } else if (isMainBundle) { return 2; } else { return 3; } }
javascript
{ "resource": "" }
q50385
getSharedBundlesOf
train
function getSharedBundlesOf(name, baseUrl, bundles, mains) { var shared = {}; var normalize = require("normalize-path"); // this will ensure that we only add the main bundle if there is a single // main; not a multi-main project. var singleMain = mains.length === 1 && mains[0]; bundles.forEach(function(bundle) { if (includes(bundle.bundles, name) || includes(bundle.bundles, singleMain)) { var relative = normalize( path.relative( baseUrl.replace("file:", ""), bundle.bundlePath ) ); shared[relative] = { weight: getWeightOf(bundle), type: isJavaScriptBundle(bundle) ? "script" : "style" }; } }); return shared; }
javascript
{ "resource": "" }
q50386
getBundlesPaths
train
function getBundlesPaths(configuration){ // If a bundlesPath is not provided, the paths are not needed because they are // already set up in steal.js if(!configuration.loader.bundlesPath) { return ""; } var bundlesPath = configuration.bundlesPathURL; // Get the dist directory and set the paths output var paths = util.format('\tSystem.paths["bundles/*.css"] ="%s/*css";\n' + '\tSystem.paths["bundles/*"] = "%s/*.js";\n', bundlesPath, bundlesPath); return "if(!System.bundlesPath) {\n" + paths + "}\n"; }
javascript
{ "resource": "" }
q50387
regenerate
train
function regenerate(moduleName, done){ var cfg = clone(config, true); // if the moduleName is not in the graph, make it the main. if(moduleName && !cachedData.graph[moduleName]) { cfg.main = moduleName; } makeBundleGraph(cfg, options).then(function(data){ var graph = data.graph; var oldGraph = cachedData ? cachedData.graph : {}; for(var name in graph){ if(name !== moduleName && oldGraph[name]) { graph[name].transforms = oldGraph[name].transforms; } } cachedData = cloneData(data); done(null, data); }, done); }
javascript
{ "resource": "" }
q50388
diff
train
function diff(node) { var oldBundle = (cachedData.loader.bundle || []).slice(); return getDependencies(node.load).then(function(result){ var newBundle = (cachedData.loader.bundle || []).slice(); // If the deps are the same we can return the existing graph. if(same(node.deps, result.deps) && same(oldBundle, newBundle)) { clean(node, result.source); if(result.virtualModules.length) { var promises = result.virtualModules.map(function(l){ var node = cachedData.graph[l.name]; node.load.source = l.source; node.load.metadata.useSource = true; return diff(node); }); return Promise.all(promises).then(function(results){ result.same = results.every(function(res){ return res.same; }); return result; }); } result.same = true; } return result; }); }
javascript
{ "resource": "" }
q50389
inlineNodeEnvironmentVariables
train
function inlineNodeEnvironmentVariables(data) { var dependencyGraph = data.graph; var configuration = data.configuration; var options = configuration.options; if (options.envify) { winston.info("Inlining Node-style environment variables..."); envifyGraph(dependencyGraph, options); envifyGraph(data.configGraph, options); } return data; }
javascript
{ "resource": "" }
q50390
getPresetName
train
function getPresetName(preset) { if (includesPresetName(preset)) { return _.isString(preset) ? preset : _.head(preset); } else { return null; } }
javascript
{ "resource": "" }
q50391
includesPresetName
train
function includesPresetName(preset) { return _.isString(preset) || _.isArray(preset) && _.isString(_.head(preset)); }
javascript
{ "resource": "" }
q50392
isBuiltinPreset
train
function isBuiltinPreset(name) { var isNpmPresetName = /^(?:babel-preset-)/; var availablePresets = babel.availablePresets || {}; var shorthand = isNpmPresetName.test(name) ? name.replace("babel-preset-", "") : name; return !!availablePresets[shorthand]; }
javascript
{ "resource": "" }
q50393
loadNodeBuilder
train
function loadNodeBuilder(data) { return new Promise(function(resolve, reject) { var graph = data.graph; var loader = data.loader; var promises = keys(graph).map(function(nodeName) { var node = graph[nodeName]; // pluginBuilder | extensionBuilder is a module identifier that // should be loaded to replace the node's source during the build var nodeBuilder = node.value && (node.value.pluginBuilder || node.value.extensionBuilder); // nothing to do in this case, return right away if (!nodeBuilder) return; return loader .normalize(nodeBuilder) .then(locate) .then(_fetch) .then(makeReplace(node)); }); function locate(name) { return Promise.all([name, loader.locate({ name: name, metadata: {} })]); } // [ name, address ] function _fetch(data) { return Promise.all([ data[1], loader.fetch({ name: data[0], address: data[1], metadata: {} }) ]); } function makeReplace(node) { // [ address, load ] return function replace(data) { node.load = assign(node.load, { address: data[0], source: data[1], metadata: {} }); }; } Promise.all(promises) .then(function() { resolve(graph); }) .catch(reject); }); }
javascript
{ "resource": "" }
q50394
normalize
train
function normalize(loader, mods) { var modNames = (mods && !Array.isArray(mods)) ? [mods] : mods; return (modNames || []).map(function(moduleName) { return !_.isString(moduleName) ? Promise.resolve(moduleName) : loader.normalize(moduleName); }); }
javascript
{ "resource": "" }
q50395
isExcludedFromBuild
train
function isExcludedFromBuild(node) { if (node.load.excludeFromBuild) { return true; } if ( node.load.metadata && node.load.metadata.hasOwnProperty("bundle") && node.load.metadata.bundle === false ) { return true; } if ( node.isPlugin && !node.value.includeInBuild && !node.load.metadata.includeInBuild ) { return true; } return false; }
javascript
{ "resource": "" }
q50396
ignoredMetas
train
function ignoredMetas(cfgs, metas){ cfgs = cfgs || {}; Object.keys(metas).forEach(function(name){ var cfg = metas[name]; if(cfg && cfg.bundle === false) { cfgs[name] = cfg; } }); return { meta: cfgs }; }
javascript
{ "resource": "" }
q50397
processPlugins
train
function processPlugins(baseURL, plugins) { var normalized = []; // path.resolve does not work correctly if baseURL starts with "file:" baseURL = baseURL.replace("file:", ""); plugins = plugins || []; plugins.forEach(function(plugin) { var name = getPluginName(plugin); if (isPluginFunction(plugin) || isBuiltinPlugin(name)) { normalized.push(plugin); } else if (!isBuiltinPlugin(name)) { var npmPluginNameOrPath = getNpmPluginNameOrPath(baseURL, name); // load the plugin! var pluginFn = require(npmPluginNameOrPath); if (_.isString(plugin)) { normalized.push(pluginFn); } else if (_.isArray(plugin)) { // [ pluginName, pluginOptions ] normalized.push([pluginFn, plugin[1]]); } } }); return normalized; }
javascript
{ "resource": "" }
q50398
isPluginFunction
train
function isPluginFunction(plugin) { return _.isFunction(plugin) || _.isFunction(_.head(plugin)); }
javascript
{ "resource": "" }
q50399
getPluginName
train
function getPluginName(plugin) { if (isPluginFunction(plugin)) return null; return _.isString(plugin) ? plugin : _.head(plugin); }
javascript
{ "resource": "" }