_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q12200
train
function (req, res) { var query = req.query; if (this.omit.length) { query = _.omit(query, this.omit); } query = this.model.find(query); if (this.lean) { query.lean(); } if (this.select.length) { query.select(this.select.join(' ')); } this.populateQuery(query, this.filterPopulations('index')); query.exec(function (err, documents) { if (err) { return res.handleError(err); } return res.ok(documents); }); }
javascript
{ "resource": "" }
q12201
train
function (req, res) { var self = this; var populations = self.filterPopulations('create'); this.model.populate(req.body, populations, function (err, populated) { if (err) { return res.handleError(err); } self.model.create(populated, function (err, document) { if (err) { return res.handleError(err); } populated._id = document._id; return res.created(self.getResponseObject(populated)); }) }); }
javascript
{ "resource": "" }
q12202
setResponseErrors
train
function setResponseErrors(err, obj) { /* jshint validthis: true */ var self = this; obj = obj || {}; if (err.data && err.data.errors) { err = err.data.errors; } if (err.errors) { err = err.errors; } angular.forEach(err, function (error, field) { if (self[field]) { self[field].$setValidity('mongoose', false); } obj[field] = error.type; }); }
javascript
{ "resource": "" }
q12203
CustomHtml
train
function CustomHtml(options) { this.button = document.createElement('button'); this.button.className = 'medium-editor-action'; if (this.button.innerText) { this.button.innerText = options.buttonText || "</>"; } else { this.button.textContent = options.buttonText || "</>"; } this.button.onclick = this.onClick.bind(this); this.options = options; }
javascript
{ "resource": "" }
q12204
registerClientModelDocSockets
train
function registerClientModelDocSockets(socket) { ClientModelDoc.schema.post('save', function (doc) { onSave(socket, doc); }); ClientModelDoc.schema.post('remove', function (doc) { onRemove(socket, doc); }); }
javascript
{ "resource": "" }
q12205
update
train
function update(form) { // refuse to work with invalid data if (!vm.clientModelDoc._id || form && !form.$valid) { return; } ClientModelDocService.update(vm.clientModelDoc) .then(updateClientModelDocSuccess) .catch(updateClientModelDocCatch); function updateClientModelDocSuccess(updatedClientModelDoc) { // update the display name after successful save vm.displayName = updatedClientModelDoc.name; Toast.show({text: 'ClientModelDoc ' + vm.displayName + ' updated'}); if (form) { form.$setPristine(); } } function updateClientModelDocCatch(err) { Toast.show({ type: 'warn', text: 'Error while updating ClientModelDoc ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err.data); } } }
javascript
{ "resource": "" }
q12206
remove
train
function remove(form, ev) { var confirm = $mdDialog.confirm() .title('Delete clientModelDoc ' + vm.displayName + '?') .content('Do you really want to delete clientModelDoc ' + vm.displayName + '?') .ariaLabel('Delete clientModelDoc') .ok('Delete clientModelDoc') .cancel('Cancel') .targetEvent(ev); $mdDialog.show(confirm) .then(performRemove); /** * Removes a clientModelDoc by using the ClientModelDocService remove method * @api private */ function performRemove() { ClientModelDocService.remove(vm.clientModelDoc) .then(deleteClientModelDocSuccess) .catch(deleteClientModelDocCatch); function deleteClientModelDocSuccess() { Toast.show({type: 'success', text: 'ClientModelDoc ' + vm.displayName + ' deleted'}); vm.showList(); } function deleteClientModelDocCatch(err) { Toast.show({ type: 'warn', text: 'Error while deleting clientModelDoc ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err, vm.errors); } } } }
javascript
{ "resource": "" }
q12207
performRemove
train
function performRemove() { ClientModelDocService.remove(vm.clientModelDoc) .then(deleteClientModelDocSuccess) .catch(deleteClientModelDocCatch); function deleteClientModelDocSuccess() { Toast.show({type: 'success', text: 'ClientModelDoc ' + vm.displayName + ' deleted'}); vm.showList(); } function deleteClientModelDocCatch(err) { Toast.show({ type: 'warn', text: 'Error while deleting clientModelDoc ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err, vm.errors); } } }
javascript
{ "resource": "" }
q12208
ParamController
train
function ParamController(model, idName, paramName, router) { var modelName = model.modelName.toLowerCase(); // make idName and paramName arguments optional (v0.1.1) if (typeof idName === 'function') { router = idName; idName = modelName + 'Id'; } if (typeof paramName === 'function') { router = paramName; paramName = modelName + 'Param'; } // call super constructor CrudController.call(this, model, idName); // only set param if it is set, will default to 'id' if (!paramName) { paramName = modelName + 'Param'; } this.paramName = String(paramName); this.paramString = ':' + this.paramName; // register param name route parameter router.param(this.paramName, this.registerRequestParameter); }
javascript
{ "resource": "" }
q12209
train
function (req, res, next, id) { var self = this; // check if a custom id is used, when not only process a valid object id if (this.mongoId && !ObjectID.isValid(id)) { res.badRequest(); return next(); } // attach the document as this.paramName to the request this.model.findOne({'_id': id}, function (err, doc) { if (err) { return next(err); } if (!doc) { res.notFound(); return next('route'); } req[self.paramName] = doc; return next(); }); }
javascript
{ "resource": "" }
q12210
ToggleComponentService
train
function ToggleComponentService($mdComponentRegistry, $log, $q) { return function (contentHandle) { var errorMsg = "ToggleComponent '" + contentHandle + "' is not available!"; var instance = $mdComponentRegistry.get(contentHandle); if (!instance) { $log.error('No content-switch found for handle ' + contentHandle); } return { isOpen: isOpen, toggle: toggle, open: open, close: close }; function isOpen() { return instance && instance.isOpen(); } function toggle() { return instance ? instance.toggle() : $q.reject(errorMsg); } function open() { return instance ? instance.open() : $q.reject(errorMsg); } function close() { return instance ? instance.close() : $q.reject(errorMsg); } }; }
javascript
{ "resource": "" }
q12211
isAuthenticated
train
function isAuthenticated() { return compose() // Validate jwt .use(function (req, res, next) { // allow access_token to be passed through query parameter as well if (req.query && req.query.hasOwnProperty('access_token')) { req.headers.authorization = 'Bearer ' + req.query.access_token; } validateJwt(req, res, next); }) .use(function (req, res, next) { // Attach userInfo to request // return if this request has already been authorized if (req.hasOwnProperty('userInfo')) { return next(); } // load user model on demand var User = require('../../api/user/user.model').model; // read the user id from the token information provided in req.user User.findOne({_id: req.user._id, active: true}, function (err, user) { if (err) { return next(err); } if (!user) { res.unauthorized(); return next(); } // set the requests userInfo object as the authenticated user req.userInfo = user; next(); }); }); }
javascript
{ "resource": "" }
q12212
hasRole
train
function hasRole(roleRequired) { if (!roleRequired) { throw new Error('Required role needs to be set'); } return compose() .use(isAuthenticated()) .use(function meetsRequirements(req, res, next) { if (roles.hasRole(req.userInfo.role, roleRequired)) { next(); } else { res.forbidden(); } }); }
javascript
{ "resource": "" }
q12213
signToken
train
function signToken(id, role) { return jwt.sign({_id: id, role: role}, config.secrets.session, {expiresInMinutes: 60 * 5}); }
javascript
{ "resource": "" }
q12214
addAuthContext
train
function addAuthContext(namespace) { if (!namespace) { throw new Error('No context namespace specified!'); } return function addAuthContextMiddleWare(req, res, next) { contextService.setContext(namespace, req.userInfo); next(); }; }
javascript
{ "resource": "" }
q12215
request
train
function request(config) { config.headers = config.headers || {}; if ($cookieStore.get('token')) { config.headers.Authorization = 'Bearer ' + $cookieStore.get('token'); } return config; }
javascript
{ "resource": "" }
q12216
responseError
train
function responseError(response) { if (response.status === 401) { // remove any stale tokens $cookieStore.remove('token'); // use timeout to perform location change // in the next digest cycle $timeout(function () { $location.path('/login'); }, 0); return $q.reject(response); } return $q.reject(response); }
javascript
{ "resource": "" }
q12217
initExpress
train
function initExpress(app) { var env = app.get('env'); var publicDir = path.join(config.root, config.publicDir); app.set('ip', config.ip); app.set('port', config.port); app.set('views', config.root + '/server/views'); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); app.use(compression()); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(methodOverride()); app.use(cookieParser()); app.use(passport.initialize()); app.use(favicon(path.join(publicDir, 'favicon.ico'))); if ('production' === env) { app.use(express.static(publicDir)); app.set('appPath', publicDir); app.use(morgan('tiny')); } if ('development' === env || 'test' === env) { app.use(express.static(path.join(config.root, '.tmp'))); app.use(express.static(publicDir)); app.set('appPath', publicDir); app.use(morgan('dev')); // Error handler - has to be last app.use(errorHandler()); } }
javascript
{ "resource": "" }
q12218
syncUpdates
train
function syncUpdates(modelName, array, cb) { cb = cb || angular.noop; /** * Syncs item creation/updates on 'model:save' */ socket.on(modelName + ':save', function (item) { var index = _.findIndex(array, {_id: item._id}); var event = 'created'; // replace oldItem if it exists // otherwise just add item to the collection if (index !== -1) { array.splice(index, 1, item); event = 'updated'; } else { array.push(item); } cb(event, item, array); }); /** * Syncs removed items on 'model:remove' */ socket.on(modelName + ':remove', function (item) { var event = 'deleted'; _.remove(array, {_id: item._id}); cb(event, item, array); }); }
javascript
{ "resource": "" }
q12219
registerUserSockets
train
function registerUserSockets(socket) { User.schema.post('save', function (doc) { onSave(socket, doc); }); User.schema.post('remove', function (doc) { onRemove(socket, doc); }); }
javascript
{ "resource": "" }
q12220
update
train
function update(form) { // refuse to work with invalid data if (!vm.user._id || form && !form.$valid) { return; } UserService.update(vm.user) .then(updateUserSuccess) .catch(updateUserCatch); function updateUserSuccess(updatedUser) { // update the display name after successful save vm.displayName = updatedUser.name; Toast.show({text: 'User ' + updatedUser.name + ' updated'}); if (form) { form.$setPristine(); } } function updateUserCatch(err) { Toast.show({ type: 'warn', text: 'Error while updating user ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err.data); } } }
javascript
{ "resource": "" }
q12221
remove
train
function remove(form, ev) { var confirm = $mdDialog.confirm() .title('Delete user ' + vm.displayName + '?') .content('Do you really want to delete user ' + vm.displayName + '?') .ariaLabel('Delete user') .ok('Delete user') .cancel('Cancel') .targetEvent(ev); $mdDialog.show(confirm) .then(performRemove); /** * Removes a user by using the UserService remove method * @api private */ function performRemove() { UserService.remove(vm.user) .then(deleteUserSuccess) .catch(deleteUserCatch); function deleteUserSuccess() { Toast.show({type: 'success', text: 'User ' + vm.displayName + ' deleted'}); vm.showList(); } function deleteUserCatch(err) { Toast.show({ type: 'warn', text: 'Error while deleting user ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err, vm.errors); } } } }
javascript
{ "resource": "" }
q12222
performRemove
train
function performRemove() { UserService.remove(vm.user) .then(deleteUserSuccess) .catch(deleteUserCatch); function deleteUserSuccess() { Toast.show({type: 'success', text: 'User ' + vm.displayName + ' deleted'}); vm.showList(); } function deleteUserCatch(err) { Toast.show({ type: 'warn', text: 'Error while deleting user ' + vm.displayName, link: {state: $state.$current, params: $stateParams} }); if (form && err) { form.setResponseErrors(err, vm.errors); } } }
javascript
{ "resource": "" }
q12223
showChangePasswordDialog
train
function showChangePasswordDialog(event) { $mdDialog.show({ controller: 'EditPasswordController', controllerAs: 'password', templateUrl: 'app/admin/user/list/edit/edit-password/edit-password.html', targetEvent: event, locals: {user: vm.user}, bindToController: true, clickOutsideToClose: false }); }
javascript
{ "resource": "" }
q12224
sendData
train
function sendData(data, options) { // jshint validthis: true var req = this.req; var res = this.res; // headers already sent, nothing to do here if (res.headersSent) { return; } // If appropriate, serve data as JSON if (req.xhr || req.accepts('application/json')) { return res.json(data); } // if a template string is given as the options param // use it to render a view var viewFilePath = (typeof options === 'string') ? options : options.view; // try to render the given template, fall back to json // if an error occurs while rendering the view file if (viewFilePath && req.accepts('html')) { res.render(viewFilePath, data, function (err, result) { if (err) { return res.json(data); } return res.send(result); }); } return res.json(data); }
javascript
{ "resource": "" }
q12225
toggleOpen
train
function toggleOpen(isOpen) { if (scope.isOpen === isOpen) { return $q.when(true); } var deferred = $q.defer(); // Toggle value to force an async `updateIsOpen()` to run scope.isOpen = isOpen; $timeout(setElementFocus, 0, false); return deferred.promise; function setElementFocus() { // When the current `updateIsOpen()` animation finishes promise.then(function (result) { if (!scope.isOpen) { // reset focus to originating element (if available) upon close triggeringElement && triggeringElement.focus(); triggeringElement = null; } deferred.resolve(result); }); } }
javascript
{ "resource": "" }
q12226
ClientModelDocService
train
function ClientModelDocService(ClientModelDoc) { return { create: create, update: update, remove: remove }; /** * Save a new clientModelDoc * * @param {Object} clientModelDoc - clientModelDocData * @param {Function} callback - optional * @return {Promise} */ function create(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.create(clientModelDoc, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; } /** * Remove a clientModelDoc * * @param {Object} clientModelDoc - clientModelDocData * @param {Function} callback - optional * @return {Promise} */ function remove(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.remove({id: clientModelDoc._id}, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; } /** * Create a new clientModelDoc * * @param {Object} clientModelDoc - clientModelDocData * @param {Function} callback - optional * @return {Promise} */ function update(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.update(clientModelDoc, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; } }
javascript
{ "resource": "" }
q12227
create
train
function create(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.create(clientModelDoc, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; }
javascript
{ "resource": "" }
q12228
remove
train
function remove(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.remove({id: clientModelDoc._id}, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; }
javascript
{ "resource": "" }
q12229
update
train
function update(clientModelDoc, callback) { var cb = callback || angular.noop; return ClientModelDoc.update(clientModelDoc, function (clientModelDoc) { return cb(clientModelDoc); }, function (err) { return cb(err); }).$promise; }
javascript
{ "resource": "" }
q12230
startServer
train
function startServer() { var server = require('http').createServer(app); var socket = socketio(server, { serveClient: true, path: '/socket.io-client' }); // Setup SocketIO socketConfig(socket); return server; }
javascript
{ "resource": "" }
q12231
passphraseToKey
train
function passphraseToKey(type, passphrase, salt) { debug('passphraseToKey', type, passphrase, salt); var nkey = keyBytes[type]; if (!nkey) { var allowed = Object.keys(keyBytes); throw new TypeError('Unsupported type. Allowed: ' + allowed); } var niv = salt.length; var saltLen = 8; if (salt.length !== saltLen) salt = salt.slice(0, saltLen); var mds = 16; var addmd = false; var md_buf; var key = new Buffer(nkey); var keyidx = 0; while (true) { debug('loop nkey=%d mds=%d', nkey, mds); var c = crypto.createHash('md5'); if (addmd) c.update(md_buf); else addmd = true; if (!Buffer.isBuffer(passphrase)) c.update(passphrase, 'ascii'); else c.update(passphrase); c.update(salt); md_buf = c.digest('buffer'); var i = 0; while (nkey && i < mds) { key[keyidx++] = md_buf[i]; nkey--; i++; } var steps = Math.min(niv, mds - i); niv -= steps; i += steps; if ((nkey == 0) && (niv == 0)) break; } return key }
javascript
{ "resource": "" }
q12232
verifyToken
train
function verifyToken(token) { var decodedToken = jwt.decode(token) return userdb.users.filter(user => user.name == decodedToken).length > 0; }
javascript
{ "resource": "" }
q12233
convertImports
train
function convertImports(imports) { for (var file in imports) { if (imports.hasOwnProperty(file)) { postCssInputs[file] = new Input(imports[file], file !== "input" ? { from: file } : undefined); } } }
javascript
{ "resource": "" }
q12234
train
function(directive) { var filename = directive.path ? directive.path.currentFileInfo.filename : directive.currentFileInfo.filename; var val, node, nodeTmp = buildNodeObject(filename, directive.index); if(!directive.path) { if(directive.features) { val = getObject(directive.features, true).stringValue; } else { val = getObject(directive.value, true).stringValue; } } else { val = directive.path.quote + directive.path.value + directive.path.quote; } node = { type: "" }; if(directive.type === 'Media') { node.name = 'media'; } else if(directive.type === 'Import') { node.name = 'import'; } else { // Remove "@" for PostCSS node.name = directive.name.replace('@',''); } node.source = nodeTmp.source; node.params = val; var atrule = postcss.atRule(node); if(directive.rules) { atrule.nodes = []; processRules(atrule, directive.rules); } return atrule; }
javascript
{ "resource": "" }
q12235
train
function( methodStr ){ var parts = methodStr.split('['), definition = { name: parts[0], args: [] }, args ; if( parts.length > 1 ){ args = parts[1]; if( args[ args.length - 1 ] == ']' ) args = args.slice(0, args.length - 1); definition.args = args.split(/\s*,\s*/); } return definition; }
javascript
{ "resource": "" }
q12236
train
function( field ){ var tagName = field.tagName.toLowerCase(); if( tagName == 'input' && field.type == 'checkbox' ){ return field.checked; } if( tagName == 'select' ){ return field.options[field.selectedIndex].value; } return field.value; }
javascript
{ "resource": "" }
q12237
train
function( key ){ var fields = this.state.fields; if( fields[ key ] && fields[ key ].settings.focus === true ){ fields = assign({}, fields); fields[key].settings.focus = false; this.setState( {fields: fields} ); } }
javascript
{ "resource": "" }
q12238
train
function(kgraph) { if (kgraph) { zoomToFit(kgraph); // assign coordinates to nodes kgraph.children.forEach(function(n) { var d3node = nodes[parseInt(n.id)]; copyProps(n, d3node); (n.ports || []).forEach(function(p, i) { copyProps(p, d3node.ports[i]); }); (n.labels || []).forEach(function(l, i) { copyProps(l, d3node.labels[i]); }); }); // edges kgraph.edges.forEach(function(e) { var l = links[parseInt(e.id) - nodes.length]; copyProps(e, l); copyProps(e.source, l.source); copyProps(e.target, l.target); // make sure the bendpoint array is valid l.bendPoints = e.bendPoints || []; }); } function copyProps(src, tgt, copyKeys) { var keys = kgraphKeys; if (copyKeys) { keys = copyKeys.reduce(function (p, c) {p[c] = 1; return p;}, {}); } for (var k in src) { if (keys[k]) { tgt[k] = src[k]; } } } // invoke the 'finish' event dispatch.finish({graph: kgraph}); }
javascript
{ "resource": "" }
q12239
train
function(kgraph) { zoomToFit(kgraph); var nodeMap = {}; // convert to absolute positions toAbsolutePositions(kgraph, {x: 0, y:0}, nodeMap); toAbsolutePositionsEdges(kgraph, nodeMap); // invoke the 'finish' event dispatch.finish({graph: kgraph}); }
javascript
{ "resource": "" }
q12240
zoomToFit
train
function zoomToFit(kgraph) { // scale everything so that it fits the specified size var scale = width / kgraph.width || 1; var sh = height / kgraph.height || 1; if (sh < scale) { scale = sh; } // if a transformation group was specified we // perform a 'zoomToFit' if (transformGroup) { transformGroup.attr("transform", "scale(" + scale + ")"); } }
javascript
{ "resource": "" }
q12241
RegExpStringIterator
train
function RegExpStringIterator(R, S, global, fullUnicode) { if (ES.Type(S) !== 'String') { throw new TypeError('S must be a string'); } if (ES.Type(global) !== 'Boolean') { throw new TypeError('global must be a boolean'); } if (ES.Type(fullUnicode) !== 'Boolean') { throw new TypeError('fullUnicode must be a boolean'); } hidden.set(this, '[[IteratingRegExp]]', R); hidden.set(this, '[[IteratedString]]', S); hidden.set(this, '[[Global]]', global); hidden.set(this, '[[Unicode]]', fullUnicode); hidden.set(this, '[[Done]]', false); }
javascript
{ "resource": "" }
q12242
buildChunksSort
train
function buildChunksSort( order ) { return (a, b) => order.indexOf(a.names[0]) - order.indexOf(b.names[0]); }
javascript
{ "resource": "" }
q12243
minValueNode
train
function minValueNode(root) { var current = root; while (current.left) { current = current.left; } return current; }
javascript
{ "resource": "" }
q12244
maxValueNode
train
function maxValueNode(root) { var current = root; while (current.right) { current = current.right; } return current; }
javascript
{ "resource": "" }
q12245
getBalanceState
train
function getBalanceState(node) { var heightDifference = node.leftHeight() - node.rightHeight(); switch (heightDifference) { case -2: return BalanceState.UNBALANCED_RIGHT; case -1: return BalanceState.SLIGHTLY_UNBALANCED_RIGHT; case 1: return BalanceState.SLIGHTLY_UNBALANCED_LEFT; case 2: return BalanceState.UNBALANCED_LEFT; default: return BalanceState.BALANCED; } }
javascript
{ "resource": "" }
q12246
UrlNode
train
function UrlNode(data){ this.append = function(next){ this.next = next; }; this.getData = function(){ return this.data; }; this.setData = function(data){ this.data = data; } this.getNext = function(){ return this.next; }; this.setParams = function(params){ var queryParameters = params.split("&"); if(queryParameters != null){ this.params = []; for(var counter = 0; counter < queryParameters.length; counter++) { var keyValuePair = queryParameters[counter].split("="); this.params[keyValuePair[0]] = keyValuePair[1]; } } else{ queryParameters = null; } }; this.getParams = function(){ return this.params; }; //set var's for this object var queryParamSplit = data.split("?"); this.params = null; this.data = null; this.next = null; if(queryParamSplit != null && queryParamSplit.length > 1){ this.setData(queryParamSplit[0]); this.setParams(queryParamSplit[1]); } else{ this.setData(data); } }
javascript
{ "resource": "" }
q12247
train
function (key, value) { this.left = null; this.right = null; this.height = null; this.key = key; this.value = value; }
javascript
{ "resource": "" }
q12248
train
function (event, method) { if (methods.indexOf(method.toUpperCase()) !== -1) { showLoader = (event.name === 'loaderShow'); } else if (methods.length === 0) { showLoader = (event.name === 'loaderShow'); } if (ttl <= 0 || (!timeoutId && !showLoader)) { $scope.showLoader = showLoader; return; } if (timeoutId) { return; } $scope.showLoader = showLoader; timeoutId = $timeout(function () { if (!showLoader) { $scope.showLoader = showLoader; } timeoutId = undefined; }, ttl); }
javascript
{ "resource": "" }
q12249
train
function (url) { if (url.substring(0, 2) !== '//' && url.indexOf('://') === -1 && whitelistLocalRequests) { return true; } for (var i = domains.length; i--;) { if (url.indexOf(domains[i]) !== -1) { return true; } } return false; }
javascript
{ "resource": "" }
q12250
train
function (config) { if (isUrlOnWhitelist(config.url)) { numLoadings++; $rootScope.$emit('loaderShow', config.method); } return config || $q.when(config); }
javascript
{ "resource": "" }
q12251
outputPath
train
function outputPath(options, source) { var DEBUG = false; if (DEBUG) console.log('sourceFolder: ' + options.sourceFolder); var globBase = options.sourceFolder.replace(/\*.*/, ''); if (globBase.endsWith('.sol')) // single file globBase = path.join(globBase, '../'); if (DEBUG) console.log('globBase: ' + globBase); var optDestination = options.destinationFolder ? options.destinationFolder : globBase; if (DEBUG) console.log('optDestination: ' + optDestination); var destinationFolder = path.join(globBase, optDestination); if (optDestination === globBase) destinationFolder = globBase; if (DEBUG) console.log('destinationFolder: ' + destinationFolder); // destination-folder is absolut if (options.destinationFolder && options.destinationFolder.startsWith('/')) destinationFolder = path.join(options.destinationFolder, './'); var fileNameRelative = source.filename.replace(globBase, ''); if (DEBUG) console.log('fileNameRelative: ' + fileNameRelative); var goalPath = path.join(destinationFolder, fileNameRelative); return goalPath; }
javascript
{ "resource": "" }
q12252
generateOutput
train
function generateOutput(source) { return __awaiter(this, void 0, void 0, function () { var isCached, artifact, compiled, artifact, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, caching.has(source.codeHash)]; case 1: isCached = _b.sent(); if (!isCached) return [3 /*break*/, 3]; return [4 /*yield*/, caching.get(source.codeHash)]; case 2: artifact = _b.sent(); return [2 /*return*/, artifact]; case 3: return [4 /*yield*/, solc_install_1.installVersion(source.solcVersion)]; case 4: _b.sent(); return [4 /*yield*/, compile_1.default(source)]; case 5: compiled = _b.sent(); _a = { compiled: compiled }; return [4 /*yield*/, output_files_1.createJavascriptFile(source, compiled)]; case 6: _a.javascript = _b.sent(); return [4 /*yield*/, output_files_1.createTypescriptFile(source, compiled)]; case 7: artifact = (_a.typescript = _b.sent(), _a); return [4 /*yield*/, caching.set(source.codeHash, artifact)]; case 8: _b.sent(); return [2 /*return*/, artifact]; } }); }); }
javascript
{ "resource": "" }
q12253
getSourceCode
train
function getSourceCode(fileName) { return __awaiter(this, void 0, void 0, function () { var code, codeCommentsRegex, importsRegex, imports; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, readFile(fileName, 'utf-8')]; case 1: code = _a.sent(); codeCommentsRegex = /(\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\/)|(\/\/.*)/g; code = code.replace(codeCommentsRegex, ''); importsRegex = /import "([^"]*)";/g; imports = matches(importsRegex, code); return [4 /*yield*/, Promise.all(imports.map(function (match) { return __awaiter(_this, void 0, void 0, function () { var p, innerCode; return __generator(this, function (_a) { switch (_a.label) { case 0: p = path.resolve(fileName, '..', match.inner); return [4 /*yield*/, getSourceCode(p)]; case 1: innerCode = _a.sent(); // remove first line containing version innerCode = innerCode.replace(/^.*\n/, ''); code = code.replace(match.full, innerCode); return [2 /*return*/]; } }); }); }))]; case 2: _a.sent(); return [2 /*return*/, code]; } }); }); }
javascript
{ "resource": "" }
q12254
Manager
train
function Manager(options) { this.roleGetters_ = {}; this.entityGetters_ = {}; this.actionDefs_ = {}; this.options = { pauseStream: true }; if (options) { for (var option in this.options) { if (options.hasOwnProperty(option)) { this.options[option] = options[option]; } } } }
javascript
{ "resource": "" }
q12255
triggerResize
train
function triggerResize(callback) { const { animateContent, checked } = callback.getState() if ((animateContent === 'height' && checked) || (animateContent === 'marginTop' && !checked)) { callback() } }
javascript
{ "resource": "" }
q12256
train
function () { if(this.data.debug){ console.log('Initialized preloader'); } if(this.data.type === 'bootstrap' && typeof $ === 'undefined'){ console.error('jQuery is not present, cannot instantiate Bootstrap modal for preloader!'); } document.querySelector('a-assets').addEventListener('loaded',function(){ if(this.data.debug){ console.info('All assets loaded'); } this.triggerProgressComplete(); }.bind(this)); var assetItems = document.querySelectorAll('a-assets a-asset-item,a-assets img,a-assets audio,a-assets video'); this.totalAssetCount = assetItems.length; this.watchPreloadProgress(assetItems); if(!this.data.target && this.data.autoInject){ if(this.data.debug){ console.info('No preloader html found, auto-injecting'); } this.injectHTML(); }else{ switch(this.data.type){ case 'bootstrap': this.initBootstrapModal($(this.data.target)); break; default: //do nothing break; } } if(this.data.disableVRModeUI){ this.sceneEl.setAttribute('vr-mode-ui','enabled','false'); } }
javascript
{ "resource": "" }
q12257
getHandlersFromArgs
train
function getHandlersFromArgs(args, start) { assert.ok(args); args = Array.prototype.slice.call(args, start); function process(handlers, acc) { if (handlers.length === 0) { return acc; } var head = handlers.shift(); if (Array.isArray(head)) { return process(head.concat(handlers), acc); } else { assert.func(head, 'handler'); acc.push(head); return process(handlers, acc); } } return process(args, []); }
javascript
{ "resource": "" }
q12258
Router
train
function Router() { // Routes with all verbs var routes = {}; methods.forEach(function (method) { routes[method] = []; }); this.routes = routes; this.commonHandlers = []; this.routers = []; }
javascript
{ "resource": "" }
q12259
tasks
train
function tasks(options) { options = options || {}; var fp = path.resolve(options.template); var tmpl = new utils.File({path: fp, contents: fs.readFileSync(fp)}); var data = {tasks: []}; return utils.through.obj(function(file, enc, next) { var description = options.description || file.stem; if (typeof description === 'function') { description = options.description(file); } data.tasks.push({ alias: 'gitignore', path: path.relative(path.resolve('generators'), file.path), name: file.stem.toLowerCase(), description: description, relative: file.relative, basename: '.gitignore' }); next(); }, function(next) { tmpl.data = data; this.push(tmpl); next(); }); }
javascript
{ "resource": "" }
q12260
train
function (evt) { let state = this.data.holdState // api change in A-Frame v0.8.0 if (evt.detail === state || evt.detail.state === state) { this.el.body.allowSleep = false } }
javascript
{ "resource": "" }
q12261
dispatch
train
function dispatch(context, event, args) { var date = new Date() for (var i = 0; i < listeners.length; i++) listeners[i](context, event, date, args) }
javascript
{ "resource": "" }
q12262
train
function (successCallback, errorCallback, options) { argscheck.checkArgs('fFO', 'GPSLocation.getCurrentPosition', arguments); options = parseParameters(options); var id = utils.createUUID(); // Tell device to get a position ASAP, and also retrieve a reference to the timeout timer generated in getCurrentPosition timers[id] = GPSLocation.getCurrentPosition(successCallback, errorCallback, options); var fail = function (e) { clearTimeout(timers[id].timer); var err = new PositionError(e.code, e.message); if (errorCallback) { errorCallback(err); } }; var win = function (p) { clearTimeout(timers[id].timer); if (options.timeout !== Infinity) { timers[id].timer = createTimeout(fail, options.timeout); } var pos = new Position({ latitude: p.latitude, longitude: p.longitude, altitude: p.altitude, accuracy: p.accuracy, heading: p.heading, velocity: p.velocity, altitudeAccuracy: p.altitudeAccuracy }, (p.timestamp === undefined ? new Date() : ((p.timestamp instanceof Date) ? p.timestamp : new Date(p.timestamp)))); GPSLocation.lastPosition = pos; successCallback(pos); }; exec(win, fail, "GPSLocation", "addWatch", [id]); return id; }
javascript
{ "resource": "" }
q12263
base64toBlob
train
function base64toBlob(base64Data, contentType, sliceSize) { contentType = contentType || ''; sliceSize = sliceSize || 512; var byteCharacters = atob(base64Data); var byteArrays = []; for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) { var slice = byteCharacters.slice(offset, offset + sliceSize); var byteNumbers = new Array(slice.length); for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } return new Blob(byteArrays, {type: contentType}); }
javascript
{ "resource": "" }
q12264
train
function(file, $canvas, callback) { this.newImage(); if (!file) return; var reader = new FileReader(); reader.onload = function (fileReaderEvent) { image.onload = function () { readImageToCanvasOnLoad(this, $canvas, callback); }; image.src = fileReaderEvent.target.result; // The URL from FileReader }; reader.readAsDataURL(file); }
javascript
{ "resource": "" }
q12265
encryptAndSeal
train
function encryptAndSeal(plainText, AAD, nonce, key) { const cipherText = Sodium .crypto_stream_chacha20_xor_ic(plainText, nonce, 1, key); const hmac = computePoly1305(cipherText, AAD, nonce, key); return [ cipherText, hmac ]; }
javascript
{ "resource": "" }
q12266
train
function (param1, param2, param3) { var pc = new OriginalRTCPeerConnection(param1, param2, param3); window.webdriverRTCPeerConnectionBucket = pc; return pc; }
javascript
{ "resource": "" }
q12267
getVariables
train
function getVariables(configName, variableNames) { return Promise.all(variableNames.map(function(variableName) { return getVariable(configName, variableName); })); }
javascript
{ "resource": "" }
q12268
getVariable
train
function getVariable(configName, variableName) { return new Promise(function(resolve, reject) { auth().then(function(authClient) { const projectId = process.env.GCLOUD_PROJECT; const fullyQualifiedName = 'projects/' + projectId + '/configs/' + configName + '/variables/' + variableName; runtimeConfig.projects.configs.variables.get({ auth: authClient, name: fullyQualifiedName, }, function(err, res) { if (err) { reject(err); return; } const variable = res.data; if (typeof variable.text !== 'undefined') { resolve(variable.text); } else if (typeof variable.value !== 'undefined') { resolve(Buffer.from(variable.value, 'base64').toString()); } else { reject(new Error('Property text or value not defined')); } }); }); }); }
javascript
{ "resource": "" }
q12269
train
function() { // choose from the sub-protocols if (typeof self.options.handleProtocols == 'function') { var protList = (protocols || '').split(/, */); var callbackCalled = false; self.options.handleProtocols(protList, function(result, protocol) { callbackCalled = true; if (!result) abortConnection(socket, 401, 'Unauthorized'); else completeHybiUpgrade2(protocol); }); if (!callbackCalled) { // the handleProtocols handler never called our callback abortConnection(socket, 501, 'Could not process protocols'); } return; } else { if (typeof protocols !== 'undefined') { completeHybiUpgrade2(protocols.split(/, */)[0]); } else { completeHybiUpgrade2(); } } }
javascript
{ "resource": "" }
q12270
internalAssert
train
function internalAssert(condition, message) { if (!condition) { throw new AssertionError({ message, actual: false, expected: true, operator: '==' }); } }
javascript
{ "resource": "" }
q12271
isStackOverflowError
train
function isStackOverflowError(err) { if (maxStack_ErrorMessage === undefined) { try { function overflowStack() { overflowStack(); } overflowStack(); } catch (err) { maxStack_ErrorMessage = err.message; maxStack_ErrorName = err.name; } } return err.name === maxStack_ErrorName && err.message === maxStack_ErrorMessage; }
javascript
{ "resource": "" }
q12272
train
function (config) { winston.Transport.call(this, config); /** @property {string} name - the name of the transport */ this.name = 'SplunkStreamEvent'; /** @property {string} level - the minimum level to log */ this.level = config.level || 'info'; // Verify that we actually have a splunk object and a token if (!config.splunk || !config.splunk.token) { throw new Error('Invalid Configuration: options.splunk is invalid'); } // If source/sourcetype are mentioned in the splunk object, then store the // defaults in this and delete from the splunk object this.defaultMetadata = { source: 'winston', sourcetype: 'winston-splunk-logger' }; if (config.splunk.source) { this.defaultMetadata.source = config.splunk.source; delete config.splunk.source; } if (config.splunk.sourcetype) { this.defaultMetadata.sourcetype = config.splunk.sourcetype; delete config.splunk.sourcetype; } // This gets around a problem with setting maxBatchCount config.splunk.maxBatchCount = 1; this.server = new SplunkLogger(config.splunk); // Override the default event formatter if (config.splunk.eventFormatter) { this.server.eventFormatter = config.splunk.eventFormatter; } }
javascript
{ "resource": "" }
q12273
regexize
train
function regexize (rulesToRemove) { var rulesRegexes = [] for (var i = 0, l = rulesToRemove.length; i < l; i++) { if (typeof rulesToRemove[i] === 'string') { rulesRegexes.push(new RegExp('^\\s*' + escapeRegExp(rulesToRemove[i]) + '\\s*$')) } else { rulesRegexes.push(rulesToRemove[i]) } } return rulesRegexes }
javascript
{ "resource": "" }
q12274
concatRegexes
train
function concatRegexes (regexes) { var rconcat = '' if (Array.isArray(regexes)) { for (var i = 0, l = regexes.length; i < l; i++) { rconcat += regexes[i].source + '|' } rconcat = rconcat.substr(0, rconcat.length - 1) return new RegExp(rconcat) } }
javascript
{ "resource": "" }
q12275
train
function (ctx, next) { var filter; if (ctx.args && ctx.args.filter) { filter = ctx.args.filter.where; } if (!ctx.res._headerSent) { this.count(filter, function (err, count) { ctx.res.set('X-Total-Count', count); next(); }); } else { next(); } }
javascript
{ "resource": "" }
q12276
configureFilters
train
function configureFilters(config){ if (typeof config.minPeakHeight !== 'number' || isNaN(config.minPeakHeight)){ throw new TypeError('config.minPeakHeight should be a numeric value. Was: ' + String(config.minPeakHeight)); } this.filters.push(function minHeightFilter(item){ return item >= config.minPeakHeight; }); }
javascript
{ "resource": "" }
q12277
filterDataItem
train
function filterDataItem(item){ return this.filters.some(function(filter){ return filter.call(null, item); }) ? item : null; }
javascript
{ "resource": "" }
q12278
WebpackLaravelMixManifest
train
function WebpackLaravelMixManifest({ filename = null, transform = null } = {}) { this.filename = filename ? filename : 'mix-manifest.json'; this.transform = transform instanceof Function ? transform : require('./transform'); }
javascript
{ "resource": "" }
q12279
objectMapper
train
function objectMapper(originalData, y, i){ return this.getItem({ x: this.getValueX(originalData[i], i), y: y }, originalData[i], i); }
javascript
{ "resource": "" }
q12280
train
function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; process.env.NODE_ENV !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0; } return undefined; }
javascript
{ "resource": "" }
q12281
train
function (transaction) { if (this._pendingElement != null) { ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context); } else if (this._pendingStateQueue !== null || this._pendingForceUpdate) { this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); } else { this._updateBatchNumber = null; } }
javascript
{ "resource": "" }
q12282
train
function (inst, registrationName) { var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } var bankForRegistrationName = listenerBank[registrationName]; // TODO: This should never be null -- when is it? if (bankForRegistrationName) { var key = getDictionaryKey(inst); delete bankForRegistrationName[key]; } }
javascript
{ "resource": "" }
q12283
train
function (inst) { var key = getDictionaryKey(inst); for (var registrationName in listenerBank) { if (!listenerBank.hasOwnProperty(registrationName)) { continue; } if (!listenerBank[registrationName][key]) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } delete listenerBank[registrationName][key]; } }
javascript
{ "resource": "" }
q12284
batchedMountComponentIntoNode
train
function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */ !shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement); transaction.perform(mountComponentIntoNode, null, componentInstance, container, transaction, shouldReuseMarkup, context); ReactUpdates.ReactReconcileTransaction.release(transaction); }
javascript
{ "resource": "" }
q12285
hasNonRootReactChild
train
function hasNonRootReactChild(container) { var rootEl = getReactRootElementInContainer(container); if (rootEl) { var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl); return !!(inst && inst._hostParent); } }
javascript
{ "resource": "" }
q12286
train
function (nextElement, container, shouldReuseMarkup, context) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : _prodInvariant('37') : void 0; ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var componentInstance = instantiateReactComponent(nextElement, false); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context); var wrapperID = componentInstance._instance.rootID; instancesByReactRootID[wrapperID] = componentInstance; if (process.env.NODE_ENV !== 'production') { // The instance here is TopLevelWrapper so we report mount for its child. ReactInstrumentation.debugTool.onMountRootComponent(componentInstance._renderedComponent._debugID); } return componentInstance; }
javascript
{ "resource": "" }
q12287
findDOMNode
train
function findDOMNode(componentOrElement) { if (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === 1) { return componentOrElement; } var inst = ReactInstanceMap.get(componentOrElement); if (inst) { inst = getHostComponentFromComposite(inst); return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null; } if (typeof componentOrElement.render === 'function') { process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : _prodInvariant('44'); } else { process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : _prodInvariant('45', Object.keys(componentOrElement)); } }
javascript
{ "resource": "" }
q12288
train
function (callback, a, b, c, d, e) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(a, b, c, d, e); } else { transaction.perform(callback, null, a, b, c, d, e); } }
javascript
{ "resource": "" }
q12289
hasArrayNature
train
function hasArrayNature(obj) { return ( // not null/false !!obj && ( // arrays are objects, NodeLists are functions in Safari typeof obj == 'object' || typeof obj == 'function') && // quacks like an array 'length' in obj && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 typeof obj.nodeType != 'number' && ( // a real array Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); }
javascript
{ "resource": "" }
q12290
getParentInstance
train
function getParentInstance(inst) { !('_hostNode' in inst) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getParentInstance: Invalid argument.') : _prodInvariant('36') : void 0; return inst._hostParent; }
javascript
{ "resource": "" }
q12291
makeMove
train
function makeMove(child, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.MOVE_EXISTING, content: null, fromIndex: child._mountIndex, fromNode: ReactReconciler.getHostNode(child), toIndex: toIndex, afterNode: afterNode }; }
javascript
{ "resource": "" }
q12292
train
function (child, mountImage, afterNode, index, transaction, context) { child._mountIndex = index; return this.createChild(child, afterNode, mountImage); }
javascript
{ "resource": "" }
q12293
train
function (child, node) { var update = this.removeChild(child, node); child._mountIndex = null; return update; }
javascript
{ "resource": "" }
q12294
train
function (parentInst, updates) { var node = ReactDOMComponentTree.getNodeFromInstance(parentInst); DOMChildrenOperations.processUpdates(node, updates); }
javascript
{ "resource": "" }
q12295
train
function(msg) { if (window.console && window.console.error) { window.console.error(msg); } else { log(msg); } }
javascript
{ "resource": "" }
q12296
makeFunctionWrapper
train
function makeFunctionWrapper(original, functionName) { //log("wrap fn: " + functionName); var f = original[functionName]; return function() { //log("call: " + functionName); var result = f.apply(original, arguments); return result; }; }
javascript
{ "resource": "" }
q12297
makeLostContextFunctionWrapper
train
function makeLostContextFunctionWrapper(ctx, functionName) { var f = ctx[functionName]; return function() { // log("calling:" + functionName); // Only call the functions if the context is not lost. loseContextIfTime(); if (!contextLost_) { //if (!checkResources(arguments)) { // glErrorShadow_[wrappedContext_.INVALID_OPERATION] = true; // return; //} var result = f.apply(ctx, arguments); return result; } }; }
javascript
{ "resource": "" }
q12298
train
function (config) { // at this stage, the `db` variable should not exist. expecting fresh setup or post teardown setup. if (Transaction.databases[config.identity]) { // @todo - emit wrror event instead of console.log console.log('Warn: duplicate setup of connection found in Transactions.setup'); this.teardown(); } var _db; // clone the configuration config = util.clone(config); delete config.replication; // allow special transaction related config util.each(config, function (value, name, config) { if (!/^transaction.+/g.test(name)) { return; } // remove transaction config prefix var baseName = name.replace(/^transaction/g, ''); baseName = baseName.charAt(0).toLowerCase() + baseName.slice(1); delete config[name]; config[baseName] = value; }); _db = db.createSource(config); // Save a few configurations _db && (_db.transactionConfig = { rollbackOnError: config.rollbackTransactionOnError }); Transaction.databases[config.identity] = _db; }
javascript
{ "resource": "" }
q12299
train
function () { // just to be sure! clear all items in the connections object. they should be cleared by now util.each(this.connections, function (value, prop, conns) { try { value.release(); } catch (e) { } // nothing to do with error delete conns[prop]; }); // now execute end on the databases. will end pool if pool, or otherwise will execute whatever // `end` that has been exposed by db.js util.each(Transaction.databases, function (value, prop, databases) { value.end(); databases[prop] = null; }); }
javascript
{ "resource": "" }